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.concurrent.Callable;
22 import java.util.stream.IntStream;
26 public class ChatMessageChannel implements Callable<Optional<Exception>>, ConsumerRebalanceListener
28 private final String topic;
29 private final Producer<String, MessageTo> producer;
30 private final Consumer<String, MessageTo> consumer;
31 private final ZoneId zoneId;
32 private final int numShards;
33 private final boolean[] isShardOwned;
34 private final long[] currentOffset;
35 private final long[] nextOffset;
36 private final Map<UUID, ChatRoom>[] chatrooms;
37 private final KafkaLikeShardingStrategy shardingStrategy;
39 private boolean running;
41 private volatile boolean loadInProgress;
44 public ChatMessageChannel(
46 Producer<String, MessageTo> producer,
47 Consumer<String, MessageTo> consumer,
52 "Creating ChatMessageChannel for topic {} with {} partitions",
56 this.consumer = consumer;
57 this.producer = producer;
59 this.numShards = numShards;
60 this.isShardOwned = new boolean[numShards];
61 this.currentOffset = new long[numShards];
62 this.nextOffset = new long[numShards];
63 this.chatrooms = new Map[numShards];
64 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
68 Mono<Message> sendMessage(
70 Message.MessageKey key,
71 LocalDateTime timestamp,
74 int shard = this.shardingStrategy.selectShard(chatRoomId);
75 TopicPartition tp = new TopicPartition(topic, shard);
76 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
77 return Mono.create(sink ->
79 ProducerRecord<String, MessageTo> record =
84 chatRoomId.toString(),
85 MessageTo.of(key.getUsername(), key.getMessageId(), text));
87 producer.send(record, ((metadata, exception) ->
92 Message message = new Message(key, metadata.offset(), timestamp, text);
93 log.info("Successfully send message {}", message);
94 sink.success(message);
100 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
106 sink.error(exception);
113 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
115 log.info("Newly assigned partitions! Pausing normal operations...");
116 loadInProgress = true;
118 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
120 int partition = topicPartition.partition();
121 isShardOwned[partition] = true;
122 this.currentOffset[partition] = currentOffset;
125 "Partition assigned: {} - loading messages: next={} -> current={}",
127 nextOffset[partition],
130 consumer.seek(topicPartition, nextOffset[partition]);
133 consumer.resume(partitions);
137 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
139 partitions.forEach(topicPartition ->
141 int partition = topicPartition.partition();
142 isShardOwned[partition] = false;
143 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
148 public void onPartitionsLost(Collection<TopicPartition> partitions)
150 log.warn("Lost partitions: {}, partitions");
151 // TODO: Muss auf den Verlust anders reagiert werden?
152 onPartitionsRevoked(partitions);
156 public Optional<Exception> call()
158 consumer.subscribe(List.of(topic));
166 ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
167 log.info("Fetched {} messages", records.count());
171 loadMessages(records);
173 if (isLoadingCompleted())
175 log.info("Loading of messages completed! Pausing all owned partitions...");
176 pauseAllOwnedPartions();
177 log.info("Resuming normal operations...");
178 loadInProgress = false;
183 if (!records.isEmpty())
185 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
189 catch (WakeupException e)
191 log.info("Received WakeupException, exiting!");
196 log.error("Exiting abnormally!");
197 return Optional.of(e);
201 log.info("Exiting normally");
202 return Optional.empty();
205 void loadMessages(ConsumerRecords<String, MessageTo> records)
207 for (ConsumerRecord<String, MessageTo> record : records)
209 nextOffset[record.partition()] = record.offset() + 1;
210 UUID chatRoomId = UUID.fromString(record.key());
211 MessageTo messageTo = record.value();
213 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
215 Instant instant = Instant.ofEpochSecond(record.timestamp());
216 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
218 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
220 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
221 if (chatRoom == null)
223 // Alles pausieren und erst von putChatRoom wieder resumen lassen!
225 KafkaChatRoomService kafkaChatRoomService =
226 (KafkaChatRoomService) chatRoom.getChatRoomService();
228 kafkaChatRoomService.persistMessage(message);
232 boolean isLoadingCompleted()
236 .filter(shard -> isShardOwned[shard])
237 .mapToObj(shard -> nextOffset[shard] >= currentOffset[shard])
239 () -> Boolean.TRUE, // TODO: Boolean is immutable
240 (acc, v) -> Boolean.valueOf(acc && v), // TODO: Boolean is immutable
241 (a, b) -> Boolean.valueOf(a && b)); // TODO: Boolean is immutable
244 void pauseAllOwnedPartions()
246 consumer.pause(IntStream
248 .filter(shard -> isShardOwned[shard])
249 .mapToObj(shard -> new TopicPartition(topic, shard))
254 void putChatRoom(ChatRoom chatRoom)
256 Integer partition = chatRoom.getShard();
257 UUID chatRoomId = chatRoom.getId();
258 if (chatrooms[partition].containsKey(chatRoomId))
260 log.warn("Ignoring existing chat-room: " + chatRoom);
265 "Adding new chat-room to partition {}: {}",
269 chatrooms[partition].put(chatRoomId, chatRoom);
273 Mono<ChatRoom> getChatRoom(int shard, UUID id)
275 return Mono.justOrEmpty(chatrooms[shard].get(id));
278 Flux<ChatRoom> getChatRooms()
280 return Flux.fromStream(IntStream
282 .filter(shard -> isShardOwned[shard])
283 .mapToObj(shard -> Integer.valueOf(shard))
284 .flatMap(shard -> chatrooms[shard].values().stream()));