feat: Introduced a configurable instance-id
[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.*;
4 import de.juplo.kafka.chat.backend.domain.exceptions.LoadInProgressException;
5 import de.juplo.kafka.chat.backend.domain.exceptions.ShardNotOwnedException;
6 import de.juplo.kafka.chat.backend.implementation.kafka.messages.AbstractMessageTo;
7 import de.juplo.kafka.chat.backend.implementation.kafka.messages.data.EventChatMessageReceivedTo;
8 import lombok.Getter;
9 import lombok.extern.slf4j.Slf4j;
10 import org.apache.kafka.clients.consumer.Consumer;
11 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
12 import org.apache.kafka.clients.consumer.ConsumerRecord;
13 import org.apache.kafka.clients.consumer.ConsumerRecords;
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.*;
22 import java.util.stream.IntStream;
23
24
25 @Slf4j
26 public class DataChannel implements Runnable, ConsumerRebalanceListener
27 {
28   private final String instanceId;
29   private final String topic;
30   private final Producer<String, AbstractMessageTo> producer;
31   private final Consumer<String, AbstractMessageTo> consumer;
32   private final ZoneId zoneId;
33   private final int numShards;
34   private final int bufferSize;
35   private final Clock clock;
36   private final boolean[] isShardOwned;
37   private final long[] currentOffset;
38   private final long[] nextOffset;
39   private final Map<UUID, ChatRoomData>[] chatRoomData;
40   private final InfoChannel infoChannel;
41
42   private boolean running;
43   @Getter
44   private volatile boolean loadInProgress;
45
46
47   public DataChannel(
48     String instanceId,
49     String topic,
50     Producer<String, AbstractMessageTo> producer,
51     Consumer<String, AbstractMessageTo> dataChannelConsumer,
52     ZoneId zoneId,
53     int numShards,
54     int bufferSize,
55     Clock clock,
56     InfoChannel infoChannel)
57   {
58     log.debug(
59         "{}: Creating DataChannel for topic {} with {} partitions",
60         instanceId,
61         topic,
62         numShards);
63     this.instanceId = instanceId;
64     this.topic = topic;
65     this.consumer = dataChannelConsumer;
66     this.producer = producer;
67     this.zoneId = zoneId;
68     this.numShards = numShards;
69     this.bufferSize = bufferSize;
70     this.clock = clock;
71     this.isShardOwned = new boolean[numShards];
72     this.currentOffset = new long[numShards];
73     this.nextOffset = new long[numShards];
74     this.chatRoomData = new Map[numShards];
75     IntStream
76         .range(0, numShards)
77         .forEach(shard -> this.chatRoomData[shard] = new HashMap<>());
78     this.infoChannel = infoChannel;
79   }
80
81
82
83   Mono<Message> sendChatMessage(
84       UUID chatRoomId,
85       Message.MessageKey key,
86       LocalDateTime timestamp,
87       String text)
88   {
89     ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
90     return Mono.create(sink ->
91     {
92       ProducerRecord<String, AbstractMessageTo> record =
93           new ProducerRecord<>(
94               topic,
95               null,
96               zdt.toEpochSecond(),
97               chatRoomId.toString(),
98               EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
99
100       producer.send(record, ((metadata, exception) ->
101       {
102         if (exception == null)
103         {
104           // On successful send
105           Message message = new Message(key, metadata.offset(), timestamp, text);
106           log.info("Successfully send message {}", message);
107           sink.success(message);
108         }
109         else
110         {
111           // On send-failure
112           log.error(
113               "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
114               chatRoomId,
115               key,
116               timestamp,
117               text,
118               exception);
119           sink.error(exception);
120         }
121       }));
122     });
123   }
124
125   @Override
126   public void onPartitionsAssigned(Collection<TopicPartition> partitions)
127   {
128     log.info("Newly assigned partitions! Pausing normal operations...");
129     loadInProgress = true;
130
131     consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
132     {
133       int partition = topicPartition.partition();
134       isShardOwned[partition] =  true;
135       this.currentOffset[partition] = currentOffset;
136
137       log.info(
138           "Partition assigned: {} - loading messages: next={} -> current={}",
139           partition,
140           nextOffset[partition],
141           currentOffset);
142
143       consumer.seek(topicPartition, nextOffset[partition]);
144       infoChannel.sendShardAssignedEvent(partition);
145     });
146
147     consumer.resume(partitions);
148   }
149
150   @Override
151   public void onPartitionsRevoked(Collection<TopicPartition> partitions)
152   {
153     partitions.forEach(topicPartition ->
154     {
155       int partition = topicPartition.partition();
156       isShardOwned[partition] = false;
157       log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
158       infoChannel.sendShardRevokedEvent(partition);
159     });
160   }
161
162   @Override
163   public void onPartitionsLost(Collection<TopicPartition> partitions)
164   {
165     log.warn("Lost partitions: {}, partitions");
166     // TODO: Muss auf den Verlust anders reagiert werden?
167     onPartitionsRevoked(partitions);
168   }
169
170   @Override
171   public void run()
172   {
173     running = true;
174
175     while (running)
176     {
177       try
178       {
179         ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(Duration.ofMinutes(1));
180         log.info("Fetched {} messages", records.count());
181
182         if (loadInProgress)
183         {
184           loadChatRoomData(records);
185
186           if (isLoadingCompleted())
187           {
188             log.info("Loading of messages completed! Pausing all owned partitions...");
189             pauseAllOwnedPartions();
190             log.info("Resuming normal operations...");
191             loadInProgress = false;
192           }
193         }
194         else
195         {
196           if (!records.isEmpty())
197           {
198             throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
199           }
200         }
201       }
202       catch (WakeupException e)
203       {
204         log.info("Received WakeupException, exiting!");
205         running = false;
206       }
207     }
208
209     log.info("Exiting normally");
210   }
211
212   private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
213   {
214     for (ConsumerRecord<String, AbstractMessageTo> record : records)
215     {
216       UUID chatRoomId = UUID.fromString(record.key());
217
218       switch (record.value().getType())
219       {
220         case EVENT_CHATMESSAGE_RECEIVED:
221           Instant instant = Instant.ofEpochSecond(record.timestamp());
222           LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
223           loadChatMessage(
224               chatRoomId,
225               timestamp,
226               record.offset(),
227               (EventChatMessageReceivedTo) record.value(),
228               record.partition());
229           break;
230
231         default:
232           log.debug(
233               "Ignoring message for chat-room {} with offset {}: {}",
234               chatRoomId,
235               record.offset(),
236               record.value());
237       }
238
239       nextOffset[record.partition()] = record.offset() + 1;
240     }
241   }
242
243   private void loadChatMessage(
244       UUID chatRoomId,
245       LocalDateTime timestamp,
246       long offset,
247       EventChatMessageReceivedTo chatMessageTo,
248       int partition)
249   {
250     Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
251     Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
252
253     ChatRoomData chatRoomData = this
254         .chatRoomData[partition]
255         .computeIfAbsent(chatRoomId, this::computeChatRoomData);
256     KafkaChatMessageService kafkaChatRoomService =
257         (KafkaChatMessageService) chatRoomData.getChatRoomService();
258
259     kafkaChatRoomService.persistMessage(message);
260   }
261
262   private boolean isLoadingCompleted()
263   {
264     return IntStream
265         .range(0, numShards)
266         .filter(shard -> isShardOwned[shard])
267         .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
268   }
269
270   private void pauseAllOwnedPartions()
271   {
272     consumer.pause(IntStream
273         .range(0, numShards)
274         .filter(shard -> isShardOwned[shard])
275         .mapToObj(shard -> new TopicPartition(topic, shard))
276         .toList());
277   }
278
279
280   int[] getOwnedShards()
281   {
282     return IntStream
283         .range(0, numShards)
284         .filter(shard -> isShardOwned[shard])
285         .toArray();
286   }
287
288   Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
289   {
290     if (loadInProgress)
291     {
292       return Mono.error(new LoadInProgressException());
293     }
294
295     if (!isShardOwned[shard])
296     {
297       return Mono.error(new ShardNotOwnedException(instanceId, shard));
298     }
299
300     return infoChannel
301         .getChatRoomInfo(id)
302         .map(chatRoomInfo ->
303             chatRoomData[shard].computeIfAbsent(id, this::computeChatRoomData));
304   }
305
306   private ChatRoomData computeChatRoomData(UUID chatRoomId)
307   {
308     log.info("Creating ChatRoom {} with buffer-size {}", chatRoomId, bufferSize);
309     KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
310     return new ChatRoomData(clock, service, bufferSize);
311   }
312 }