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, 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;
38 private boolean running;
40 private volatile boolean loadInProgress;
43 public ChatMessageChannel(
45 Producer<String, MessageTo> producer,
46 Consumer<String, MessageTo> 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, MessageTo> record =
86 chatRoomId.toString(),
87 MessageTo.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, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
169 log.info("Fetched {} messages", records.count());
173 loadMessages(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 loadMessages(ConsumerRecords<String, MessageTo> records)
203 for (ConsumerRecord<String, MessageTo> record : records)
205 nextOffset[record.partition()] = record.offset() + 1;
206 UUID chatRoomId = UUID.fromString(record.key());
207 MessageTo messageTo = record.value();
209 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
211 Instant instant = Instant.ofEpochSecond(record.timestamp());
212 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
214 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
216 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
217 if (chatRoom == null)
219 // Alles pausieren und erst von putChatRoom wieder resumen lassen!
221 KafkaChatRoomService kafkaChatRoomService =
222 (KafkaChatRoomService) chatRoom.getChatRoomService();
224 kafkaChatRoomService.persistMessage(message);
228 boolean isLoadingCompleted()
232 .filter(shard -> isShardOwned[shard])
233 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
236 void pauseAllOwnedPartions()
238 consumer.pause(IntStream
240 .filter(shard -> isShardOwned[shard])
241 .mapToObj(shard -> new TopicPartition(topic, shard))
246 void putChatRoom(ChatRoom chatRoom)
248 Integer partition = chatRoom.getShard();
249 UUID chatRoomId = chatRoom.getId();
250 if (chatrooms[partition].containsKey(chatRoomId))
252 log.warn("Ignoring existing chat-room: " + chatRoom);
257 "Adding new chat-room to partition {}: {}",
261 chatrooms[partition].put(chatRoomId, chatRoom);
265 Mono<ChatRoom> getChatRoom(int shard, UUID id)
267 return Mono.justOrEmpty(chatrooms[shard].get(id));
270 Flux<ChatRoom> getChatRooms()
272 return Flux.fromStream(IntStream
274 .filter(shard -> isShardOwned[shard])
275 .mapToObj(shard -> Integer.valueOf(shard))
276 .flatMap(shard -> chatrooms[shard].values().stream()));