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);
72 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
74 log.info("Newly assigned partitions! Pausing normal operations...");
75 loadInProgress = true;
77 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
79 int partition = topicPartition.partition();
80 isShardOwned[partition] = true;
81 this.currentOffset[partition] = currentOffset;
84 "Partition assigned: {} - loading messages: next={} -> current={}",
86 nextOffset[partition],
89 consumer.seek(topicPartition, nextOffset[partition]);
92 consumer.resume(partitions);
96 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
98 partitions.forEach(topicPartition ->
100 int partition = topicPartition.partition();
101 isShardOwned[partition] = false;
102 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
107 public void onPartitionsLost(Collection<TopicPartition> partitions)
109 log.warn("Lost partitions: {}, partitions");
110 // TODO: Muss auf den Verlust anders reagiert werden?
111 onPartitionsRevoked(partitions);
117 consumer.subscribe(List.of(topic));
125 ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
126 log.info("Fetched {} messages", records.count());
130 loadMessages(records);
132 if (isLoadingCompleted())
134 log.info("Loading of messages completed! Pausing all owned partitions...");
135 pauseAllOwnedPartions();
136 log.info("Resuming normal operations...");
137 loadInProgress = false;
142 if (!records.isEmpty())
144 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
148 catch (WakeupException e)
151 catch (RecordDeserializationException e)
157 void loadMessages(ConsumerRecords<String, MessageTo> records)
159 for (ConsumerRecord<String, MessageTo> record : records)
161 nextOffset[record.partition()] = record.offset() + 1;
162 UUID chatRoomId = UUID.fromString(record.key());
163 MessageTo messageTo = record.value();
165 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
167 Instant instant = Instant.ofEpochSecond(record.timestamp());
168 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
170 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
172 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
173 if (chatRoom == null)
175 // Alles pausieren und erst von putChatRoom wieder resumen lassen!
177 KafkaChatRoomService kafkaChatRoomService =
178 (KafkaChatRoomService) chatRoom.getChatRoomService();
180 kafkaChatRoomService.persistMessage(message);
184 boolean isLoadingCompleted()
188 .filter(shard -> isShardOwned[shard])
189 .mapToObj(shard -> nextOffset[shard] >= currentOffset[shard])
191 () -> Boolean.TRUE, // TODO: Boolean is immutable
192 (acc, v) -> Boolean.valueOf(acc && v), // TODO: Boolean is immutable
193 (a, b) -> Boolean.valueOf(a && b)); // TODO: Boolean is immutable
196 void pauseAllOwnedPartions()
198 consumer.pause(IntStream
200 .filter(shard -> isShardOwned[shard])
201 .mapToObj(shard -> new TopicPartition(topic, shard))
205 Mono<Message> sendMessage(
207 Message.MessageKey key,
208 LocalDateTime timestamp,
211 int shard = this.shardingStrategy.selectShard(chatRoomId);
212 TopicPartition tp = new TopicPartition(topic, shard);
213 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
214 return Mono.create(sink ->
216 ProducerRecord<String, MessageTo> record =
217 new ProducerRecord<>(
221 chatRoomId.toString(),
222 MessageTo.of(key.getUsername(), key.getMessageId(), text));
224 producer.send(record, ((metadata, exception) ->
226 if (metadata != null)
228 // On successful send
229 Message message = new Message(key, metadata.offset(), timestamp, text);
230 log.info("Successfully send message {}", message);
231 sink.success(message);
237 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
243 sink.error(exception);
250 void putChatRoom(ChatRoom chatRoom)
252 Integer partition = chatRoom.getShard();
253 UUID chatRoomId = chatRoom.getId();
254 if (chatrooms[partition].containsKey(chatRoomId))
256 log.warn("Ignoring existing chat-room: " + chatRoom);
261 "Adding new chat-room to partition {}: {}",
265 chatrooms[partition].put(chatRoomId, chatRoom);
269 Mono<ChatRoom> getChatRoom(int shard, UUID id)
271 return Mono.justOrEmpty(chatrooms[shard].get(id));
274 Flux<ChatRoom> getChatRooms(int shard)
276 return Flux.fromStream(chatrooms[shard].values().stream());