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.RecordDeserializationException;
16 import org.apache.kafka.common.errors.WakeupException;
17 import reactor.core.publisher.Flux;
18 import reactor.core.publisher.Mono;
21 import java.util.Collection;
22 import java.util.List;
24 import java.util.UUID;
25 import java.util.stream.IntStream;
29 public class ChatMessageChannel implements Runnable, ConsumerRebalanceListener
31 private final String topic;
32 private final Consumer<String, MessageTo> consumer;
33 private final Producer<String, MessageTo> producer;
34 private final ZoneId zoneId;
35 private final int numShards;
36 private final boolean[] isShardOwned;
37 private final long[] currentOffset;
38 private final long[] nextOffset;
39 private final Map<UUID, ChatRoom>[] chatrooms;
40 private final KafkaLikeShardingStrategy shardingStrategy;
42 private boolean running;
44 private volatile boolean loadInProgress;
47 public ChatMessageChannel(
49 Consumer<String, MessageTo> consumer,
50 Producer<String, MessageTo> producer,
55 "Creating ChatMessageChannel for topic {} with {} partitions",
59 this.consumer = consumer;
60 this.producer = producer;
62 this.numShards = numShards;
63 this.isShardOwned = new boolean[numShards];
64 this.currentOffset = new long[numShards];
65 this.nextOffset = new long[numShards];
66 this.chatrooms = new Map[numShards];
67 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
71 Mono<Message> sendMessage(
73 Message.MessageKey key,
74 LocalDateTime timestamp,
77 int shard = this.shardingStrategy.selectShard(chatRoomId);
78 TopicPartition tp = new TopicPartition(topic, shard);
79 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
80 return Mono.create(sink ->
82 ProducerRecord<String, MessageTo> record =
87 chatRoomId.toString(),
88 MessageTo.of(key.getUsername(), key.getMessageId(), text));
90 producer.send(record, ((metadata, exception) ->
95 Message message = new Message(key, metadata.offset(), timestamp, text);
96 log.info("Successfully send message {}", message);
97 sink.success(message);
103 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
109 sink.error(exception);
116 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
118 log.info("Newly assigned partitions! Pausing normal operations...");
119 loadInProgress = true;
121 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
123 int partition = topicPartition.partition();
124 isShardOwned[partition] = true;
125 this.currentOffset[partition] = currentOffset;
128 "Partition assigned: {} - loading messages: next={} -> current={}",
130 nextOffset[partition],
133 consumer.seek(topicPartition, nextOffset[partition]);
136 consumer.resume(partitions);
140 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
142 partitions.forEach(topicPartition ->
144 int partition = topicPartition.partition();
145 isShardOwned[partition] = false;
146 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
151 public void onPartitionsLost(Collection<TopicPartition> partitions)
153 log.warn("Lost partitions: {}, partitions");
154 // TODO: Muss auf den Verlust anders reagiert werden?
155 onPartitionsRevoked(partitions);
161 consumer.subscribe(List.of(topic));
169 ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
170 log.info("Fetched {} messages", records.count());
174 loadMessages(records);
176 if (isLoadingCompleted())
178 log.info("Loading of messages completed! Pausing all owned partitions...");
179 pauseAllOwnedPartions();
180 log.info("Resuming normal operations...");
181 loadInProgress = false;
186 if (!records.isEmpty())
188 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
192 catch (WakeupException e)
194 log.info("Received WakeupException, exiting!");
200 void loadMessages(ConsumerRecords<String, MessageTo> records)
202 for (ConsumerRecord<String, MessageTo> record : records)
204 nextOffset[record.partition()] = record.offset() + 1;
205 UUID chatRoomId = UUID.fromString(record.key());
206 MessageTo messageTo = record.value();
208 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
210 Instant instant = Instant.ofEpochSecond(record.timestamp());
211 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
213 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
215 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
216 if (chatRoom == null)
218 // Alles pausieren und erst von putChatRoom wieder resumen lassen!
220 KafkaChatRoomService kafkaChatRoomService =
221 (KafkaChatRoomService) chatRoom.getChatRoomService();
223 kafkaChatRoomService.persistMessage(message);
227 boolean isLoadingCompleted()
231 .filter(shard -> isShardOwned[shard])
232 .mapToObj(shard -> nextOffset[shard] >= currentOffset[shard])
234 () -> Boolean.TRUE, // TODO: Boolean is immutable
235 (acc, v) -> Boolean.valueOf(acc && v), // TODO: Boolean is immutable
236 (a, b) -> Boolean.valueOf(a && b)); // TODO: Boolean is immutable
239 void pauseAllOwnedPartions()
241 consumer.pause(IntStream
243 .filter(shard -> isShardOwned[shard])
244 .mapToObj(shard -> new TopicPartition(topic, shard))
249 void putChatRoom(ChatRoom chatRoom)
251 Integer partition = chatRoom.getShard();
252 UUID chatRoomId = chatRoom.getId();
253 if (chatrooms[partition].containsKey(chatRoomId))
255 log.warn("Ignoring existing chat-room: " + chatRoom);
260 "Adding new chat-room to partition {}: {}",
264 chatrooms[partition].put(chatRoomId, chatRoom);
268 Mono<ChatRoom> getChatRoom(int shard, UUID id)
270 return Mono.justOrEmpty(chatrooms[shard].get(id));
273 Flux<ChatRoom> getChatRooms(int shard)
275 return Flux.fromStream(chatrooms[shard].values().stream());