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 reactor.core.publisher.Flux;
17 import reactor.core.publisher.Mono;
21 import java.util.concurrent.ExecutorService;
25 public class KafkaChatHomeService implements ChatHomeService, Runnable, ConsumerRebalanceListener
27 private final ExecutorService executorService;
28 private final Consumer<String, MessageTo> consumer;
29 private final Producer<String, MessageTo> producer;
30 private final String topic;
31 private final ZoneId zoneId;
32 private final int numShards;
33 private final boolean[] isShardOwned;
34 private final long[] currentOffset;
35 private final long[] nextOffset;
36 private final Map<UUID, ChatRoom>[] chatRoomMaps;
37 private final KafkaLikeShardingStrategy shardingStrategy;
39 private boolean running;
40 private volatile boolean loadInProgress;
43 public KafkaChatHomeService(
44 ExecutorService executorService,
45 Consumer<String, MessageTo> consumer,
46 Producer<String, MessageTo> producer,
51 log.debug("Creating KafkaChatHomeService");
52 this.executorService = executorService;
53 this.consumer = consumer;
54 this.producer = producer;
57 this.numShards = numShards;
58 this.isShardOwned = new boolean[numShards];
59 this.currentOffset = new long[numShards];
60 this.nextOffset = new long[numShards];
61 this.chatRoomMaps = new Map[numShards];
62 this.shardingStrategy = new KafkaLikeShardingStrategy(numShards);
67 public void onPartitionsAssigned(Collection<TopicPartition> partitions)
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 for (ConsumerRecord<String, MessageTo> record : records)
126 UUID chatRoomId = UUID.fromString(record.key());
127 MessageTo messageTo = record.value();
129 Message.MessageKey key = Message.MessageKey.of(messageTo.getUser(), messageTo.getId());
131 Instant instant = Instant.ofEpochSecond(record.timestamp());
132 LocalDateTime timestamp = LocalDateTime.ofInstant(instant, zoneId);
134 Message message = new Message(key, record.offset(), timestamp, messageTo.getText());
136 ChatRoom chatRoom = chatRoomMaps[record.partition()].get(chatRoomId);
137 KafkaChatRoomService kafkaChatRoomService =
138 (KafkaChatRoomService) chatRoom.getChatRoomService();
140 kafkaChatRoomService.persistMessage(message);
145 if (!records.isEmpty())
147 throw new IllegalStateException("All owned partitions should be paused, when no load is in progress!");
154 Mono<Message> sendMessage(
156 Message.MessageKey key,
157 LocalDateTime timestamp,
160 int shard = this.shardingStrategy.selectShard(chatRoomId);
161 TopicPartition tp = new TopicPartition(topic, shard);
162 ZonedDateTime zdt = ZonedDateTime.of(timestamp, zoneId);
163 return Mono.create(sink ->
165 ProducerRecord<String, MessageTo> record =
166 new ProducerRecord<>(
170 chatRoomId.toString(),
171 MessageTo.of(key.getUsername(), key.getMessageId(), text));
173 producer.send(record, ((metadata, exception) ->
175 if (metadata != null)
177 // On successful send
178 Message message = new Message(key, metadata.offset(), timestamp, text);
179 log.info("Successfully send message {}", message);
180 sink.success(message);
186 "Could not send message for chat-room={}, key={}, timestamp={}, text={}: {}",
192 sink.error(exception);
200 public Mono<ChatRoom> getChatRoom(int shard, UUID id)
204 throw new ShardNotOwnedException(shard);
208 return Mono.justOrEmpty(chatRoomMaps[shard].get(id));
213 public Flux<ChatRoom> getChatRooms(int shard)
217 throw new ShardNotOwnedException(shard);
221 return Flux.fromStream(chatRoomMaps[shard].values().stream());