refactor: `KafkaServicesApplicationRunner` aufgerÀumt
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / implementation / kafka / InfoChannel.java
index 3fe15c4..2df7573 100644 (file)
@@ -1,10 +1,12 @@
 package de.juplo.kafka.chat.backend.implementation.kafka;
 
 import de.juplo.kafka.chat.backend.domain.ChatRoomInfo;
+import de.juplo.kafka.chat.backend.domain.exceptions.LoadInProgressException;
 import de.juplo.kafka.chat.backend.implementation.kafka.messages.AbstractMessageTo;
 import de.juplo.kafka.chat.backend.implementation.kafka.messages.info.EventChatRoomCreated;
 import de.juplo.kafka.chat.backend.implementation.kafka.messages.info.EventShardAssigned;
 import de.juplo.kafka.chat.backend.implementation.kafka.messages.info.EventShardRevoked;
+import lombok.Getter;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
@@ -38,6 +40,8 @@ public class InfoChannel implements Runnable
   private final String instanceUri;
 
   private boolean running;
+  @Getter
+  private volatile boolean loadInProgress = true;
 
 
   public InfoChannel(
@@ -68,13 +72,6 @@ public class InfoChannel implements Runnable
   }
 
 
-  boolean isLoadInProgress()
-  {
-    return IntStream
-        .range(0, numShards)
-        .anyMatch(partition -> nextOffset[partition] < currentOffset[partition]);
-  }
-
   Mono<ChatRoomInfo> sendChatRoomCreatedEvent(
       UUID chatRoomId,
       String name,
@@ -189,6 +186,7 @@ public class InfoChannel implements Runnable
     IntStream
         .range(0, numShards)
         .forEach(partition -> this.nextOffset[partition] = 0l);
+    loadInProgress = true;
 
     while (running)
     {
@@ -215,6 +213,11 @@ public class InfoChannel implements Runnable
   private void updateNextOffset(int partition, long nextOffset)
   {
     this.nextOffset[partition] = nextOffset;
+    if (loadInProgress) {
+      loadInProgress = IntStream
+          .range(0, numShards)
+          .anyMatch(shard -> this.nextOffset[shard] < currentOffset[partition]);
+    }
   }
 
   private void handleMessage(ConsumerRecord<String, AbstractMessageTo> record)
@@ -286,6 +289,11 @@ public class InfoChannel implements Runnable
 
   Mono<ChatRoomInfo> getChatRoomInfo(UUID id)
   {
+    if (loadInProgress)
+    {
+      return Mono.error(new LoadInProgressException());
+    }
+
     return Mono.fromSupplier(() -> chatRoomInfo.get(id));
   }