1 package de.juplo.kafka.chat.backend.persistence.kafka;
3 import de.juplo.kafka.chat.backend.domain.*;
4 import de.juplo.kafka.chat.backend.persistence.kafka.messages.AbstractMessageTo;
5 import de.juplo.kafka.chat.backend.persistence.kafka.messages.CommandCreateChatRoomTo;
6 import de.juplo.kafka.chat.backend.persistence.kafka.messages.EventChatMessageReceivedTo;
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 ChatRoomChannel implements Runnable, ConsumerRebalanceListener
28 private final String topic;
29 private final Producer<String, AbstractMessageTo> producer;
30 private final Consumer<String, AbstractMessageTo> consumer;
31 private final ZoneId zoneId;
32 private final int numShards;
33 private final int bufferSize;
34 private final Clock clock;
35 private final boolean[] isShardOwned;
36 private final long[] currentOffset;
37 private final long[] nextOffset;
38 private final Map<UUID, ChatRoom>[] chatrooms;
40 private boolean running;
42 private volatile boolean loadInProgress;
45 public ChatRoomChannel(
47 Producer<String, AbstractMessageTo> producer,
48 Consumer<String, AbstractMessageTo> consumer,
55 "Creating ChatRoomChannel for topic {} with {} partitions",
59 this.consumer = consumer;
60 this.producer = producer;
62 this.numShards = numShards;
63 this.bufferSize = bufferSize;
65 this.isShardOwned = new boolean[numShards];
66 this.currentOffset = new long[numShards];
67 this.nextOffset = new long[numShards];
68 this.chatrooms = new Map[numShards];
71 .forEach(shard -> this.chatrooms[shard] = new HashMap<>());
76 Mono<ChatRoomInfo> sendCreateChatRoomRequest(
80 CommandCreateChatRoomTo createChatRoomRequestTo = CommandCreateChatRoomTo.of(name);
81 return Mono.create(sink ->
83 ProducerRecord<String, AbstractMessageTo> record =
86 chatRoomId.toString(),
87 createChatRoomRequestTo);
89 producer.send(record, ((metadata, exception) ->
93 log.info("Successfully send chreate-request for chat room: {}", createChatRoomRequestTo);
94 ChatRoomInfo chatRoomInfo = new ChatRoomInfo(chatRoomId, name, record.partition());
95 createChatRoom(chatRoomInfo);
96 sink.success(chatRoomInfo);
102 "Could not send create-request for chat room (id={}, name={}): {}",
106 sink.error(exception);
112 Mono<Message> sendChatMessage(
114 Message.MessageKey key,
115 LocalDateTime timestamp,
118 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
119 return Mono.create(sink ->
121 ProducerRecord<String, AbstractMessageTo> record =
122 new ProducerRecord<>(
126 chatRoomId.toString(),
127 EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
129 producer.send(record, ((metadata, exception) ->
131 if (metadata != null)
133 // On successful send
134 Message message = new Message(key, metadata.offset(), timestamp, text);
135 log.info("Successfully send message {}", message);
136 sink.success(message);
142 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
148 sink.error(exception);
155 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
157 log.info("Newly assigned partitions! Pausing normal operations...");
158 loadInProgress = true;
160 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
162 int partition = topicPartition.partition();
163 isShardOwned[partition] = true;
164 this.currentOffset[partition] = currentOffset;
167 "Partition assigned: {} - loading messages: next={} -> current={}",
169 nextOffset[partition],
172 consumer.seek(topicPartition, nextOffset[partition]);
175 consumer.resume(partitions);
179 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
181 partitions.forEach(topicPartition ->
183 int partition = topicPartition.partition();
184 isShardOwned[partition] = false;
185 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
190 public void onPartitionsLost(Collection<TopicPartition> partitions)
192 log.warn("Lost partitions: {}, partitions");
193 // TODO: Muss auf den Verlust anders reagiert werden?
194 onPartitionsRevoked(partitions);
206 ConsumerRecords<String, AbstractMessageTo> 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 private void loadChatRoom(ConsumerRecords<String, AbstractMessageTo> records)
241 for (ConsumerRecord<String, AbstractMessageTo> record : records)
243 UUID chatRoomId = UUID.fromString(record.key());
245 switch (record.value().getType())
247 case COMMAND_CREATE_CHATROOM:
250 (CommandCreateChatRoomTo) record.value(),
254 case EVENT_CHATMESSAGE_RECEIVED:
255 Instant instant = Instant.ofEpochSecond(record.timestamp());
256 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
261 (EventChatMessageReceivedTo) record.value(),
267 "Ignoring message for chat-room {} with offset {}: {}",
273 nextOffset[record.partition()] = record.offset() + 1;
277 private void createChatRoom(
279 CommandCreateChatRoomTo createChatRoomRequestTo,
282 log.info("Loading ChatRoom {} with buffer-size {}", chatRoomId, bufferSize);
283 KafkaChatRoomService service = new KafkaChatRoomService(this, chatRoomId);
284 ChatRoom chatRoom = new ChatRoom(
286 createChatRoomRequestTo.getName(),
291 putChatRoom(chatRoom);
295 private void createChatRoom(ChatRoomInfo chatRoomInfo)
297 UUID id = chatRoomInfo.getId();
298 String name = chatRoomInfo.getName();
299 int shard = chatRoomInfo.getShard();
300 log.info("Creating ChatRoom {} with buffer-size {}", id, bufferSize);
301 KafkaChatRoomService service = new KafkaChatRoomService(this, id);
302 ChatRoom chatRoom = new ChatRoom(id, name, shard, clock, service, bufferSize);
303 putChatRoom(chatRoom);
306 private void loadChatMessage(
308 LocalDateTime timestamp,
310 EventChatMessageReceivedTo chatMessageTo,
313 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
314 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
316 ChatRoom chatRoom = chatrooms[partition].get(chatRoomId);
317 KafkaChatRoomService kafkaChatRoomService =
318 (KafkaChatRoomService) chatRoom.getChatRoomService();
320 kafkaChatRoomService.persistMessage(message);
323 private boolean isLoadingCompleted()
327 .filter(shard -> isShardOwned[shard])
328 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
331 private void pauseAllOwnedPartions()
333 consumer.pause(IntStream
335 .filter(shard -> isShardOwned[shard])
336 .mapToObj(shard -> new TopicPartition(topic, shard))
341 private void putChatRoom(ChatRoom chatRoom)
343 Integer partition = chatRoom.getShard();
344 UUID chatRoomId = chatRoom.getId();
345 if (chatrooms[partition].containsKey(chatRoomId))
347 log.warn("Ignoring existing chat-room: " + chatRoom);
352 "Adding new chat-room to partition {}: {}",
356 chatrooms[partition].put(chatRoomId, chatRoom);
360 int[] getOwnedShards()
364 .filter(shard -> isShardOwned[shard])
368 Mono<ChatRoom> getChatRoom(int shard, UUID id)
372 return Mono.error(new LoadInProgressException());
375 if (!isShardOwned[shard])
377 return Mono.error(new ShardNotOwnedException(shard));
380 return Mono.justOrEmpty(chatrooms[shard].get(id));
383 Flux<ChatRoom> getChatRooms()
386 .fromStream(IntStream.range(0, numShards).mapToObj(i -> Integer.valueOf(i)))
387 .filter(shard -> isShardOwned[shard])
388 .flatMap(shard -> Flux.fromIterable(chatrooms[shard].values()));