NEU
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / persistence / kafka / ChatMessageChannel.java
1 package de.juplo.kafka.chat.backend.persistence.kafka;
2
3 import de.juplo.kafka.chat.backend.domain.ChatRoom;
4 import de.juplo.kafka.chat.backend.domain.Message;
5 import de.juplo.kafka.chat.backend.persistence.KafkaLikeShardingStrategy;
6 import lombok.Getter;
7 import lombok.extern.slf4j.Slf4j;
8 import org.apache.kafka.clients.consumer.Consumer;
9 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
10 import org.apache.kafka.clients.consumer.ConsumerRecord;
11 import org.apache.kafka.clients.consumer.ConsumerRecords;
12 import org.apache.kafka.clients.producer.Producer;
13 import org.apache.kafka.clients.producer.ProducerRecord;
14 import org.apache.kafka.common.TopicPartition;
15 import org.apache.kafka.common.errors.WakeupException;
16 import reactor.core.publisher.Flux;
17 import reactor.core.publisher.Mono;
18
19 import java.time.*;
20 import java.util.Collection;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.UUID;
24 import java.util.stream.IntStream;
25
26
27 @Slf4j
28 public class ChatMessageChannel implements Runnable, ConsumerRebalanceListener
29 {
30   private final String topic;
31   private final Producer<String, MessageTo> producer;
32   private final Consumer<String, MessageTo> consumer;
33   private final ZoneId zoneId;
34   private final int numShards;
35   private final boolean[] isShardOwned;
36   private final long[] currentOffset;
37   private final long[] nextOffset;
38   private final Map<UUID, ChatRoom>[] chatrooms;
39   private final KafkaLikeShardingStrategy shardingStrategy;
40
41   private boolean running;
42   @Getter
43   private volatile boolean loadInProgress;
44
45
46   public ChatMessageChannel(
47     String topic,
48     Producer<String, MessageTo> producer,
49     Consumer<String, MessageTo> consumer,
50     ZoneId zoneId,
51     int numShards)
52   {
53     log.debug(
54         "Creating ChatMessageChannel for topic {} with {} partitions",
55         topic,
56         numShards);
57     this.topic = topic;
58     this.consumer = consumer;
59     this.producer = producer;
60     this.zoneId = zoneId;
61     this.numShards = numShards;
62     this.isShardOwned = new boolean[numShards];
63     this.currentOffset = new long[numShards];
64     this.nextOffset = new long[numShards];
65     this.chatrooms = new Map[numShards];
66     this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
67   }
68
69
70   Mono<Message> sendMessage(
71       UUID chatRoomId,
72       Message.MessageKey key,
73       LocalDateTime timestamp,
74       String text)
75   {
76     int shard = this.shardingStrategy.selectShard(chatRoomId);
77     TopicPartition tp = new TopicPartition(topic, shard);
78     ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
79     return Mono.create(sink ->
80     {
81       ProducerRecord<String, MessageTo> record =
82           new ProducerRecord<>(
83               tp.topic(),
84               tp.partition(),
85               zdt.toEpochSecond(),
86               chatRoomId.toString(),
87               MessageTo.of(key.getUsername(), key.getMessageId(), text));
88
89       producer.send(record, ((metadata, exception) ->
90       {
91         if (metadata != null)
92         {
93           // On successful send
94           Message message = new Message(key, metadata.offset(), timestamp, text);
95           log.info("Successfully send message {}", message);
96           sink.success(message);
97         }
98         else
99         {
100           // On send-failure
101           log.error(
102               "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
103               chatRoomId,
104               key,
105               timestamp,
106               text,
107               exception);
108           sink.error(exception);
109         }
110       }));
111     });
112   }
113
114   @Override
115   public void onPartitionsAssigned(Collection<TopicPartition> partitions)
116   {
117     log.info("Newly assigned partitions! Pausing normal operations...");
118     loadInProgress = true;
119
120     consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
121     {
122       int partition = topicPartition.partition();
123       isShardOwned[partition] =  true;
124       this.currentOffset[partition] = currentOffset;
125
126       log.info(
127           "Partition assigned: {} - loading messages: next={} -> current={}",
128           partition,
129           nextOffset[partition],
130           currentOffset);
131
132       consumer.seek(topicPartition, nextOffset[partition]);
133     });
134
135     consumer.resume(partitions);
136   }
137
138   @Override
139   public void onPartitionsRevoked(Collection<TopicPartition> partitions)
140   {
141     partitions.forEach(topicPartition ->
142     {
143       int partition = topicPartition.partition();
144       isShardOwned[partition] = false;
145       log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
146     });
147   }
148
149   @Override
150   public void onPartitionsLost(Collection<TopicPartition> partitions)
151   {
152     log.warn("Lost partitions: {}, partitions");
153     // TODO: Muss auf den Verlust anders reagiert werden?
154     onPartitionsRevoked(partitions);
155   }
156
157   @Override
158   public void run()
159   {
160     consumer.subscribe(List.of(topic));
161
162     running = true;
163
164     while (running)
165     {
166       try
167       {
168         ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
169         log.info("Fetched {} messages", records.count());
170
171         if (loadInProgress)
172         {
173           loadMessages(records);
174
175           if (isLoadingCompleted())
176           {
177             log.info("Loading of messages completed! Pausing all owned partitions...");
178             pauseAllOwnedPartions();
179             log.info("Resuming normal operations...");
180             loadInProgress = false;
181           }
182         }
183         else
184         {
185           if (!records.isEmpty())
186           {
187             throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
188           }
189         }
190       }
191       catch (WakeupException e)
192       {
193         log.info("Received WakeupException, exiting!");
194         running = false;
195       }
196     }
197   }
198
199   void loadMessages(ConsumerRecords<String, MessageTo> records)
200   {
201     for (ConsumerRecord<String, MessageTo> record : records)
202     {
203       nextOffset[record.partition()] = record.offset() + 1;
204       UUID chatRoomId = UUID.fromString(record.key());
205       MessageTo messageTo = record.value();
206
207       Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
208
209       Instant instant = Instant.ofEpochSecond(record.timestamp());
210       LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
211
212       Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
213
214       ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
215       if (chatRoom == null)
216       {
217         // Alles pausieren und erst von putChatRoom wieder resumen lassen!
218       }
219       KafkaChatRoomService kafkaChatRoomService =
220           (KafkaChatRoomService) chatRoom.getChatRoomService();
221
222       kafkaChatRoomService.persistMessage(message);
223     }
224   }
225
226   boolean isLoadingCompleted()
227   {
228     return IntStream
229         .range(0, numShards)
230         .filter(shard -> isShardOwned[shard])
231         .mapToObj(shard -> nextOffset[shard] >= currentOffset[shard])
232         .collect(
233             () -> Boolean.TRUE, // TODO: Boolean is immutable
234             (acc, v) -> Boolean.valueOf(acc && v), // TODO: Boolean is immutable
235             (a, b) -> Boolean.valueOf(a && b)); // TODO: Boolean is immutable
236   }
237
238   void pauseAllOwnedPartions()
239   {
240     consumer.pause(IntStream
241         .range(0, numShards)
242         .filter(shard -> isShardOwned[shard])
243         .mapToObj(shard -> new TopicPartition(topic, shard))
244         .toList());
245   }
246
247
248   void putChatRoom(ChatRoom chatRoom)
249   {
250     Integer partition = chatRoom.getShard();
251     UUID chatRoomId = chatRoom.getId();
252     if (chatrooms[partition].containsKey(chatRoomId))
253     {
254       log.warn("Ignoring existing chat-room: " + chatRoom);
255     }
256     else
257     {
258       log.info(
259           "Adding new chat-room to partition {}: {}",
260           partition,
261           chatRoom);
262
263       chatrooms[partition].put(chatRoomId, chatRoom);
264     }
265   }
266
267   Mono<ChatRoom> getChatRoom(int shard, UUID id)
268   {
269     return Mono.justOrEmpty(chatrooms[shard].get(id));
270   }
271
272   Flux<ChatRoom> getChatRooms()
273   {
274     return Flux.fromStream(IntStream
275         .range(0, numShards)
276         .filter(shard -> isShardOwned[shard])
277         .mapToObj(shard -> Integer.valueOf(shard))
278         .flatMap(shard -> chatrooms[shard].values().stream()));
279   }
280 }