1 package de.juplo.kafka.chat.backend.persistence.kafka;
3 import de.juplo.kafka.chat.backend.domain.ChatHomeService;
4 import de.juplo.kafka.chat.backend.domain.ChatRoom;
5 import de.juplo.kafka.chat.backend.domain.Message;
6 import de.juplo.kafka.chat.backend.domain.ShardNotOwnedException;
7 import de.juplo.kafka.chat.backend.persistence.KafkaLikeShardingStrategy;
8 import lombok.extern.slf4j.Slf4j;
9 import org.apache.kafka.clients.consumer.Consumer;
10 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
11 import org.apache.kafka.clients.consumer.ConsumerRecord;
12 import org.apache.kafka.clients.consumer.ConsumerRecords;
13 import org.apache.kafka.clients.producer.Producer;
14 import org.apache.kafka.clients.producer.ProducerRecord;
15 import org.apache.kafka.common.TopicPartition;
16 import org.apache.kafka.common.errors.RecordDeserializationException;
17 import org.apache.kafka.common.errors.WakeupException;
18 import reactor.core.publisher.Flux;
19 import reactor.core.publisher.Mono;
23 import java.util.stream.IntStream;
27 public class KafkaChatHomeService implements ChatHomeService, Runnable, ConsumerRebalanceListener
29 private final Consumer<String, MessageTo> consumer;
30 private final Producer<String, MessageTo> producer;
31 private final String topic;
32 private final ZoneId zoneId;
33 private final int numShards;
34 private final boolean[] isShardOwned;
35 private final long[] currentOffset;
36 private final long[] nextOffset;
37 private final Map<UUID, ChatRoom>[] chatrooms;
38 private final KafkaLikeShardingStrategy shardingStrategy;
40 private boolean running;
41 private volatile boolean loadInProgress;
44 public KafkaChatHomeService(
45 Consumer<String, MessageTo> consumer,
46 Producer<String, MessageTo> producer,
51 log.debug("Creating KafkaChatHomeService");
52 this.consumer = consumer;
53 this.producer = producer;
56 this.numShards = numShards;
57 this.isShardOwned = new boolean[numShards];
58 this.currentOffset = new long[numShards];
59 this.nextOffset = new long[numShards];
60 this.chatrooms = new Map[numShards];
61 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
66 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
68 log.info("Newly assigned partitions! Pausing normal operations...");
69 loadInProgress = true;
71 consumer.endOffsets(partitions).forEach((topicPartition, currentOffset) ->
73 int partition = topicPartition.partition();
74 isShardOwned[partition] = true;
75 this.currentOffset[partition] = currentOffset;
78 "Partition assigned: {} - loading messages: next={} -> current={}",
80 nextOffset[partition],
83 consumer.seek(topicPartition, nextOffset[partition]);
86 consumer.resume(partitions);
90 public void onPartitionsRevoked(Collection<TopicPartition> partitions)
92 partitions.forEach(topicPartition ->
94 int partition = topicPartition.partition();
95 isShardOwned[partition] = false;
96 log.info("Partition revoked: {} - next={}", partition, nextOffset[partition]);
101 public void onPartitionsLost(Collection<TopicPartition> partitions)
103 log.warn("Lost partitions: {}, partitions");
104 // TODO: Muss auf den Verlust anders reagiert werden?
105 onPartitionsRevoked(partitions);
111 consumer.subscribe(List.of(topic));
119 ConsumerRecords<String, MessageTo> records = consumer.poll(Duration.ofMinutes(5));
120 log.info("Fetched {} messages", records.count());
124 loadMessages(records);
126 if (isLoadingCompleted())
128 log.info("Loading of messages completed! Pausing all owned partitions...");
129 pauseAllOwnedPartions();
130 log.info("Resuming normal operations...");
131 loadInProgress = false;
136 if (!records.isEmpty())
138 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
142 catch (WakeupException e)
145 catch (RecordDeserializationException e)
151 void loadMessages(ConsumerRecords<String, MessageTo> records)
153 for (ConsumerRecord<String, MessageTo> record : records)
155 nextOffset[record.partition()] = record.offset() + 1;
156 UUID chatRoomId = UUID.fromString(record.key());
157 MessageTo messageTo = record.value();
159 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
161 Instant instant = Instant.ofEpochSecond(record.timestamp());
162 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
164 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
166 ChatRoom chatRoom = chatrooms[record.partition()].get(chatRoomId);
167 KafkaChatRoomService kafkaChatRoomService =
168 (KafkaChatRoomService) chatRoom.getChatRoomService();
170 kafkaChatRoomService.persistMessage(message);
174 boolean isLoadingCompleted()
178 .filter(shard -> isShardOwned[shard])
179 .mapToObj(shard -> nextOffset[shard] >= currentOffset[shard])
182 (acc, v) -> Boolean.valueOf(acc && v),
183 (a, b) -> Boolean.valueOf(a && b));
186 void pauseAllOwnedPartions()
188 consumer.pause(IntStream
190 .filter(shard -> isShardOwned[shard])
191 .mapToObj(shard -> new TopicPartition(topic, shard))
195 Mono<Message> sendMessage(
197 Message.MessageKey key,
198 LocalDateTime timestamp,
201 int shard = this.shardingStrategy.selectShard(chatRoomId);
202 TopicPartition tp = new TopicPartition(topic, shard);
203 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
204 return Mono.create(sink ->
206 ProducerRecord<String, MessageTo> record =
207 new ProducerRecord<>(
211 chatRoomId.toString(),
212 MessageTo.of(key.getUsername(), key.getMessageId(), text));
214 producer.send(record, ((metadata, exception) ->
216 if (metadata != null)
218 // On successful send
219 Message message = new Message(key, metadata.offset(), timestamp, text);
220 log.info("Successfully send message {}", message);
221 sink.success(message);
227 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
233 sink.error(exception);
240 public void putChatRoom(ChatRoom chatRoom)
242 // TODO: Nachricht senden!
243 chatrooms[chatRoom.getShard()].put(chatRoom.getId(), chatRoom);
247 public Mono<ChatRoom> getChatRoom(int shard, UUID id)
251 throw new ShardNotOwnedException(shard);
255 return Mono.justOrEmpty(chatrooms[shard].get(id));
260 public Flux<ChatRoom> getChatRooms(int shard)
264 throw new ShardNotOwnedException(shard);
268 return Flux.fromStream(chatrooms[shard].values().stream());