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)
55 return storageStrategy
59 if (shard == null || info.getShard() == shard)
66 "SimpleChatHome for shard {} ignores not owned chat-room {}",
74 UUID chatRoomId = info.getId();
75 InMemoryChatMessageService chatMessageService =
76 new InMemoryChatMessageService(chatRoomId);
78 chatRoomInfo.put(chatRoomId, info);
86 return chatMessageService.restore(storageStrategy);
89 .doOnSuccess(count -> log.info("Restored {} with {} chat-rooms", this, count))
90 .doOnError(throwable -> log.error("Could not restore {}", this))
96 public Mono<ChatRoomInfo> createChatRoom(UUID id, String name)
98 log.info("Creating ChatRoom with buffer-size {}", bufferSize);
99 ChatMessageService service = new InMemoryChatMessageService(id);
100 ChatRoomInfo chatRoomInfo = new ChatRoomInfo(id, name, shard);
101 this.chatRoomInfo.put(id, chatRoomInfo);
102 ChatRoomData chatRoomData = new ChatRoomData(clock, service, bufferSize);
103 this.chatRoomData.put(id, chatRoomData);
104 return Mono.just(chatRoomInfo);
108 public Mono<ChatRoomInfo> getChatRoomInfo(UUID id)
111 .justOrEmpty(chatRoomInfo.get(id))
112 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
116 public Flux<ChatRoomInfo> getChatRoomInfo()
118 return Flux.fromIterable(chatRoomInfo.values());
122 public Mono<ChatRoomData> getChatRoomData(UUID id)
125 .justOrEmpty(chatRoomData.get(id))
126 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
130 public Mono<String[]> getShardOwners()
136 public String toString()
138 return SimpleChatHomeService.class.getSimpleName() + ", shard=" + shard;