WIP
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / implementation / StorageStrategy.java
index 9dd7625..98db975 100644 (file)
@@ -8,6 +8,9 @@ import org.slf4j.LoggerFactory;
 import reactor.core.publisher.Flux;
 
 import java.util.UUID;
+import java.util.concurrent.Phaser;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 
@@ -16,19 +19,48 @@ public interface StorageStrategy
 {
   Logger log = LoggerFactory.getLogger(StorageStrategy.class.getCanonicalName());
 
+  AtomicBoolean running = new AtomicBoolean(true);
+
+
   default void write(ChatHomeService chatHomeService)
   {
+    if (!running.getAndSet(false))
+    {
+      log.info("{} is not running, skip write...", chatHomeService);
+      return;
+    }
+
+    Phaser writtenChatRooms = new Phaser(1);
+    AtomicInteger numErrors = new AtomicInteger();
+
     writeChatRoomInfo(
         chatHomeService
             .getChatRoomInfo()
-            .doOnNext(chatRoomInfo ->
-                writeChatRoomData(
-                    chatRoomInfo.getId(),
-                    chatHomeService
-                        .getChatRoomData(chatRoomInfo.getId())
-                        .flatMapMany(chatRoomData -> chatRoomData.getMessages()),
-                    this::logSuccess,
-                    this::logFailure)));
+            .doOnNext(chatRoomInfo -> writtenChatRooms.register())
+            .doOnNext(chatRoomInfo -> writeChatRoomData(
+                chatRoomInfo.getId(),
+                chatHomeService
+                    .getChatRoomData(chatRoomInfo.getId())
+                    .flatMapMany(chatRoomData -> chatRoomData.getMessages()),
+                (chatRoomId) ->
+                {
+                  logSuccess(chatRoomId);
+                  writtenChatRooms.arriveAndDeregister();
+                },
+                (chatRoomId, throwable) ->
+                {
+                  logFailure(chatRoomId, throwable);
+                  numErrors.incrementAndGet();
+                  writtenChatRooms.arriveAndDeregister();
+                })));
+
+    writtenChatRooms.arriveAndAwaitAdvance();
+    if (numErrors.get() > 0)
+    {
+      throw new RuntimeException("Could not write all chat-rooms for " + chatHomeService);
+    }
+
+    log.info("All chat-rooms were written successfully for {}", chatHomeService);
   }
 
   void writeChatRoomInfo(Flux<ChatRoomInfo> chatRoomInfoFlux);