query:1.0.2 - Fixed responses for availability edge-cases
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / query / QueryStreamProcessor.java
1 package de.juplo.kafka.wordcount.query;
2
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import lombok.extern.slf4j.Slf4j;
6 import org.apache.kafka.clients.consumer.ConsumerConfig;
7 import org.apache.kafka.common.serialization.Serdes;
8 import org.apache.kafka.streams.*;
9 import org.apache.kafka.streams.kstream.KStream;
10 import org.apache.kafka.streams.kstream.KTable;
11 import org.apache.kafka.streams.kstream.Materialized;
12 import org.apache.kafka.streams.state.HostInfo;
13 import org.apache.kafka.streams.state.QueryableStoreTypes;
14 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
15 import org.springframework.boot.SpringApplication;
16 import org.springframework.context.ConfigurableApplicationContext;
17 import org.springframework.stereotype.Component;
18
19 import javax.annotation.PostConstruct;
20 import javax.annotation.PreDestroy;
21 import java.net.URI;
22 import java.util.Optional;
23 import java.util.Properties;
24 import java.util.concurrent.CompletableFuture;
25
26 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
27
28
29 @Slf4j
30 @Component
31 public class QueryStreamProcessor
32 {
33         public final KafkaStreams streams;
34         public final HostInfo hostInfo;
35         public final String storeName = "rankingsByUsername";
36         public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
37         public final ObjectMapper mapper;
38
39
40         public QueryStreamProcessor(
41                         QueryApplicationProperties properties,
42                         ObjectMapper mapper,
43                         ConfigurableApplicationContext context)
44         {
45                 StreamsBuilder builder = new StreamsBuilder();
46
47                 KTable<String, String> users = builder.table(properties.getUsersInputTopic());
48                 KStream<String, String> rankings = builder.stream(properties.getRankingInputTopic());
49
50                 rankings
51                                 .join(users, (rankingJson, userJson) ->
52                                 {
53                                         try
54                                         {
55                                                 Ranking ranking = mapper.readValue(rankingJson, Ranking.class);
56                                                 User user = mapper.readValue(userJson, User.class);
57
58                                                 return mapper.writeValueAsString(
59                                                                 UserRanking.of(
60                                                                                 user.getFirstName(),
61                                                                                 user.getLastName(),
62                                                                                 ranking.getEntries()));
63                                         }
64                                         catch (JsonProcessingException e)
65                                         {
66                                                 throw new RuntimeException(e);
67                                         }
68                                 })
69                                 .toTable(Materialized.as(storeName));
70
71                 Properties props = new Properties();
72                 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
73                 props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, properties.getApplicationServer());
74                 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
75                 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
76                 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
77                 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
78
79                 streams = new KafkaStreams(builder.build(), props);
80                 streams.setUncaughtExceptionHandler((Throwable e) ->
81                 {
82                         log.error("Unexpected error!", e);
83                         CompletableFuture.runAsync(() ->
84                         {
85                                 log.info("Stopping application...");
86                                 SpringApplication.exit(context, () -> 1);
87                         });
88                         return SHUTDOWN_CLIENT;
89                 });
90
91                 hostInfo = HostInfo.buildFromEndpoint(properties.getApplicationServer());
92                 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
93                 this.mapper = mapper;
94         }
95
96         public Optional<URI> getRedirect(String username)
97         {
98                 KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
99                 HostInfo activeHost = metadata.activeHost();
100                 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
101
102                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
103                 {
104                         return Optional.empty();
105                 }
106
107                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
108                 log.debug("Redirecting to {}", location);
109                 return Optional.of(location);
110         }
111
112         public Optional<UserRanking> getUserRanking(String username)
113         {
114                 return
115                                 Optional
116                                                 .ofNullable(streams.store(storeParameters).get(username))
117                                                 .map(json ->
118                                                 {
119                                                         try
120                                                         {
121                                                                 return mapper.readValue(json, UserRanking.class);
122                                                         }
123                                                         catch (JsonProcessingException e)
124                                                         {
125                                                                 throw new RuntimeException(e);
126                                                         }
127                                                 });
128         }
129
130         @PostConstruct
131         public void start()
132         {
133                 log.info("Starting Stream-Processor");
134                 streams.start();
135         }
136
137         @PreDestroy
138         public void stop()
139         {
140                 log.info("Stopping Stream-Processor");
141                 streams.close();
142         }
143 }