1 package de.juplo.kafka.chat.backend.persistence.kafka;
3 import de.juplo.kafka.chat.backend.domain.ChatRoom;
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.persistence.KafkaLikeShardingStrategy;
8 import lombok.extern.slf4j.Slf4j;
9 import org.apache.kafka.clients.consumer.Consumer;
10 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
11 import org.apache.kafka.clients.consumer.ConsumerRecord;
12 import org.apache.kafka.clients.consumer.ConsumerRecords;
13 import org.apache.kafka.clients.producer.Producer;
14 import org.apache.kafka.clients.producer.ProducerRecord;
15 import org.apache.kafka.common.TopicPartition;
16 import org.apache.kafka.common.errors.WakeupException;
17 import reactor.core.publisher.Flux;
18 import reactor.core.publisher.Mono;
22 import java.util.stream.IntStream;
26 public class ChatMessageChannel implements Runnable, ConsumerRebalanceListener
28 private final String topic;
29 private final Producer<String, AbstractTo> producer;
30 private final Consumer<String, AbstractTo> consumer;
31 private final ZoneId zoneId;
32 private final int numShards;
33 private final boolean[] isShardOwned;
34 private final long[] currentOffset;
35 private final long[] nextOffset;
36 private final Map<UUID, ChatRoom>[] chatrooms;
37 private final KafkaLikeShardingStrategy shardingStrategy;
39 private boolean running;
41 private volatile boolean loadInProgress;
44 public ChatMessageChannel(
46 Producer<String, AbstractTo> producer,
47 Consumer<String, AbstractTo> consumer,
52 "Creating ChatMessageChannel for topic {} with {} partitions",
56 this.consumer = consumer;
57 this.producer = producer;
59 this.numShards = numShards;
60 this.isShardOwned = new boolean[numShards];
61 this.currentOffset = new long[numShards];
62 this.nextOffset = new long[numShards];
63 this.chatrooms = new Map[numShards];
66 .forEach(shard -> this.chatrooms[shard] = new HashMap<>());
67 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
72 Mono<ChatRoomInfo> sendCreateChatRoomRequest(
76 CreateChatRoomRequestTo createChatRoomRequestTo = CreateChatRoomRequestTo.of(name);
77 return Mono.create(sink ->
79 ProducerRecord<String, CreateChatRoomRequestTo> record =
82 chatRoomId.toString(),
83 createChatRoomRequestTo);
85 producer.send(record, ((metadata, exception) ->
89 log.info("Successfully send chreate-request for chat room: {}", createChatRoomRequestTo);
90 ChatRoomInfo chatRoomInfo = ChatRoomInfo.of(chatRoomId, name, record.partition());
91 createChatRoom(chatRoomInfo);
92 sink.success(chatRoomInfo);
98 "Could not send create-request for chat room (id={}, name={}): {}",
102 sink.error(exception);
108 Mono<Message> sendChatMessage(
110 Message.MessageKey key,
111 LocalDateTime timestamp,
114 int shard = this.shardingStrategy.selectShard(chatRoomId);
115 TopicPartition tp = new TopicPartition(topic, shard);
116 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
117 return Mono.create(sink ->
119 ProducerRecord<String, ChatMessageTo> record =
120 new ProducerRecord<>(
124 chatRoomId.toString(),
125 ChatMessageTo.of(key.getUsername(), key.getMessageId(), text));
127 producer.send(record, ((metadata, exception) ->
129 if (metadata != null)
131 // On successful send
132 Message message = new Message(key, metadata.offset(), timestamp, text);
133 log.info("Successfully send message {}", message);
134 sink.success(message);
140 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
146 sink.error(exception);
153 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
155 log.info("Newly assigned partitions! Pausing normal operations...");
156 loadInProgress = true;
158 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
160 int partition = topicPartition.partition();
161 isShardOwned[partition] = true;
162 this.currentOffset[partition] = currentOffset;
165 "Partition assigned: {} - loading messages: next={} -> current={}",
167 nextOffset[partition],
170 consumer.seek(topicPartition, nextOffset[partition]);
173 consumer.resume(partitions);
177 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
179 partitions.forEach(topicPartition ->
181 int partition = topicPartition.partition();
182 isShardOwned[partition] = false;
183 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
188 public void onPartitionsLost(Collection<TopicPartition> partitions)
190 log.warn("Lost partitions: {}, partitions");
191 // TODO: Muss auf den Verlust anders reagiert werden?
192 onPartitionsRevoked(partitions);
198 consumer.subscribe(List.of(topic), this);
206 ConsumerRecords<String, AbstractTo> records = consumer.poll(Duration.ofMinutes(5));
207 log.info("Fetched {} messages", records.count());
211 loadChatRoom(records);
213 if (isLoadingCompleted())
215 log.info("Loading of messages completed! Pausing all owned partitions...");
216 pauseAllOwnedPartions();
217 log.info("Resuming normal operations...");
218 loadInProgress = false;
223 if (!records.isEmpty())
225 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
229 catch (WakeupException e)
231 log.info("Received WakeupException, exiting!");
236 log.info("Exiting normally");
239 void loadChatRoom(ConsumerRecords<String, AbstractTo> records)
241 for (ConsumerRecord<String, AbstractTo> record : records)
243 UUID chatRoomId = UUID.fromString(record.key());
245 switch (record.value().getType())
247 case CREATE_CHATROOM_REQUEST:
250 (CreateChatRoomRequestTo) record.value(),
255 Instant instant = Instant.ofEpochSecond(record.timestamp());
256 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
261 (ChatMessageTo) record.value(),
266 nextOffset[record.partition()] = record.offset() + 1;
272 CreateChatRoomRequestTo createChatRoomRequestTo,
275 putChatRoom(ChatRoomInfo.of(
277 createChatRoomRequestTo.getName(),
282 void createChatRoom(ChatRoomInfo chatRoomInfo)
284 UUID id = chatRoomInfo.getId();
285 String name = chatRoomInfo.getName();
286 int shard = chatRoomInfo.getShard();
287 log.info("Creating ChatRoom {} with buffer-size {}", id, bufferSize);
288 KafkaChatRoomService service = new KafkaChatRoomService(this, id);
289 ChatRoom chatRoom = new ChatRoom(id, name, shard, clock, service, bufferSize);
290 putChatRoom(chatRoom);
293 void loadChatMessage(
295 LocalDateTime timestamp,
297 ChatMessageTo chatMessageTo,
300 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
301 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
303 ChatRoom chatRoom = chatrooms[partition].get(chatRoomId);
304 KafkaChatRoomService kafkaChatRoomService =
305 (KafkaChatRoomService) chatRoom.getChatRoomService();
307 kafkaChatRoomService.persistMessage(message);
310 boolean isLoadingCompleted()
314 .filter(shard -> isShardOwned[shard])
315 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
318 void pauseAllOwnedPartions()
320 consumer.pause(IntStream
322 .filter(shard -> isShardOwned[shard])
323 .mapToObj(shard -> new TopicPartition(topic, shard))
328 private void putChatRoom(ChatRoom chatRoom)
330 Integer partition = chatRoom.getShard();
331 UUID chatRoomId = chatRoom.getId();
332 if (chatrooms[partition].containsKey(chatRoomId))
334 log.warn("Ignoring existing chat-room: " + chatRoom);
339 "Adding new chat-room to partition {}: {}",
343 chatrooms[partition].put(chatRoomId, chatRoom);
347 Mono<ChatRoom> getChatRoom(int shard, UUID id)
349 return Mono.justOrEmpty(chatrooms[shard].get(id));
352 Flux<ChatRoom> getChatRooms()
354 return Flux.fromStream(IntStream
356 .filter(shard -> isShardOwned[shard])
357 .mapToObj(shard -> Integer.valueOf(shard))
358 .flatMap(shard -> chatrooms[shard].values().stream()));