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.function.Function;
23 import java.util.stream.IntStream;
27 public class DataChannel implements Runnable, ConsumerRebalanceListener
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;
42 private boolean running;
44 private volatile boolean loadInProgress;
49 Producer<String, AbstractMessageTo> producer,
50 Consumer<String, AbstractMessageTo> dataChannelConsumer,
55 InfoChannel infoChannel)
58 "Creating DataChannel for topic {} with {} partitions",
62 this.consumer = dataChannelConsumer;
63 this.producer = producer;
65 this.numShards = numShards;
66 this.bufferSize = bufferSize;
68 this.isShardOwned = new boolean[numShards];
69 this.currentOffset = new long[numShards];
70 this.nextOffset = new long[numShards];
71 this.chatRoomData = new Map[numShards];
74 .forEach(shard -> this.chatRoomData[shard] = new HashMap<>());
75 this.infoChannel = infoChannel;
80 Mono<Message> sendChatMessage(
82 Message.MessageKey key,
83 LocalDateTime timestamp,
86 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
87 return Mono.create(sink ->
89 ProducerRecord<String, AbstractMessageTo> record =
94 chatRoomId.toString(),
95 EventChatMessageReceivedTo.of(key.getUsername(), key.getMessageId(), text));
97 producer.send(record, ((metadata, exception) ->
101 // On successful send
102 Message message = new Message(key, metadata.offset(), timestamp, text);
103 log.info("Successfully send message {}", message);
104 sink.success(message);
110 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
116 sink.error(exception);
123 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
125 log.info("Newly assigned partitions! Pausing normal operations...");
126 loadInProgress = true;
128 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
130 int partition = topicPartition.partition();
131 isShardOwned[partition] = true;
132 this.currentOffset[partition] = currentOffset;
135 "Partition assigned: {} - loading messages: next={} -> current={}",
137 nextOffset[partition],
140 consumer.seek(topicPartition, nextOffset[partition]);
143 consumer.resume(partitions);
147 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
149 partitions.forEach(topicPartition ->
151 int partition = topicPartition.partition();
152 isShardOwned[partition] = false;
153 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
158 public void onPartitionsLost(Collection<TopicPartition> partitions)
160 log.warn("Lost partitions: {}, partitions");
161 // TODO: Muss auf den Verlust anders reagiert werden?
162 onPartitionsRevoked(partitions);
174 ConsumerRecords<String, AbstractMessageTo> records = consumer.poll(Duration.ofMinutes(1));
175 log.info("Fetched {} messages", records.count());
179 loadChatRoomData(records);
181 if (isLoadingCompleted())
183 log.info("Loading of messages completed! Pausing all owned partitions...");
184 pauseAllOwnedPartions();
185 log.info("Resuming normal operations...");
186 loadInProgress = false;
191 if (!records.isEmpty())
193 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
197 catch (WakeupException e)
199 log.info("Received WakeupException, exiting!");
204 log.info("Exiting normally");
207 private void loadChatRoomData(ConsumerRecords<String, AbstractMessageTo> records)
209 for (ConsumerRecord<String, AbstractMessageTo> record : records)
211 UUID chatRoomId = UUID.fromString(record.key());
213 switch (record.value().getType())
215 case EVENT_CHATMESSAGE_RECEIVED:
216 Instant instant = Instant.ofEpochSecond(record.timestamp());
217 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
222 (EventChatMessageReceivedTo) record.value(),
228 "Ignoring message for chat-room {} with offset {}: {}",
234 nextOffset[record.partition()] = record.offset() + 1;
238 private void loadChatMessage(
240 LocalDateTime timestamp,
242 EventChatMessageReceivedTo chatMessageTo,
245 Message.MessageKey key = Message.MessageKey.of(chatMessageTo.getUser(), chatMessageTo.getId());
246 Message message = new Message(key, offset, timestamp, chatMessageTo.getText());
248 ChatRoomData chatRoomData = this
249 .chatRoomData[partition]
250 .computeIfAbsent(chatRoomId, this::computeChatRoomData);
251 KafkaChatMessageService kafkaChatRoomService =
252 (KafkaChatMessageService) chatRoomData.getChatRoomService();
254 kafkaChatRoomService.persistMessage(message);
257 private boolean isLoadingCompleted()
261 .filter(shard -> isShardOwned[shard])
262 .allMatch(shard -> nextOffset[shard] >= currentOffset[shard]);
265 private void pauseAllOwnedPartions()
267 consumer.pause(IntStream
269 .filter(shard -> isShardOwned[shard])
270 .mapToObj(shard -> new TopicPartition(topic, shard))
275 int[] getOwnedShards()
279 .filter(shard -> isShardOwned[shard])
283 Mono<ChatRoomData> getChatRoomData(int shard, UUID id)
287 return Mono.error(new LoadInProgressException());
290 if (!isShardOwned[shard])
292 return Mono.error(new ShardNotOwnedException(shard));
298 chatRoomData[shard].computeIfAbsent(id, this::computeChatRoomData));
301 private ChatRoomData computeChatRoomData(UUID chatRoomId)
303 log.info("Creating ChatRoom {} with buffer-size {}", chatRoomId, bufferSize);
304 KafkaChatMessageService service = new KafkaChatMessageService(this, chatRoomId);
305 return new ChatRoomData(clock, service, bufferSize);