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(empty -> log.info("Restored {}", this))
90 .doOnError(throwable -> log.error("Could not restore {}", this));
95 public Mono<ChatRoomInfo> createChatRoom(UUID id, String name)
97 log.info("Creating ChatRoom with buffer-size {}", bufferSize);
98 ChatMessageService service = new InMemoryChatMessageService(id);
99 ChatRoomInfo chatRoomInfo = new ChatRoomInfo(id, name, shard);
100 this.chatRoomInfo.put(id, chatRoomInfo);
101 ChatRoomData chatRoomData = new ChatRoomData(clock, service, bufferSize);
102 this.chatRoomData.put(id, chatRoomData);
103 return Mono.just(chatRoomInfo);
107 public Mono<ChatRoomInfo> getChatRoomInfo(UUID id)
110 .justOrEmpty(chatRoomInfo.get(id))
111 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
115 public Flux<ChatRoomInfo> getChatRoomInfo()
117 return Flux.fromIterable(chatRoomInfo.values());
121 public Mono<ChatRoomData> getChatRoomData(UUID id)
124 .justOrEmpty(chatRoomData.get(id))
125 .switchIfEmpty(Mono.error(() -> new UnknownChatroomException(id)));
129 public Mono<String[]> getShardOwners()
135 public String toString()
137 return SimpleChatHomeService.class.getSimpleName() + ", shard=" + shard;