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.Consumer;
11 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
12 import org.apache.kafka.clients.consumer.ConsumerRecord;
13 import org.apache.kafka.clients.consumer.ConsumerRecords;
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;
22 import java.util.stream.IntStream;
26 public class DataChannel implements Runnable, ConsumerRebalanceListener
28 private final String instanceId;
29 private final String topic;
30 private final Producer<String, AbstractMessageTo> producer;
31 private final Consumer<String, AbstractMessageTo> consumer;
32 private final ZoneId zoneId;
33 private final int numShards;
34 private final int bufferSize;
35 private final Clock clock;
36 private final boolean[] isShardOwned;
37 private final long[] currentOffset;
38 private final long[] nextOffset;
39 private final Map<UUID, ChatRoomData>[] chatRoomData;
40 private final InfoChannel infoChannel;
41 private final ShardingPublisherStrategy shardingPublisherStrategy;
43 private boolean running;
45 private volatile boolean loadInProgress;
51 Producer<String, AbstractMessageTo> producer,
52 Consumer<String, AbstractMessageTo> dataChannelConsumer,
57 InfoChannel infoChannel,
58 ShardingPublisherStrategy shardingPublisherStrategy)
61 "{}: Creating DataChannel for topic {} with {} partitions",
65 this.instanceId = instanceId;
67 this.consumer = dataChannelConsumer;
68 this.producer = producer;
70 this.numShards = numShards;
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.infoChannel = infoChannel;
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 infoChannel.sendShardAssignedEvent(partition);
148 shardingPublisherStrategy
149 .publishOwnership(partition)
150 .doOnNext(instanceId -> log.info(
151 "Instance {} was published as owner of shard {}",
157 consumer.resume(partitions);
161 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
163 partitions.forEach(topicPartition ->
165 int partition = topicPartition.partition();
166 isShardOwned[partition] = false;
167 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
168 infoChannel.sendShardRevokedEvent(partition);
173 public void onPartitionsLost(Collection<TopicPartition> partitions)
175 log.warn("Lost partitions: {}, partitions");
176 // TODO: Muss auf den Verlust anders reagiert werden?
177 onPartitionsRevoked(partitions);
189 ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(Duration.ofMinutes(1));
190 log.info("Fetched {} messages", records.count());
194 loadChatRoomData(records);
196 if (isLoadingCompleted())
198 log.info("Loading of messages completed! Pausing all owned partitions...");
199 pauseAllOwnedPartions();
200 log.info("Resuming normal operations...");
201 loadInProgress = false;
206 if (!records.isEmpty())
208 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
212 catch (WakeupException e)
214 log.info("Received WakeupException, exiting!");
219 log.info("Exiting normally");
222 private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
224 for (ConsumerRecord<String, AbstractMessageTo> record : records)
226 UUID chatRoomId = UUID.fromString(record.key());
228 switch (record.value().getType())
230 case EVENT_CHATMESSAGE_RECEIVED:
231 Instant instant = Instant.ofEpochSecond(record.timestamp());
232 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
237 (EventChatMessageReceivedTo) record.value(),
243 "Ignoring message for chat-room {} with offset {}: {}",
249 nextOffset[record.partition()] = record.offset() + 1;
253 private void loadChatMessage(
255 LocalDateTime timestamp,
257 EventChatMessageReceivedTo chatMessageTo,
260 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
261 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
263 ChatRoomData chatRoomData = this
264 .chatRoomData[partition]
265 .computeIfAbsent(chatRoomId, this::computeChatRoomData);
266 KafkaChatMessageService kafkaChatRoomService =
267 (KafkaChatMessageService) chatRoomData.getChatRoomService();
269 kafkaChatRoomService.persistMessage(message);
272 private boolean isLoadingCompleted()
276 .filter(shard -> isShardOwned[shard])
277 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
280 private void pauseAllOwnedPartions()
282 consumer.pause(IntStream
284 .filter(shard -> isShardOwned[shard])
285 .mapToObj(shard -> new TopicPartition(topic, shard))
290 int[] getOwnedShards()
294 .filter(shard -> isShardOwned[shard])
298 Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
302 return Mono.error(new LoadInProgressException());
305 if (!isShardOwned[shard])
307 return Mono.error(new ShardNotOwnedException(instanceId, shard));
313 chatRoomData[shard].computeIfAbsent(id, this::computeChatRoomData));
316 private ChatRoomData computeChatRoomData(UUID chatRoomId)
318 log.info("Creating ChatRoom {} with buffer-size {}", chatRoomId, bufferSize);
319 KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
320 return new ChatRoomData(clock, service, bufferSize);