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.Message;
5 import de.juplo.kafka.chat.backend.persistence.KafkaLikeShardingStrategy;
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 boolean[] isShardOwned;
33 private final long[] currentOffset;
34 private final long[] nextOffset;
35 private final Map<UUID, ChatRoom>[] chatrooms;
36 private final KafkaLikeShardingStrategy shardingStrategy;
38 private boolean running;
40 private volatile boolean loadInProgress;
43 public ChatMessageChannel(
45 Producer<String, AbstractTo> producer,
46 Consumer<String, AbstractTo> consumer,
51 "Creating ChatMessageChannel for topic {} with {} partitions",
55 this.consumer = consumer;
56 this.producer = producer;
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];
65 .forEach(shard -> this.chatrooms[shard] = new HashMap<>());
66 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
70 Mono<Message> sendMessage(
72 Message.MessageKey key,
73 LocalDateTime timestamp,
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 ->
81 ProducerRecord<String, ChatMessageTo> record =
86 chatRoomId.toString(),
87 ChatMessageTo.of(key.getUsername(), key.getMessageId(), text));
89 producer.send(record, ((metadata, exception) ->
94 Message message = new Message(key, metadata.offset(), timestamp, text);
95 log.info("Successfully send message {}", message);
96 sink.success(message);
102 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
108 sink.error(exception);
115 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
117 log.info("Newly assigned partitions! Pausing normal operations...");
118 loadInProgress = true;
120 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
122 int partition = topicPartition.partition();
123 isShardOwned[partition] = true;
124 this.currentOffset[partition] = currentOffset;
127 "Partition assigned: {} - loading messages: next={} -> current={}",
129 nextOffset[partition],
132 consumer.seek(topicPartition, nextOffset[partition]);
135 consumer.resume(partitions);
139 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
141 partitions.forEach(topicPartition ->
143 int partition = topicPartition.partition();
144 isShardOwned[partition] = false;
145 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
150 public void onPartitionsLost(Collection<TopicPartition> partitions)
152 log.warn("Lost partitions: {}, partitions");
153 // TODO: Muss auf den Verlust anders reagiert werden?
154 onPartitionsRevoked(partitions);
160 consumer.subscribe(List.of(topic), this);
168 ConsumerRecords<String, AbstractTo> records = consumer.poll(Duration.ofMinutes(5));
169 log.info("Fetched {} messages", records.count());
173 loadChatRoom(records);
175 if (isLoadingCompleted())
177 log.info("Loading of messages completed! Pausing all owned partitions...");
178 pauseAllOwnedPartions();
179 log.info("Resuming normal operations...");
180 loadInProgress = false;
185 if (!records.isEmpty())
187 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
191 catch (WakeupException e)
193 log.info("Received WakeupException, exiting!");
198 log.info("Exiting normally");
201 void loadChatRoom(ConsumerRecords<String, AbstractTo> records)
203 for (ConsumerRecord<String, AbstractTo> record : records)
205 switch (record.value().getType())
207 case CREATE_CHATROOM_REQUEST:
208 createChatRoom((CreateChatRoomRequestTo) record.value());
212 UUID chatRoomId = UUID.fromString(record.key());
213 Instant instant = Instant.ofEpochSecond(record.timestamp());
214 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
219 (ChatMessageTo) record.value(),
224 nextOffset[record.partition()] = record.offset() + 1;
229 CreateChatRoomRequestTo createChatRoomRequestTo,
232 chatrooms[partition].put
235 void loadChatMessage(
237 LocalDateTime timestamp,
239 ChatMessageTo chatMessageTo,
242 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
243 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
245 ChatRoom chatRoom = chatrooms[partition].get(chatRoomId);
246 KafkaChatRoomService kafkaChatRoomService =
247 (KafkaChatRoomService) chatRoom.getChatRoomService();
249 kafkaChatRoomService.persistMessage(message);
252 boolean isLoadingCompleted()
256 .filter(shard -> isShardOwned[shard])
257 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
260 void pauseAllOwnedPartions()
262 consumer.pause(IntStream
264 .filter(shard -> isShardOwned[shard])
265 .mapToObj(shard -> new TopicPartition(topic, shard))
270 void putChatRoom(ChatRoom chatRoom)
272 Integer partition = chatRoom.getShard();
273 UUID chatRoomId = chatRoom.getId();
274 if (chatrooms[partition].containsKey(chatRoomId))
276 log.warn("Ignoring existing chat-room: " + chatRoom);
281 "Adding new chat-room to partition {}: {}",
285 chatrooms[partition].put(chatRoomId, chatRoom);
289 Mono<ChatRoom> getChatRoom(int shard, UUID id)
291 return Mono.justOrEmpty(chatrooms[shard].get(id));
294 Flux<ChatRoom> getChatRooms()
296 return Flux.fromStream(IntStream
298 .filter(shard -> isShardOwned[shard])
299 .mapToObj(shard -> Integer.valueOf(shard))
300 .flatMap(shard -> chatrooms[shard].values().stream()));