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];
63 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
67 Mono<Message> sendMessage(
69 Message.MessageKey key,
70 LocalDateTime timestamp,
73 int shard = this.shardingStrategy.selectShard(chatRoomId);
74 TopicPartition tp = new TopicPartition(topic, shard);
75 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
76 return Mono.create(sink ->
78 ProducerRecord<String, MessageTo> record =
83 chatRoomId.toString(),
84 MessageTo.of(key.getUsername(), key.getMessageId(), text));
86 producer.send(record, ((metadata, exception) ->
91 Message message = new Message(key, metadata.offset(), timestamp, text);
92 log.info("Successfully send message {}", message);
93 sink.success(message);
99 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
105 sink.error(exception);
112 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
114 log.info("Newly assigned partitions! Pausing normal operations...");
115 loadInProgress = true;
117 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
119 int partition = topicPartition.partition();
120 isShardOwned[partition] = true;
121 this.currentOffset[partition] = currentOffset;
124 "Partition assigned: {} - loading messages: next={} -> current={}",
126 nextOffset[partition],
129 consumer.seek(topicPartition, nextOffset[partition]);
132 consumer.resume(partitions);
136 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
138 partitions.forEach(topicPartition ->
140 int partition = topicPartition.partition();
141 isShardOwned[partition] = false;
142 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
147 public void onPartitionsLost(Collection<TopicPartition> partitions)
149 log.warn("Lost partitions: {}, partitions");
150 // TODO: Muss auf den Verlust anders reagiert werden?
151 onPartitionsRevoked(partitions);
157 consumer.subscribe(List.of(topic), this);
165 ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
166 log.info("Fetched {} messages", records.count());
170 loadMessages(records);
172 if (isLoadingCompleted())
174 log.info("Loading of messages completed! Pausing all owned partitions...");
175 pauseAllOwnedPartions();
176 log.info("Resuming normal operations...");
177 loadInProgress = false;
182 if (!records.isEmpty())
184 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
188 catch (WakeupException e)
190 log.info("Received WakeupException, exiting!");
195 log.info("Exiting normally");
198 void loadMessages(ConsumerRecords<String, MessageTo> records)
200 for (ConsumerRecord<String, MessageTo> record : records)
202 nextOffset[record.partition()] = record.offset() + 1;
203 UUID chatRoomId = UUID.fromString(record.key());
204 MessageTo messageTo = record.value();
206 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
208 Instant instant = Instant.ofEpochSecond(record.timestamp());
209 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
211 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
213 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
214 if (chatRoom == null)
216 // Alles pausieren und erst von putChatRoom wieder resumen lassen!
218 KafkaChatRoomService kafkaChatRoomService =
219 (KafkaChatRoomService) chatRoom.getChatRoomService();
221 kafkaChatRoomService.persistMessage(message);
225 boolean isLoadingCompleted()
229 .filter(shard -> isShardOwned[shard])
230 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
233 void pauseAllOwnedPartions()
235 consumer.pause(IntStream
237 .filter(shard -> isShardOwned[shard])
238 .mapToObj(shard -> new TopicPartition(topic, shard))
243 void putChatRoom(ChatRoom chatRoom)
245 Integer partition = chatRoom.getShard();
246 UUID chatRoomId = chatRoom.getId();
247 if (chatrooms[partition].containsKey(chatRoomId))
249 log.warn("Ignoring existing chat-room: " + chatRoom);
254 "Adding new chat-room to partition {}: {}",
258 chatrooms[partition].put(chatRoomId, chatRoom);
262 Mono<ChatRoom> getChatRoom(int shard, UUID id)
264 return Mono.justOrEmpty(chatrooms[shard].get(id));
267 Flux<ChatRoom> getChatRooms()
269 return Flux.fromStream(IntStream
271 .filter(shard -> isShardOwned[shard])
272 .mapToObj(shard -> Integer.valueOf(shard))
273 .flatMap(shard -> chatrooms[shard].values().stream()));