1 package de.juplo.kafka.chat.backend.implementation.inmemory;
3 import de.juplo.kafka.chat.backend.domain.*;
4 import de.juplo.kafka.chat.backend.domain.exceptions.UnknownChatroomException;
5 import de.juplo.kafka.chat.backend.implementation.StorageStrategy;
6 import lombok.extern.slf4j.Slf4j;
7 import reactor.core.publisher.Flux;
8 import reactor.core.publisher.Mono;
10 import java.time.Clock;
15 public class SimpleChatHomeService implements ChatHomeService
17 private final Integer shard;
18 private final Map<UUID, ChatRoomInfo> chatRoomInfo;
19 private final Map<UUID, ChatRoomData> chatRoomData;
20 private final Clock clock;
21 private final int bufferSize;
25 public SimpleChatHomeService(
35 public SimpleChatHomeService(
40 log.debug("Creating SimpleChatHomeService");
43 this.chatRoomInfo = new HashMap<>();
44 this.chatRoomData = new HashMap<>();
46 this.bufferSize = bufferSize;
50 Mono<Void> restore(StorageStrategy storageStrategy)
52 return storageStrategy
56 if (shard == null || info.getShard() == shard)
63 "SimpleChatHome for shard {} ignores not owned chat-room {}",
71 UUID chatRoomId = info.getId();
72 InMemoryChatMessageService chatMessageService =
73 new InMemoryChatMessageService(chatRoomId);
75 chatRoomInfo.put(chatRoomId, info);
83 return chatMessageService.restore(storageStrategy);
86 .doOnSuccess(empty -> log.info("Restored {}", this))
87 .doOnError(throwable -> log.error("Could not restore {}", this));
92 public Mono<ChatRoomInfo> createChatRoom(UUID id, String name)
94 log.info("Creating ChatRoom with buffer-size {}", bufferSize);
95 ChatMessageService service = new InMemoryChatMessageService(id);
96 ChatRoomInfo chatRoomInfo = new ChatRoomInfo(id, name, shard);
97 this.chatRoomInfo.put(id, chatRoomInfo);
98 ChatRoomData chatRoomData = new ChatRoomData(clock, service, bufferSize);
99 this.chatRoomData.put(id, chatRoomData);
100 return Mono.just(chatRoomInfo);
104 public Mono<ChatRoomInfo> getChatRoomInfo(UUID id)
107 .justOrEmpty(chatRoomInfo.get(id))
108 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
112 public Flux<ChatRoomInfo> getChatRoomInfo()
114 return Flux.fromIterable(chatRoomInfo.values());
118 public Mono<ChatRoomData> getChatRoomData(UUID id)
121 .justOrEmpty(chatRoomData.get(id))
122 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
126 public Mono<String[]> getShardOwners()
132 public String toString()
134 return SimpleChatHomeService.class.getSimpleName() + ", shard=" + shard;