138d9a7b706bfab4c01f2933e9502109a1b483ef
[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.*;
21 import java.util.stream.IntStream;
22
23
24 @Slf4j
25 public class ChatMessageChannel implements Runnable, ConsumerRebalanceListener
26 {
27   private final String topic;
28   private final Producer<String, MessageTo> producer;
29   private final Consumer<String, MessageTo> consumer;
30   private final ZoneId zoneId;
31   private final int numShards;
32   private final boolean[] isShardOwned;
33   private final long[] currentOffset;
34   private final long[] nextOffset;
35   private final Map<UUID, ChatRoom>[] chatrooms;
36   private final KafkaLikeShardingStrategy shardingStrategy;
37
38   private boolean running;
39   @Getter
40   private volatile boolean loadInProgress;
41
42
43   public ChatMessageChannel(
44     String topic,
45     Producer<String, MessageTo> producer,
46     Consumer<String, MessageTo> consumer,
47     ZoneId zoneId,
48     int numShards)
49   {
50     log.debug(
51         "Creating ChatMessageChannel for topic {} with {} partitions",
52         topic,
53         numShards);
54     this.topic = topic;
55     this.consumer = consumer;
56     this.producer = producer;
57     this.zoneId = zoneId;
58     this.numShards = numShards;
59     this.isShardOwned = new boolean[numShards];
60     this.currentOffset = new long[numShards];
61     this.nextOffset = new long[numShards];
62     this.chatrooms = new Map[numShards];
63     IntStream
64         .range(0, numShards)
65         .forEach(shard -> this.chatrooms[shard] = new HashMap<>());
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), this);
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     log.info("Exiting normally");
199   }
200
201   void loadMessages(ConsumerRecords<String, MessageTo> records)
202   {
203     for (ConsumerRecord<String, MessageTo> record : records)
204     {
205       nextOffset[record.partition()] = record.offset() + 1;
206       UUID chatRoomId = UUID.fromString(record.key());
207       MessageTo messageTo = record.value();
208
209       Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
210
211       Instant instant = Instant.ofEpochSecond(record.timestamp());
212       LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
213
214       Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
215
216       ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
217       if (chatRoom == null)
218       {
219         // TODO: Alles pausieren und erst von putChatRoom wieder resumen lassen!
220       }
221       KafkaChatRoomService kafkaChatRoomService =
222           (KafkaChatRoomService) chatRoom.getChatRoomService();
223
224       kafkaChatRoomService.persistMessage(message);
225     }
226   }
227
228   boolean isLoadingCompleted()
229   {
230     return IntStream
231         .range(0, numShards)
232         .filter(shard -> isShardOwned[shard])
233         .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
234   }
235
236   void pauseAllOwnedPartions()
237   {
238     consumer.pause(IntStream
239         .range(0, numShards)
240         .filter(shard -> isShardOwned[shard])
241         .mapToObj(shard -> new TopicPartition(topic, shard))
242         .toList());
243   }
244
245
246   void putChatRoom(ChatRoom chatRoom)
247   {
248     Integer partition = chatRoom.getShard();
249     UUID chatRoomId = chatRoom.getId();
250     if (chatrooms[partition].containsKey(chatRoomId))
251     {
252       log.warn("Ignoring existing chat-room: " + chatRoom);
253     }
254     else
255     {
256       log.info(
257           "Adding new chat-room to partition {}: {}",
258           partition,
259           chatRoom);
260
261       chatrooms[partition].put(chatRoomId, chatRoom);
262     }
263   }
264
265   Mono<ChatRoom> getChatRoom(int shard, UUID id)
266   {
267     return Mono.justOrEmpty(chatrooms[shard].get(id));
268   }
269
270   Flux<ChatRoom> getChatRooms()
271   {
272     return Flux.fromStream(IntStream
273         .range(0, numShards)
274         .filter(shard -> isShardOwned[shard])
275         .mapToObj(shard -> Integer.valueOf(shard))
276         .flatMap(shard -> chatrooms[shard].values().stream()));
277   }
278 }