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 topic;
29 private final Producer<String, AbstractMessageTo> producer;
30 private final Consumer<String, AbstractMessageTo> consumer;
31 private final ZoneId zoneId;
32 private final int numShards;
33 private final int bufferSize;
34 private final Clock clock;
35 private final boolean[] isShardOwned;
36 private final long[] currentOffset;
37 private final long[] nextOffset;
38 private final Map<UUID, ChatRoomData>[] chatRoomData;
40 private boolean running;
42 private volatile boolean loadInProgress;
47 Producer<String, AbstractMessageTo> producer,
48 Consumer<String, AbstractMessageTo> dataChannelConsumer,
55 "Creating DataChannel for topic {} with {} partitions",
59 this.consumer = dataChannelConsumer;
60 this.producer = producer;
62 this.numShards = numShards;
63 this.bufferSize = bufferSize;
65 this.isShardOwned = new boolean[numShards];
66 this.currentOffset = new long[numShards];
67 this.nextOffset = new long[numShards];
68 this.chatRoomData = new Map[numShards];
73 this.chatRoomData[shard] = new HashMap<>();
79 Mono<Message> sendChatMessage(
81 Message.MessageKey key,
82 LocalDateTime timestamp,
85 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
86 return Mono.create(sink ->
88 ProducerRecord<String, AbstractMessageTo> record =
93 chatRoomId.toString(),
94 EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
96 producer.send(record, ((metadata, exception) ->
100 // On successful send
101 Message message = new Message(key, metadata.offset(), timestamp, text);
102 log.info("Successfully send message {}", message);
103 sink.success(message);
109 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
115 sink.error(exception);
122 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
124 log.info("Newly assigned partitions! Pausing normal operations...");
125 loadInProgress = true;
127 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
129 int partition = topicPartition.partition();
130 isShardOwned[partition] = true;
131 this.currentOffset[partition] = currentOffset;
134 "Partition assigned: {} - loading messages: next={} -> current={}",
136 nextOffset[partition],
139 consumer.seek(topicPartition, nextOffset[partition]);
142 consumer.resume(partitions);
146 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
148 partitions.forEach(topicPartition ->
150 int partition = topicPartition.partition();
151 isShardOwned[partition] = false;
152 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
157 public void onPartitionsLost(Collection<TopicPartition> partitions)
159 log.warn("Lost partitions: {}, partitions");
160 // TODO: Muss auf den Verlust anders reagiert werden?
161 onPartitionsRevoked(partitions);
173 ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(Duration.ofMinutes(1));
174 log.info("Fetched {} messages", records.count());
178 loadChatRoomData(records);
180 if (isLoadingCompleted())
182 log.info("Loading of messages completed! Pausing all owned partitions...");
183 pauseAllOwnedPartions();
184 log.info("Resuming normal operations...");
185 loadInProgress = false;
190 if (!records.isEmpty())
192 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
196 catch (WakeupException e)
198 log.info("Received WakeupException, exiting!");
203 log.info("Exiting normally");
206 private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
208 for (ConsumerRecord<String, AbstractMessageTo> record : records)
210 UUID chatRoomId = UUID.fromString(record.key());
212 switch (record.value().getType())
214 case EVENT_CHATMESSAGE_RECEIVED:
215 Instant instant = Instant.ofEpochSecond(record.timestamp());
216 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
221 (EventChatMessageReceivedTo) record.value(),
227 "Ignoring message for chat-room {} with offset {}: {}",
233 nextOffset[record.partition()] = record.offset() + 1;
237 private void loadChatMessage(
239 LocalDateTime timestamp,
241 EventChatMessageReceivedTo chatMessageTo,
244 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
245 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
247 ChatRoomData chatRoomData = this.chatRoomData[partition].computeIfAbsent(
251 log.info("Creating ChatRoom {} with buffer-size {}", id, bufferSize);
252 KafkaChatMessageService service = new KafkaChatMessageService(this, id);
253 return new ChatRoomData(clock, service, bufferSize);
255 KafkaChatMessageService kafkaChatRoomService =
256 (KafkaChatMessageService) chatRoomData.getChatRoomService();
258 kafkaChatRoomService.persistMessage(message);
261 private boolean isLoadingCompleted()
265 .filter(shard -> isShardOwned[shard])
266 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
269 private void pauseAllOwnedPartions()
271 consumer.pause(IntStream
273 .filter(shard -> isShardOwned[shard])
274 .mapToObj(shard -> new TopicPartition(topic, shard))
279 int[] getOwnedShards()
283 .filter(shard -> isShardOwned[shard])
287 Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
291 return Mono.error(new LoadInProgressException());
294 if (!isShardOwned[shard])
296 return Mono.error(new ShardNotOwnedException(shard));
299 return Mono.justOrEmpty(chatRoomData[shard].get(id));