feat: Moved persistence-logic from `ChatHome` into `ChatHomeService`
authorKai Moritz <kai@juplo.de>
Mon, 9 Jan 2023 18:52:05 +0000 (19:52 +0100)
committerKai Moritz <kai@juplo.de>
Mon, 9 Jan 2023 20:07:26 +0000 (21:07 +0100)
- Aligned configuration and tests accordingly.
- Also fixed some camel-case typos.

src/main/java/de/juplo/kafka/chat/backend/ChatBackendApplication.java
src/main/java/de/juplo/kafka/chat/backend/ChatBackendConfiguration.java
src/main/java/de/juplo/kafka/chat/backend/api/ChatBackendController.java
src/main/java/de/juplo/kafka/chat/backend/domain/ChatHome.java
src/main/java/de/juplo/kafka/chat/backend/domain/ChatHomeService.java
src/main/java/de/juplo/kafka/chat/backend/persistence/InMemoryChatHomeService.java
src/main/java/de/juplo/kafka/chat/backend/persistence/LocalJsonFilesStorageStrategy.java
src/test/java/de/juplo/kafka/chat/backend/api/ChatBackendControllerTest.java
src/test/java/de/juplo/kafka/chat/backend/domain/ChatHomeTest.java
src/test/java/de/juplo/kafka/chat/backend/persistence/LocalJsonFilesStorageStrategyIT.java

index f98a02a..80a46c0 100644 (file)
@@ -32,7 +32,7 @@ public class ChatBackendApplication implements WebFluxConfigurer
        @PreDestroy
        public void onExit()
        {
-               storageStrategy.writeChatrooms(chatHome.list());
+               storageStrategy.writeChatrooms(chatHome.getChatRooms());
        }
 
        public static void main(String[] args)
index 05fc2cb..68ccc4f 100644 (file)
@@ -19,31 +19,34 @@ import java.time.Clock;
 public class ChatBackendConfiguration
 {
   @Bean
-  public ChatHome chatHome(
-      ChatHomeService chatHomeService,
-      StorageStrategy storageStrategy)
+  public ChatHome chatHome(ChatHomeService chatHomeService)
   {
-    return new ChatHome(chatHomeService, storageStrategy.readChatrooms());
+    return new ChatHome(chatHomeService);
   }
 
   @Bean
-  public StorageStrategy storageStrategy(
-      ChatBackendProperties properties,
-      ObjectMapper mapper,
-      InMemoryChatHomeService chatHomeService)
+  InMemoryChatHomeService chatHomeService(
+      StorageStrategy storageStrategy,
+      Clock clock,
+      ChatBackendProperties properties)
   {
-    return new LocalJsonFilesStorageStrategy(
-        Paths.get(properties.getDatadir()),
-        mapper,
-        chatHomeService);
+    return new InMemoryChatHomeService(
+        storageStrategy.readChatrooms(),
+        clock,
+        properties.getChatroomBufferSize());
   }
 
   @Bean
-  InMemoryChatHomeService chatHomeService(
+  public StorageStrategy storageStrategy(
+      ChatBackendProperties properties,
       Clock clock,
-      ChatBackendProperties properties)
+      ObjectMapper mapper)
   {
-    return new InMemoryChatHomeService(clock, properties.getChatroomBufferSize());
+    return new LocalJsonFilesStorageStrategy(
+        Paths.get(properties.getDatadir()),
+        clock,
+        properties.getChatroomBufferSize(),
+        mapper);
   }
 
   @Bean
index 51ed6a2..e7a6f1a 100644 (file)
@@ -29,14 +29,14 @@ public class ChatBackendController
   @GetMapping("list")
   public Flux<ChatRoomTo> list()
   {
-    return chatHome.list().map(chatroom -> ChatRoomTo.from(chatroom));
+    return chatHome.getChatRooms().map(chatroom -> ChatRoomTo.from(chatroom));
   }
 
   @GetMapping("list/{chatroomId}")
   public Flux<MessageTo> list(@PathVariable UUID chatroomId)
   {
     return chatHome
-        .getChatroom(chatroomId)
+        .getChatRoom(chatroomId)
         .flatMapMany(chatroom -> chatroom
             .getMessages()
             .map(MessageTo::from));
@@ -45,7 +45,7 @@ public class ChatBackendController
   @GetMapping("get/{chatroomId}")
   public Mono<ChatRoomTo> get(@PathVariable UUID chatroomId)
   {
-    return chatHome.getChatroom(chatroomId).map(chatroom -> ChatRoomTo.from(chatroom));
+    return chatHome.getChatRoom(chatroomId).map(chatroom -> ChatRoomTo.from(chatroom));
   }
 
   @PutMapping("put/{chatroomId}/{username}/{messageId}")
@@ -57,7 +57,7 @@ public class ChatBackendController
   {
     return
         chatHome
-            .getChatroom(chatroomId)
+            .getChatRoom(chatroomId)
             .flatMap(chatroom -> put(chatroom, username, messageId, text));
   }
 
@@ -84,7 +84,7 @@ public class ChatBackendController
   {
     return
         chatHome
-            .getChatroom(chatroomId)
+            .getChatRoom(chatroomId)
             .flatMap(chatroom -> get(chatroom, username, messageId));
   }
 
@@ -103,7 +103,7 @@ public class ChatBackendController
   public Flux<ServerSentEvent<MessageTo>> listen(@PathVariable UUID chatroomId)
   {
     return chatHome
-        .getChatroom(chatroomId)
+        .getChatRoom(chatroomId)
         .flatMapMany(chatroom -> listen(chatroom));
   }
 
@@ -124,6 +124,6 @@ public class ChatBackendController
   @PostMapping("/store")
   public void store()
   {
-    storageStrategy.writeChatrooms(chatHome.list());
+    storageStrategy.writeChatrooms(chatHome.getChatRooms());
   }
 }
index bb4d89c..1450d3e 100644 (file)
@@ -1,5 +1,6 @@
 package de.juplo.kafka.chat.backend.domain;
 
+import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
@@ -8,36 +9,25 @@ import java.util.*;
 
 
 @Slf4j
+@RequiredArgsConstructor
 public class ChatHome
 {
-  private final Map<UUID, ChatRoom> chatrooms;
   private final ChatHomeService service;
 
-  public ChatHome(ChatHomeService service, Flux<ChatRoom> chatroomFlux)
-  {
-    log.debug("Creating ChatHome with factory: {}", service);
-    this.service = service;
-    this.chatrooms = new HashMap<>();
-    chatroomFlux.subscribe(chatroom -> chatrooms.put(chatroom.getId(), chatroom));
-  }
-
   public Mono<ChatRoom> createChatroom(String name)
   {
-    ChatRoom chatroom = service.createChatroom(UUID.randomUUID(), name);
-    chatrooms.put(chatroom.getId(), chatroom);
-    return Mono.just(chatroom);
+    return service.createChatRoom(UUID.randomUUID(), name);
   }
 
-  public Mono<ChatRoom> getChatroom(UUID id)
+  public Mono<ChatRoom> getChatRoom(UUID id)
   {
-    ChatRoom chatroom = chatrooms.get(id);
-    return chatroom == null
-        ? Mono.error(() -> new UnknownChatroomException(id))
-        : Mono.just(chatroom);
+    return service
+        .getChatRoom(id)
+        .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
   }
 
-  public Flux<ChatRoom> list()
+  public Flux<ChatRoom> getChatRooms()
   {
-    return Flux.fromStream(chatrooms.values().stream());
+    return service.getChatRooms();
   }
 }
index 69ed5f4..5743655 100644 (file)
@@ -1,9 +1,14 @@
 package de.juplo.kafka.chat.backend.domain;
 
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
 import java.util.UUID;
 
 
 public interface ChatHomeService<T extends ChatRoomService>
 {
-  ChatRoom createChatroom(UUID id, String name);
+  Mono<ChatRoom> createChatRoom(UUID id, String name);
+  Mono<ChatRoom> getChatRoom(UUID id);
+  Flux<ChatRoom> getChatRooms();
 }
index df0ecba..b74f17f 100644 (file)
@@ -2,33 +2,56 @@ package de.juplo.kafka.chat.backend.persistence;
 
 import de.juplo.kafka.chat.backend.domain.ChatRoom;
 import de.juplo.kafka.chat.backend.domain.ChatHomeService;
-import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
 
 import java.time.Clock;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
+import java.util.Map;
 import java.util.UUID;
 
 
-@RequiredArgsConstructor
+@Slf4j
 public class InMemoryChatHomeService implements ChatHomeService<InMemoryChatRoomService>
 {
+  private final Map<UUID, ChatRoom> chatrooms;
   private final Clock clock;
   private final int bufferSize;
 
 
+  public InMemoryChatHomeService(
+      Flux<ChatRoom> chatroomFlux,
+      Clock clock,
+      int bufferSize)
+  {
+    log.debug("Creating ChatHomeService with buffer-size {} (for created ChatRoom's)", bufferSize);
+    this.chatrooms = new HashMap<>();
+    chatroomFlux.subscribe(chatroom -> chatrooms.put(chatroom.getId(), chatroom));
+    this.clock = clock;
+    this.bufferSize = bufferSize;
+  }
+
   @Override
-  public ChatRoom createChatroom(UUID id, String name)
+  public Mono<ChatRoom> createChatRoom(UUID id, String name)
   {
     InMemoryChatRoomService service =
         new InMemoryChatRoomService(new LinkedHashMap<>());
-    return new ChatRoom(id, name, clock, service, bufferSize);
+    ChatRoom chatRoom = new ChatRoom(id, name, clock, service, bufferSize);
+    chatrooms.put(chatRoom.getId(), chatRoom);
+    return Mono.just(chatRoom);
+  }
+
+  @Override
+  public Mono<ChatRoom> getChatRoom(UUID id)
+  {
+    return Mono.justOrEmpty(chatrooms.get(id));
   }
 
-  public ChatRoom restoreChatroom(
-      UUID id,
-      String name,
-      InMemoryChatRoomService service)
+  @Override
+  public Flux<ChatRoom> getChatRooms()
   {
-    return new ChatRoom(id, name, clock, service, bufferSize);
+    return Flux.fromStream(chatrooms.values().stream());
   }
 }
index 706fbe3..7b490bf 100644 (file)
@@ -14,6 +14,7 @@ import reactor.core.publisher.Flux;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.time.Clock;
 
 import static java.nio.file.StandardOpenOption.CREATE;
 import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
@@ -27,8 +28,9 @@ public class LocalJsonFilesStorageStrategy implements StorageStrategy
 
 
   private final Path storagePath;
+  private final Clock clock;
+  private final int bufferSize;
   private final ObjectMapper mapper;
-  private final InMemoryChatHomeService service;
 
 
   @Override
@@ -102,10 +104,12 @@ public class LocalJsonFilesStorageStrategy implements StorageStrategy
         {
           InMemoryChatRoomService chatroomService =
               new InMemoryChatRoomService(readMessages(chatRoomTo));
-          return service.restoreChatroom(
+          return new ChatRoom(
               chatRoomTo.getId(),
               chatRoomTo.getName(),
-              chatroomService);
+              clock,
+              chatroomService,
+              bufferSize);
         });
   }
 
index 8947a03..5e3c928 100644 (file)
@@ -34,7 +34,7 @@ public class ChatBackendControllerTest
   {
     // Given
     UUID chatroomId = UUID.randomUUID();
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.error(() -> new UnknownChatroomException(chatroomId)));
 
     // When
@@ -55,7 +55,7 @@ public class ChatBackendControllerTest
   {
     // Given
     UUID chatroomId = UUID.randomUUID();
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.error(() -> new UnknownChatroomException(chatroomId)));
 
     // When
@@ -77,7 +77,7 @@ public class ChatBackendControllerTest
     UUID chatroomId = UUID.randomUUID();
     String username = "foo";
     Long messageId = 66l;
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.error(() -> new UnknownChatroomException(chatroomId)));
 
     // When
@@ -104,7 +104,7 @@ public class ChatBackendControllerTest
     UUID chatroomId = UUID.randomUUID();
     String username = "foo";
     Long messageId = 66l;
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.error(() -> new UnknownChatroomException(chatroomId)));
 
     // When
@@ -128,7 +128,7 @@ public class ChatBackendControllerTest
   {
     // Given
     UUID chatroomId = UUID.randomUUID();
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.error(() -> new UnknownChatroomException(chatroomId)));
 
     // When
@@ -162,7 +162,7 @@ public class ChatBackendControllerTest
     String username = "foo";
     Long messageId = 66l;
     ChatRoom chatRoom = mock(ChatRoom.class);
-    when(chatHome.getChatroom(any(UUID.class)))
+    when(chatHome.getChatRoom(any(UUID.class)))
         .thenReturn(Mono.just(chatRoom));
     Message.MessageKey key = Message.MessageKey.of("foo", 1l);
     LocalDateTime timestamp = LocalDateTime.now();
index 655c1b8..aba4d4a 100644 (file)
@@ -2,13 +2,14 @@ package de.juplo.kafka.chat.backend.domain;
 
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
-import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 
 import java.time.Clock;
 import java.util.UUID;
 
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 import static pl.rzrz.assertj.reactor.Assertions.assertThat;
 
 
@@ -20,13 +21,17 @@ public class ChatHomeTest
   {
     // Given
     ChatHomeService chatHomeService = mock(ChatHomeService.class);
-    ChatRoomService chatRoomService = mock(ChatRoomService.class);
-    UUID chatroomId = UUID.randomUUID();
-    ChatRoom chatRoom = new ChatRoom(chatroomId, "Foo", Clock.systemDefaultZone(), chatRoomService, 8);
-    ChatHome chatHome = new ChatHome(chatHomeService, Flux.just(chatRoom));
+    ChatRoom chatRoom = new ChatRoom(
+        UUID.randomUUID(),
+        "Foo",
+        Clock.systemDefaultZone(),
+        mock(ChatRoomService.class),
+        8);
+    when(chatHomeService.getChatRoom(any(UUID.class))).thenReturn(Mono.just(chatRoom));
+    ChatHome chatHome = new ChatHome(chatHomeService);
 
     // When
-    Mono<ChatRoom> mono = chatHome.getChatroom(chatroomId);
+    Mono<ChatRoom> mono = chatHome.getChatRoom(chatRoom.getId());
 
     // Then
     assertThat(mono).emitsExactly(chatRoom);
@@ -38,10 +43,11 @@ public class ChatHomeTest
   {
     // Given
     ChatHomeService chatHomeService = mock(ChatHomeService.class);
-    ChatHome chatHome = new ChatHome(chatHomeService, Flux.empty());
+    when(chatHomeService.getChatRoom(any(UUID.class))).thenReturn(Mono.empty());
+    ChatHome chatHome = new ChatHome(chatHomeService);
 
     // When
-    Mono<ChatRoom> mono = chatHome.getChatroom(UUID.randomUUID());
+    Mono<ChatRoom> mono = chatHome.getChatRoom(UUID.randomUUID());
 
     // Then
     assertThat(mono).sendsError();
index a4ff04f..fd413c3 100644 (file)
@@ -25,24 +25,24 @@ public class LocalJsonFilesStorageStrategyIT
 {
   final static Path path = Paths.get("target","local-json-files");
 
-  InMemoryChatHomeService service;
+  InMemoryChatHomeService chatHomeService;
   StorageStrategy storageStrategy;
   ChatHome chathome;
 
   void start()
   {
     Clock clock = Clock.systemDefaultZone();
-    service = new InMemoryChatHomeService(clock, 8);
     ObjectMapper mapper = new ObjectMapper();
     mapper.registerModule(new JavaTimeModule());
     mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
-    storageStrategy = new LocalJsonFilesStorageStrategy(path, mapper, service);
-    chathome = new ChatHome(service, storageStrategy.readChatrooms());
+    storageStrategy = new LocalJsonFilesStorageStrategy(path, clock, 8, mapper);
+    chatHomeService = new InMemoryChatHomeService(storageStrategy.readChatrooms(), clock, 8);
+    chathome = new ChatHome(chatHomeService);
   }
 
   void stop()
   {
-    storageStrategy.writeChatrooms(chathome.list());
+    storageStrategy.writeChatrooms(chathome.getChatRooms());
   }
 
   @Test
@@ -50,7 +50,7 @@ public class LocalJsonFilesStorageStrategyIT
   {
     start();
 
-    assertThat(chathome.list().toStream()).hasSize(0);
+    assertThat(chathome.getChatRooms().toStream()).hasSize(0);
 
     ChatRoom chatroom = chathome.createChatroom("FOO").block();
     Message m1 = chatroom.addMessage(1l,"Peter", "Hallo, ich heiße Peter!").block();
@@ -58,19 +58,19 @@ public class LocalJsonFilesStorageStrategyIT
     Message m3 = chatroom.addMessage(2l, "Peter", "Willst du mit mir gehen?").block();
     Message m4 = chatroom.addMessage(1l, "Klaus", "Ja? Nein? Vielleicht??").block();
 
-    assertThat(chathome.list().toStream()).containsExactlyElementsOf(List.of(chatroom));
-    assertThat(chathome.getChatroom(chatroom.getId())).emitsExactly(chatroom);
+    assertThat(chathome.getChatRooms().toStream()).containsExactlyElementsOf(List.of(chatroom));
+    assertThat(chathome.getChatRoom(chatroom.getId())).emitsExactly(chatroom);
     assertThat(chathome
-        .getChatroom(chatroom.getId())
+        .getChatRoom(chatroom.getId())
         .flatMapMany(cr -> cr.getMessages())).emitsExactly(m1, m2, m3, m4);
 
     stop();
     start();
 
-    assertThat(chathome.list().toStream()).containsExactlyElementsOf(List.of(chatroom));
-    assertThat(chathome.getChatroom(chatroom.getId())).emitsExactly(chatroom);
+    assertThat(chathome.getChatRooms().toStream()).containsExactlyElementsOf(List.of(chatroom));
+    assertThat(chathome.getChatRoom(chatroom.getId())).emitsExactly(chatroom);
     assertThat(chathome
-        .getChatroom(chatroom.getId())
+        .getChatRoom(chatroom.getId())
         .flatMapMany(cr -> cr.getMessages())).emitsExactly(m1, m2, m3, m4);
   }