1 package de.juplo.kafka.chat.backend.implementation.kafka;
3 import de.juplo.kafka.chat.backend.domain.ChatRoomData;
4 import de.juplo.kafka.chat.backend.domain.ChatRoomInfo;
5 import de.juplo.kafka.chat.backend.domain.Message;
6 import de.juplo.kafka.chat.backend.domain.ShardingPublisherStrategy;
7 import de.juplo.kafka.chat.backend.domain.exceptions.ShardNotOwnedException;
8 import de.juplo.kafka.chat.backend.implementation.kafka.messages.AbstractMessageTo;
9 import de.juplo.kafka.chat.backend.implementation.kafka.messages.data.EventChatMessageReceivedTo;
11 import lombok.ToString;
12 import lombok.extern.slf4j.Slf4j;
13 import org.apache.kafka.clients.consumer.*;
14 import org.apache.kafka.clients.producer.Producer;
15 import org.apache.kafka.clients.producer.ProducerRecord;
16 import org.apache.kafka.common.TopicPartition;
17 import org.apache.kafka.common.errors.WakeupException;
18 import reactor.core.publisher.Mono;
21 import java.util.Collection;
22 import java.util.HashMap;
24 import java.util.UUID;
25 import java.util.stream.IntStream;
28 @ToString(of = { "topic", "instanceId" })
30 public class DataChannel implements Channel, ConsumerRebalanceListener
32 private final String instanceId;
33 private final String topic;
34 private final Producer<String, AbstractMessageTo> producer;
35 private final Consumer<String, AbstractMessageTo> consumer;
36 private final ZoneId zoneId;
37 private final int numShards;
38 private final Duration pollingInterval;
39 private final int historyLimit;
40 private final Clock clock;
41 private final boolean[] isShardOwned;
42 private final long[] currentOffset;
43 private final long[] nextOffset;
44 private final Map<UUID, ChatRoomData>[] chatRoomData;
45 private final ChannelMediator channelMediator;
46 private final ShardingPublisherStrategy shardingPublisherStrategy;
48 private boolean running;
50 private volatile ChannelState channelState = ChannelState.STARTING;
56 Producer<String, AbstractMessageTo> producer,
57 Consumer<String, AbstractMessageTo> dataChannelConsumer,
60 Duration pollingInterval,
63 ChannelMediator channelMediator,
64 ShardingPublisherStrategy shardingPublisherStrategy)
67 "{}: Creating DataChannel for topic {} with {} partitions",
71 this.instanceId = instanceId;
73 this.consumer = dataChannelConsumer;
74 this.producer = producer;
76 this.numShards = numShards;
77 this.pollingInterval = pollingInterval;
78 this.historyLimit = historyLimit;
80 this.isShardOwned = new boolean[numShards];
81 this.currentOffset = new long[numShards];
82 this.nextOffset = new long[numShards];
83 this.chatRoomData = new Map[numShards];
86 .forEach(shard -> this.chatRoomData[shard] = new HashMap<>());
87 this.channelMediator = channelMediator;
88 this.shardingPublisherStrategy = shardingPublisherStrategy;
93 Mono<Message> sendChatMessage(
95 Message.MessageKey key,
96 LocalDateTime timestamp,
99 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
100 return Mono.create(sink ->
102 ProducerRecord<String, AbstractMessageTo> record =
103 new ProducerRecord<>(
107 chatRoomId.toString(),
108 EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
110 producer.send(record, ((metadata, exception) ->
112 if (exception == null)
114 // On successful send
115 Message message = new Message(key, metadata.offset(), timestamp, text);
116 log.info("Successfully send message {}", message);
117 sink.success(message);
123 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
129 sink.error(exception);
136 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
138 log.info("Newly assigned partitions! Pausing normal operations...");
139 channelState = ChannelState.LOAD_IN_PROGRESS;
141 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
143 int partition = topicPartition.partition();
144 isShardOwned[partition] = true;
145 this.currentOffset[partition] = currentOffset;
148 "Partition assigned: {} - loading messages: next={} -> current={}",
150 nextOffset[partition],
153 consumer.seek(topicPartition, nextOffset[partition]);
154 channelMediator.shardAssigned(partition);
155 shardingPublisherStrategy
156 .publishOwnership(partition)
157 .doOnSuccess(instanceId -> log.info(
158 "Successfully published instance {} as owner of shard {}",
161 .doOnError(throwable -> log.error(
162 "Could not publish instance {} as owner of shard {}: {}",
165 throwable.toString()))
170 consumer.resume(partitions);
174 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
176 partitions.forEach(topicPartition ->
178 int partition = topicPartition.partition();
179 chatRoomData[partition]
181 .forEach(chatRoomData -> chatRoomData.close());
182 isShardOwned[partition] = false;
183 nextOffset[partition] = consumer.position(topicPartition);
184 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
185 channelMediator.shardRevoked(partition);
190 public void onPartitionsLost(Collection<TopicPartition> partitions)
192 log.warn("Lost partitions: {}, partitions");
193 // TODO: Muss auf den Verlust anders reagiert werden?
194 onPartitionsRevoked(partitions);
206 ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(pollingInterval);
207 log.info("Fetched {} messages", records.count());
209 switch (channelState)
211 case LOAD_IN_PROGRESS ->
213 loadChatRoomData(records);
215 if (isLoadingCompleted())
217 log.info("Loading of messages completed! Pausing all owned partitions...");
218 pauseAllOwnedPartions();
219 log.info("Resuming normal operations...");
220 channelState = ChannelState.READY;
223 case SHUTTING_DOWN -> log.info("Shutdown in progress: ignoring {} fetched messages.", records.count());
226 if (!records.isEmpty())
228 throw new IllegalStateException("All owned partitions should be paused, when in state " + channelState);
233 catch (WakeupException e)
235 log.info("Received WakeupException, exiting!");
236 channelState = ChannelState.SHUTTING_DOWN;
241 log.info("Exiting normally");
244 private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
246 for (ConsumerRecord<String, AbstractMessageTo> record : records)
248 UUID chatRoomId = UUID.fromString(record.key());
250 switch (record.value().getType())
252 case EVENT_CHATMESSAGE_RECEIVED:
253 Instant instant = Instant.ofEpochSecond(record.timestamp());
254 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
259 (EventChatMessageReceivedTo) record.value(),
265 "Ignoring message for chat-room {} with offset {}: {}",
271 nextOffset[record.partition()] = record.offset() + 1;
275 private void loadChatMessage(
277 LocalDateTime timestamp,
279 EventChatMessageReceivedTo chatMessageTo,
282 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
283 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
285 ChatRoomData chatRoomData = computeChatRoomData(chatRoomId, partition);
286 KafkaChatMessageService kafkaChatRoomService =
287 (KafkaChatMessageService) chatRoomData.getChatRoomService();
290 "Loaded message from partition={} at offset={}: {}",
294 kafkaChatRoomService.persistMessage(message);
297 private boolean isLoadingCompleted()
301 .filter(shard -> isShardOwned[shard])
304 TopicPartition partition = new TopicPartition(topic, shard);
305 long position = consumer.position(partition);
306 return position >= currentOffset[shard];
310 private void pauseAllOwnedPartions()
312 consumer.pause(IntStream
314 .filter(shard -> isShardOwned[shard])
315 .mapToObj(shard -> new TopicPartition(topic, shard))
320 int[] getOwnedShards()
324 .filter(shard -> isShardOwned[shard])
328 void createChatRoomData(ChatRoomInfo chatRoomInfo)
330 computeChatRoomData(chatRoomInfo.getId(), chatRoomInfo.getShard());
333 Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
335 ChannelState capturedState = channelState;
336 if (capturedState != ChannelState.READY)
338 return Mono.error(new ChannelNotReadyException(capturedState));
341 if (!isShardOwned[shard])
343 return Mono.error(new ShardNotOwnedException(instanceId, shard));
346 return Mono.justOrEmpty(chatRoomData[shard].get(id));
349 private ChatRoomData computeChatRoomData(UUID chatRoomId, int shard)
351 ChatRoomData chatRoomData = this.chatRoomData[shard].get(chatRoomId);
353 if (chatRoomData != null)
356 "Ignoring request to create already existing ChatRoomData for {}",
361 log.info("Creating ChatRoomData {} with history-limit {}", chatRoomId, historyLimit);
362 KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
363 chatRoomData = new ChatRoomData(clock, service, historyLimit);
364 this.chatRoomData[shard].put(chatRoomId, chatRoomData);
370 ConsumerGroupMetadata getConsumerGroupMetadata()
372 return consumer.groupMetadata();