1 package de.juplo.kafka.chat.backend.implementation.kafka;
3 import de.juplo.kafka.chat.backend.domain.*;
4 import de.juplo.kafka.chat.backend.domain.exceptions.LoadInProgressException;
5 import de.juplo.kafka.chat.backend.domain.exceptions.ShardNotOwnedException;
6 import de.juplo.kafka.chat.backend.implementation.kafka.messages.AbstractMessageTo;
7 import de.juplo.kafka.chat.backend.implementation.kafka.messages.data.EventChatMessageReceivedTo;
9 import lombok.extern.slf4j.Slf4j;
10 import org.apache.kafka.clients.consumer.*;
11 import org.apache.kafka.clients.producer.Producer;
12 import org.apache.kafka.clients.producer.ProducerRecord;
13 import org.apache.kafka.common.TopicPartition;
14 import org.apache.kafka.common.errors.WakeupException;
15 import reactor.core.publisher.Mono;
19 import java.util.stream.IntStream;
23 public class DataChannel implements Runnable, ConsumerRebalanceListener
25 private final String instanceId;
26 private final String topic;
27 private final Producer<String, AbstractMessageTo> producer;
28 private final Consumer<String, AbstractMessageTo> consumer;
29 private final ZoneId zoneId;
30 private final int numShards;
31 private final Duration pollingInterval;
32 private final int bufferSize;
33 private final Clock clock;
34 private final boolean[] isShardOwned;
35 private final long[] currentOffset;
36 private final long[] nextOffset;
37 private final Map<UUID, ChatRoomData>[] chatRoomData;
38 private final ChannelMediator channelMediator;
39 private final ShardingPublisherStrategy shardingPublisherStrategy;
41 private boolean running;
43 private volatile boolean loadInProgress;
49 Producer<String, AbstractMessageTo> producer,
50 Consumer<String, AbstractMessageTo> dataChannelConsumer,
53 Duration pollingInterval,
56 ChannelMediator channelMediator,
57 ShardingPublisherStrategy shardingPublisherStrategy)
60 "{}: Creating DataChannel for topic {} with {} partitions",
64 this.instanceId = instanceId;
66 this.consumer = dataChannelConsumer;
67 this.producer = producer;
69 this.numShards = numShards;
70 this.pollingInterval = pollingInterval;
71 this.bufferSize = bufferSize;
73 this.isShardOwned = new boolean[numShards];
74 this.currentOffset = new long[numShards];
75 this.nextOffset = new long[numShards];
76 this.chatRoomData = new Map[numShards];
79 .forEach(shard -> this.chatRoomData[shard] = new HashMap<>());
80 this.channelMediator = channelMediator;
81 this.shardingPublisherStrategy = shardingPublisherStrategy;
86 Mono<Message> sendChatMessage(
88 Message.MessageKey key,
89 LocalDateTime timestamp,
92 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
93 return Mono.create(sink ->
95 ProducerRecord<String, AbstractMessageTo> record =
100 chatRoomId.toString(),
101 EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
103 producer.send(record, ((metadata, exception) ->
105 if (exception == null)
107 // On successful send
108 Message message = new Message(key, metadata.offset(), timestamp, text);
109 log.info("Successfully send message {}", message);
110 sink.success(message);
116 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
122 sink.error(exception);
129 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
131 log.info("Newly assigned partitions! Pausing normal operations...");
132 loadInProgress = true;
134 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
136 int partition = topicPartition.partition();
137 isShardOwned[partition] = true;
138 this.currentOffset[partition] = currentOffset;
141 "Partition assigned: {} - loading messages: next={} -> current={}",
143 nextOffset[partition],
146 consumer.seek(topicPartition, nextOffset[partition]);
147 channelMediator.shardAssigned(partition);
148 shardingPublisherStrategy
149 .publishOwnership(partition)
150 .doOnSuccess(instanceId -> log.info(
151 "Successfully published instance {} as owner of shard {}",
154 .doOnError(throwable -> log.error(
155 "Could not publish instance {} as owner of shard {}: {}",
158 throwable.toString()))
163 consumer.resume(partitions);
167 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
169 partitions.forEach(topicPartition ->
171 int partition = topicPartition.partition();
172 isShardOwned[partition] = false;
173 nextOffset[partition] = consumer.position(topicPartition);
174 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
175 channelMediator.shardRevoked(partition);
180 public void onPartitionsLost(Collection<TopicPartition> partitions)
182 log.warn("Lost partitions: {}, partitions");
183 // TODO: Muss auf den Verlust anders reagiert werden?
184 onPartitionsRevoked(partitions);
196 ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(pollingInterval);
197 log.info("Fetched {} messages", records.count());
201 loadChatRoomData(records);
203 if (isLoadingCompleted())
205 log.info("Loading of messages completed! Pausing all owned partitions...");
206 pauseAllOwnedPartions();
207 log.info("Resuming normal operations...");
208 loadInProgress = false;
213 if (!records.isEmpty())
215 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
219 catch (WakeupException e)
221 log.info("Received WakeupException, exiting!");
226 log.info("Exiting normally");
229 private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
231 for (ConsumerRecord<String, AbstractMessageTo> record : records)
233 UUID chatRoomId = UUID.fromString(record.key());
235 switch (record.value().getType())
237 case EVENT_CHATMESSAGE_RECEIVED:
238 Instant instant = Instant.ofEpochSecond(record.timestamp());
239 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
244 (EventChatMessageReceivedTo) record.value(),
250 "Ignoring message for chat-room {} with offset {}: {}",
256 nextOffset[record.partition()] = record.offset() + 1;
260 private void loadChatMessage(
262 LocalDateTime timestamp,
264 EventChatMessageReceivedTo chatMessageTo,
267 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
268 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
270 ChatRoomData chatRoomData = this
271 .chatRoomData[partition]
272 .computeIfAbsent(chatRoomId, this::computeChatRoomData);
273 KafkaChatMessageService kafkaChatRoomService =
274 (KafkaChatMessageService) chatRoomData.getChatRoomService();
277 "Loaded message from partition={} at offset={}: {}",
281 kafkaChatRoomService.persistMessage(message);
284 private boolean isLoadingCompleted()
288 .filter(shard -> isShardOwned[shard])
291 TopicPartition partition = new TopicPartition(topic, shard);
292 long position = consumer.position(partition);
293 return position >= currentOffset[shard];
297 private void pauseAllOwnedPartions()
299 consumer.pause(IntStream
301 .filter(shard -> isShardOwned[shard])
302 .mapToObj(shard -> new TopicPartition(topic, shard))
307 int[] getOwnedShards()
311 .filter(shard -> isShardOwned[shard])
315 Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
319 return Mono.error(new LoadInProgressException());
322 if (!isShardOwned[shard])
324 return Mono.error(new ShardNotOwnedException(instanceId, shard));
327 return channelMediator
330 chatRoomData[shard].computeIfAbsent(id, this::computeChatRoomData));
333 private ChatRoomData computeChatRoomData(UUID chatRoomId)
335 log.info("Creating ChatRoom {} with buffer-size {}", chatRoomId, bufferSize);
336 KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
337 return new ChatRoomData(clock, service, bufferSize);
340 ConsumerGroupMetadata getConsumerGroupMetadata()
342 return consumer.groupMetadata();