32a57206a061bbaa7c807649bdcb477a22c3c8f7
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / implementation / kafka / DataChannel.java
1 package de.juplo.kafka.chat.backend.implementation.kafka;
2
3 import de.juplo.kafka.chat.backend.domain.ChatRoomData;
4 import de.juplo.kafka.chat.backend.domain.ChatRoomInfo;
5 import de.juplo.kafka.chat.backend.domain.Message;
6 import de.juplo.kafka.chat.backend.domain.ShardingPublisherStrategy;
7 import de.juplo.kafka.chat.backend.domain.exceptions.ShardNotOwnedException;
8 import de.juplo.kafka.chat.backend.implementation.kafka.messages.AbstractMessageTo;
9 import de.juplo.kafka.chat.backend.implementation.kafka.messages.data.EventChatMessageReceivedTo;
10 import lombok.Getter;
11 import lombok.ToString;
12 import lombok.extern.slf4j.Slf4j;
13 import org.apache.kafka.clients.consumer.*;
14 import org.apache.kafka.clients.producer.Producer;
15 import org.apache.kafka.clients.producer.ProducerRecord;
16 import org.apache.kafka.common.TopicPartition;
17 import org.apache.kafka.common.errors.WakeupException;
18 import reactor.core.publisher.Mono;
19
20 import java.time.*;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.UUID;
25 import java.util.stream.IntStream;
26
27
28 @ToString(of = { "topic", "instanceId" })
29 @Slf4j
30 public class DataChannel implements Channel, ConsumerRebalanceListener
31 {
32   private final String instanceId;
33   private final String topic;
34   private final Producer<String, AbstractMessageTo> producer;
35   private final Consumer<String, AbstractMessageTo> consumer;
36   private final ZoneId zoneId;
37   private final int numShards;
38   private final Duration pollingInterval;
39   private final int historyLimit;
40   private final Clock clock;
41   private final boolean[] isShardOwned;
42   private final long[] currentOffset;
43   private final long[] nextOffset;
44   private final Map<UUID, ChatRoomData>[] chatRoomData;
45   private final ChannelMediator channelMediator;
46   private final ShardingPublisherStrategy shardingPublisherStrategy;
47
48   private boolean running;
49   @Getter
50   private volatile ChannelState channelState = ChannelState.STARTING;
51
52
53   public DataChannel(
54     String instanceId,
55     String topic,
56     Producer<String, AbstractMessageTo> producer,
57     Consumer<String, AbstractMessageTo> dataChannelConsumer,
58     ZoneId zoneId,
59     int numShards,
60     Duration pollingInterval,
61     int historyLimit,
62     Clock clock,
63     ChannelMediator channelMediator,
64     ShardingPublisherStrategy shardingPublisherStrategy)
65   {
66     log.debug(
67         "{}: Creating DataChannel for topic {} with {} partitions",
68         instanceId,
69         topic,
70         numShards);
71     this.instanceId = instanceId;
72     this.topic = topic;
73     this.consumer = dataChannelConsumer;
74     this.producer = producer;
75     this.zoneId = zoneId;
76     this.numShards = numShards;
77     this.pollingInterval = pollingInterval;
78     this.historyLimit = historyLimit;
79     this.clock = clock;
80     this.isShardOwned = new boolean[numShards];
81     this.currentOffset = new long[numShards];
82     this.nextOffset = new long[numShards];
83     this.chatRoomData = new Map[numShards];
84     IntStream
85         .range(0, numShards)
86         .forEach(shard -> this.chatRoomData[shard] = new HashMap<>());
87     this.channelMediator = channelMediator;
88     this.shardingPublisherStrategy = shardingPublisherStrategy;
89   }
90
91
92
93   Mono<Message> sendChatMessage(
94       UUID chatRoomId,
95       Message.MessageKey key,
96       LocalDateTime timestamp,
97       String text)
98   {
99     ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
100     return Mono.create(sink ->
101     {
102       ProducerRecord<String, AbstractMessageTo> record =
103           new ProducerRecord<>(
104               topic,
105               null,
106               zdt.toEpochSecond(),
107               chatRoomId.toString(),
108               EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
109
110       producer.send(record, ((metadata, exception) ->
111       {
112         if (exception == null)
113         {
114           // On successful send
115           Message message = new Message(key, metadata.offset(), timestamp, text);
116           log.info("Successfully send message {}", message);
117           sink.success(message);
118         }
119         else
120         {
121           // On send-failure
122           log.error(
123               "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
124               chatRoomId,
125               key,
126               timestamp,
127               text,
128               exception);
129           sink.error(exception);
130         }
131       }));
132     });
133   }
134
135   @Override
136   public void onPartitionsAssigned(Collection<TopicPartition> partitions)
137   {
138     log.info("Newly assigned partitions! Pausing normal operations...");
139     channelState = ChannelState.LOAD_IN_PROGRESS;
140
141     consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
142     {
143       int partition = topicPartition.partition();
144       isShardOwned[partition] =  true;
145       this.currentOffset[partition] = currentOffset;
146
147       chatRoomData[partition]
148           .values()
149           .forEach(chatRoomData -> chatRoomData.activate());
150
151       log.info(
152           "Partition assigned: {} - loading messages: next={} -> current={}",
153           partition,
154           nextOffset[partition],
155           currentOffset);
156
157       consumer.seek(topicPartition, nextOffset[partition]);
158       channelMediator.shardAssigned(partition);
159       shardingPublisherStrategy
160           .publishOwnership(partition)
161           .doOnSuccess(instanceId -> log.info(
162               "Successfully published instance {} as owner of shard {}",
163               instanceId,
164               partition))
165           .doOnError(throwable -> log.error(
166               "Could not publish instance {} as owner of shard {}: {}",
167               instanceId,
168               partition,
169               throwable.toString()))
170           .onErrorComplete()
171           .block();
172     });
173
174     consumer.resume(partitions);
175   }
176
177   @Override
178   public void onPartitionsRevoked(Collection<TopicPartition> partitions)
179   {
180     partitions.forEach(topicPartition ->
181     {
182       int partition = topicPartition.partition();
183       isShardOwned[partition] = false;
184       nextOffset[partition] = consumer.position(topicPartition);
185
186       log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
187
188       chatRoomData[partition]
189           .values()
190           .forEach(chatRoomData -> chatRoomData.deactivate());
191
192       channelMediator.shardRevoked(partition);
193     });
194   }
195
196   @Override
197   public void onPartitionsLost(Collection<TopicPartition> partitions)
198   {
199     log.warn("Lost partitions: {}, partitions");
200     // TODO: Muss auf den Verlust anders reagiert werden?
201     onPartitionsRevoked(partitions);
202   }
203
204   @Override
205   public void run()
206   {
207     running = true;
208
209     while (running)
210     {
211       try
212       {
213         ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(pollingInterval);
214         log.info("Fetched {} messages", records.count());
215
216         switch (channelState)
217         {
218           case LOAD_IN_PROGRESS ->
219           {
220             loadChatRoomData(records);
221
222             if (isLoadingCompleted())
223             {
224               log.info("Loading of messages completed! Pausing all owned partitions...");
225               pauseAllOwnedPartions();
226               log.info("Resuming normal operations...");
227               channelState = ChannelState.READY;
228             }
229           }
230           case SHUTTING_DOWN -> log.info("Shutdown in progress: ignoring {} fetched messages.", records.count());
231           default ->
232           {
233             if (!records.isEmpty())
234             {
235               throw new IllegalStateException("All owned partitions should be paused, when in state " + channelState);
236             }
237           }
238         }
239       }
240       catch (WakeupException e)
241       {
242         log.info("Received WakeupException, exiting!");
243         channelState = ChannelState.SHUTTING_DOWN;
244         running = false;
245       }
246     }
247
248     log.info("Exiting normally");
249   }
250
251   private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
252   {
253     for (ConsumerRecord<String, AbstractMessageTo> record : records)
254     {
255       UUID chatRoomId = UUID.fromString(record.key());
256
257       switch (record.value().getType())
258       {
259         case EVENT_CHATMESSAGE_RECEIVED:
260           Instant instant = Instant.ofEpochSecond(record.timestamp());
261           LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
262           loadChatMessage(
263               chatRoomId,
264               timestamp,
265               record.offset(),
266               (EventChatMessageReceivedTo) record.value(),
267               record.partition());
268           break;
269
270         default:
271           log.debug(
272               "Ignoring message for chat-room {} with offset {}: {}",
273               chatRoomId,
274               record.offset(),
275               record.value());
276       }
277
278       nextOffset[record.partition()] = record.offset() + 1;
279     }
280   }
281
282   private void loadChatMessage(
283       UUID chatRoomId,
284       LocalDateTime timestamp,
285       long offset,
286       EventChatMessageReceivedTo chatMessageTo,
287       int partition)
288   {
289     Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
290     Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
291
292     ChatRoomData chatRoomData = computeChatRoomData(chatRoomId, partition);
293     KafkaChatMessageService kafkaChatRoomService =
294         (KafkaChatMessageService) chatRoomData.getChatRoomService();
295
296     log.debug(
297         "Loaded message from partition={} at offset={}: {}",
298         partition,
299         offset,
300         message);
301     kafkaChatRoomService.persistMessage(message);
302   }
303
304   private boolean isLoadingCompleted()
305   {
306     return IntStream
307         .range(0, numShards)
308         .filter(shard -> isShardOwned[shard])
309         .allMatch(shard ->
310         {
311           TopicPartition partition = new TopicPartition(topic, shard);
312           long position = consumer.position(partition);
313           return position >= currentOffset[shard];
314         });
315   }
316
317   private void pauseAllOwnedPartions()
318   {
319     consumer.pause(IntStream
320         .range(0, numShards)
321         .filter(shard -> isShardOwned[shard])
322         .mapToObj(shard -> new TopicPartition(topic, shard))
323         .toList());
324   }
325
326
327   int[] getOwnedShards()
328   {
329     return IntStream
330         .range(0, numShards)
331         .filter(shard -> isShardOwned[shard])
332         .toArray();
333   }
334
335   void createChatRoomData(ChatRoomInfo chatRoomInfo)
336   {
337     ChatRoomData chatRoomData = computeChatRoomData(
338         chatRoomInfo.getId(),
339         chatRoomInfo.getShard());
340     chatRoomData.activate();
341   }
342
343   Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
344   {
345     ChannelState capturedState = channelState;
346     if (capturedState != ChannelState.READY)
347     {
348       return Mono.error(new ChannelNotReadyException(capturedState));
349     }
350
351     if (!isShardOwned[shard])
352     {
353       return Mono.error(new ShardNotOwnedException(instanceId, shard));
354     }
355
356     return Mono.justOrEmpty(chatRoomData[shard].get(id));
357   }
358
359   private ChatRoomData computeChatRoomData(UUID chatRoomId, int shard)
360   {
361     ChatRoomData chatRoomData = this.chatRoomData[shard].get(chatRoomId);
362
363     if (chatRoomData != null)
364     {
365       log.info(
366           "Ignoring request to create already existing ChatRoomData for {}",
367           chatRoomId);
368     }
369     else
370     {
371       log.info("Creating ChatRoomData {} with history-limit {}", chatRoomId, historyLimit);
372       KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
373       chatRoomData = new ChatRoomData(clock, service, historyLimit);
374       this.chatRoomData[shard].put(chatRoomId, chatRoomData);
375     }
376
377     return chatRoomData;
378   }
379
380   ConsumerGroupMetadata getConsumerGroupMetadata()
381   {
382     return consumer.groupMetadata();
383   }
384 }