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;
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;
21 import java.util.stream.IntStream;
25 public class ChatMessageChannel implements Runnable, ConsumerRebalanceListener
27 private final String topic;
28 private final Producer<String, AbstractTo> producer;
29 private final Consumer<String, AbstractTo> consumer;
30 private final ZoneId zoneId;
31 private final int numShards;
32 private final int bufferSize;
33 private final Clock clock;
34 private final boolean[] isShardOwned;
35 private final long[] currentOffset;
36 private final long[] nextOffset;
37 private final Map<UUID, ChatRoom>[] chatrooms;
39 private boolean running;
41 private volatile boolean loadInProgress;
44 public ChatMessageChannel(
46 Producer<String, AbstractTo> producer,
47 Consumer<String, AbstractTo> consumer,
54 "Creating ChatMessageChannel for topic {} with {} partitions",
58 this.consumer = consumer;
59 this.producer = producer;
61 this.numShards = numShards;
62 this.bufferSize = bufferSize;
64 this.isShardOwned = new boolean[numShards];
65 this.currentOffset = new long[numShards];
66 this.nextOffset = new long[numShards];
67 this.chatrooms = new Map[numShards];
70 .forEach(shard -> this.chatrooms[shard] = new HashMap<>());
75 Mono<ChatRoomInfo> sendCreateChatRoomRequest(
79 CreateChatRoomRequestTo createChatRoomRequestTo = CreateChatRoomRequestTo.of(name);
80 return Mono.create(sink ->
82 ProducerRecord<String, CreateChatRoomRequestTo> record =
85 chatRoomId.toString(),
86 createChatRoomRequestTo);
88 producer.send(record, ((metadata, exception) ->
92 log.info("Successfully send chreate-request for chat room: {}", createChatRoomRequestTo);
93 ChatRoomInfo chatRoomInfo = ChatRoomInfo.of(chatRoomId, name, record.partition());
94 createChatRoom(chatRoomInfo);
95 sink.success(chatRoomInfo);
101 "Could not send create-request for chat room (id={}, name={}): {}",
105 sink.error(exception);
111 Mono<Message> sendChatMessage(
113 Message.MessageKey key,
114 LocalDateTime timestamp,
117 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
118 return Mono.create(sink ->
120 ProducerRecord<String, AbstractTo> record =
121 new ProducerRecord<>(
125 chatRoomId.toString(),
126 ChatMessageTo.of(key.getUsername(), key.getMessageId(), text));
128 producer.send(record, ((metadata, exception) ->
130 if (metadata != null)
132 // On successful send
133 Message message = new Message(key, metadata.offset(), timestamp, text);
134 log.info("Successfully send message {}", message);
135 sink.success(message);
141 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
147 sink.error(exception);
154 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
156 log.info("Newly assigned partitions! Pausing normal operations...");
157 loadInProgress = true;
159 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
161 int partition = topicPartition.partition();
162 isShardOwned[partition] = true;
163 this.currentOffset[partition] = currentOffset;
166 "Partition assigned: {} - loading messages: next={} -> current={}",
168 nextOffset[partition],
171 consumer.seek(topicPartition, nextOffset[partition]);
174 consumer.resume(partitions);
178 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
180 partitions.forEach(topicPartition ->
182 int partition = topicPartition.partition();
183 isShardOwned[partition] = false;
184 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
189 public void onPartitionsLost(Collection<TopicPartition> partitions)
191 log.warn("Lost partitions: {}, partitions");
192 // TODO: Muss auf den Verlust anders reagiert werden?
193 onPartitionsRevoked(partitions);
199 consumer.subscribe(List.of(topic), this);
207 ConsumerRecords<String, AbstractTo> records = consumer.poll(Duration.ofMinutes(5));
208 log.info("Fetched {} messages", records.count());
212 loadChatRoom(records);
214 if (isLoadingCompleted())
216 log.info("Loading of messages completed! Pausing all owned partitions...");
217 pauseAllOwnedPartions();
218 log.info("Resuming normal operations...");
219 loadInProgress = false;
224 if (!records.isEmpty())
226 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
230 catch (WakeupException e)
232 log.info("Received WakeupException, exiting!");
237 log.info("Exiting normally");
240 void loadChatRoom(ConsumerRecords<String, AbstractTo> records)
242 for (ConsumerRecord<String, AbstractTo> record : records)
244 UUID chatRoomId = UUID.fromString(record.key());
246 switch (record.value().getType())
248 case CREATE_CHATROOM_REQUEST:
251 (CreateChatRoomRequestTo) record.value(),
256 Instant instant = Instant.ofEpochSecond(record.timestamp());
257 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
262 (ChatMessageTo) record.value(),
268 "Ignoring message for chat-room {} with offset {}: {}",
274 nextOffset[record.partition()] = record.offset() + 1;
280 CreateChatRoomRequestTo createChatRoomRequestTo,
283 putChatRoom(ChatRoomInfo.of(
285 createChatRoomRequestTo.getName(),
290 void createChatRoom(ChatRoomInfo chatRoomInfo)
292 UUID id = chatRoomInfo.getId();
293 String name = chatRoomInfo.getName();
294 int shard = chatRoomInfo.getShard();
295 log.info("Creating ChatRoom {} with buffer-size {}", id, bufferSize);
296 KafkaChatRoomService service = new KafkaChatRoomService(this, id);
297 ChatRoom chatRoom = new ChatRoom(id, name, shard, clock, service, bufferSize);
298 putChatRoom(chatRoom);
301 void loadChatMessage(
303 LocalDateTime timestamp,
305 ChatMessageTo chatMessageTo,
308 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
309 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
311 ChatRoom chatRoom = chatrooms[partition].get(chatRoomId);
312 KafkaChatRoomService kafkaChatRoomService =
313 (KafkaChatRoomService) chatRoom.getChatRoomService();
315 kafkaChatRoomService.persistMessage(message);
318 boolean isLoadingCompleted()
322 .filter(shard -> isShardOwned[shard])
323 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
326 void pauseAllOwnedPartions()
328 consumer.pause(IntStream
330 .filter(shard -> isShardOwned[shard])
331 .mapToObj(shard -> new TopicPartition(topic, shard))
336 private void putChatRoom(ChatRoom chatRoom)
338 Integer partition = chatRoom.getShard();
339 UUID chatRoomId = chatRoom.getId();
340 if (chatrooms[partition].containsKey(chatRoomId))
342 log.warn("Ignoring existing chat-room: " + chatRoom);
347 "Adding new chat-room to partition {}: {}",
351 chatrooms[partition].put(chatRoomId, chatRoom);
355 Mono<ChatRoom> getChatRoom(int shard, UUID id)
357 return Mono.justOrEmpty(chatrooms[shard].get(id));