query: 2.0.0 - (RED) Formulated expectations for JSON-values
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / query / QueryStreamProcessor.java
index 319861d..ff7c150 100644 (file)
@@ -2,80 +2,104 @@ package de.juplo.kafka.wordcount.query;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.common.serialization.Serdes;
 import org.apache.kafka.streams.*;
+import org.apache.kafka.streams.kstream.KStream;
+import org.apache.kafka.streams.kstream.KTable;
 import org.apache.kafka.streams.kstream.Materialized;
 import org.apache.kafka.streams.state.HostInfo;
+import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
 import org.apache.kafka.streams.state.QueryableStoreTypes;
 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
-import org.springframework.boot.SpringApplication;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
 import java.net.URI;
 import java.util.Optional;
 import java.util.Properties;
-import java.util.concurrent.CompletableFuture;
-
-import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
 
 
 @Slf4j
-@Component
 public class QueryStreamProcessor
 {
+       public static final String STORE_NAME = "rankings-by-username";
+
        public final KafkaStreams streams;
        public final HostInfo hostInfo;
-       public final String storeName = "rankingsByUsername";
        public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
        public final ObjectMapper mapper;
 
 
        public QueryStreamProcessor(
-                       QueryApplicationProperties properties,
-                       ObjectMapper mapper,
-                       ConfigurableApplicationContext context)
+                       Properties props,
+                       HostInfo applicationServer,
+                       String usersInputTopic,
+                       String rankingInputTopic,
+                       KeyValueBytesStoreSupplier storeSupplier,
+                       ObjectMapper mapper)
        {
-               StreamsBuilder builder = new StreamsBuilder();
+               Topology topology = buildTopology(
+                               usersInputTopic,
+                               rankingInputTopic,
+                               storeSupplier,
+                               mapper);
+               streams = new KafkaStreams(topology, props);
+               hostInfo = applicationServer;
+               storeParameters = StoreQueryParameters.fromNameAndType(STORE_NAME, QueryableStoreTypes.keyValueStore());;
+               this.mapper = mapper;
+       }
 
-               builder.table(properties.getRankingInputTopic(), Materialized.as(storeName));
+       static Topology buildTopology(
+                       String usersInputTopic,
+                       String rankingInputTopic,
+                       KeyValueBytesStoreSupplier storeSupplier,
+                       ObjectMapper mapper)
+       {
+               StreamsBuilder builder = new StreamsBuilder();
 
-               Properties props = new Properties();
-               props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
-               props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, properties.getApplicationServer());
-               props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
-               props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
-               props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
-               props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+               KTable<String, String> users = builder.table(usersInputTopic);
+               KStream<String, String> rankings = builder.stream(rankingInputTopic);
+
+               rankings
+                               .join(users, (rankingJson, userJson) ->
+                               {
+                                       try
+                                       {
+                                               Ranking ranking = mapper.readValue(rankingJson, Ranking.class);
+                                               User user = mapper.readValue(userJson, User.class);
+
+                                               return mapper.writeValueAsString(
+                                                               UserRanking.of(
+                                                                               user.getFirstName(),
+                                                                               user.getLastName(),
+                                                                               ranking.getEntries()));
+                                       }
+                                       catch (JsonProcessingException e)
+                                       {
+                                               throw new RuntimeException(e);
+                                       }
+                               })
+                               .toTable(Materialized.as(storeSupplier));
+
+               Topology topology = builder.build();
+               log.info("\n\n{}", topology.describe());
+
+               return topology;
+       }
 
-               streams = new KafkaStreams(builder.build(), props);
-               streams.setUncaughtExceptionHandler((Throwable e) ->
-               {
-                       log.error("Unexpected error!", e);
-                       CompletableFuture.runAsync(() ->
-                       {
-                               log.info("Stopping application...");
-                               SpringApplication.exit(context, () -> 1);
-                       });
-                       return SHUTDOWN_CLIENT;
-               });
-
-               hostInfo = HostInfo.buildFromEndpoint(properties.getApplicationServer());
-               storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
-               this.mapper = mapper;
+       ReadOnlyKeyValueStore<String, UserRanking> getStore()
+       {
+               return streams.store(storeParameters);
        }
 
        public Optional<URI> getRedirect(String username)
        {
-               KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
+               KeyQueryMetadata metadata = streams.queryMetadataForKey(STORE_NAME, username, Serdes.String().serializer());
                HostInfo activeHost = metadata.activeHost();
                log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
 
-               if (activeHost.equals(this.hostInfo))
+               if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
                {
                        return Optional.empty();
                }
@@ -85,16 +109,16 @@ public class QueryStreamProcessor
                return Optional.of(location);
        }
 
-       public Optional<Ranking> getRanking(String username)
+       public Optional<UserRanking> getUserRanking(String username)
        {
                return
                                Optional
-                                               .ofNullable(streams.store(storeParameters).get(username))
+                                               .ofNullable(getStore().get(username))
                                                .map(json ->
                                                {
                                                        try
                                                        {
-                                                               return mapper.readValue(json, Ranking.class);
+                                                               return mapper.readValue(json, UserRanking.class);
                                                        }
                                                        catch (JsonProcessingException e)
                                                        {