fix: Fixed a NPE in `ShardedChatHome.getChatRooms()`
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / domain / ChatRoom.java
1 package de.juplo.kafka.chat.backend.domain;
2
3 import lombok.EqualsAndHashCode;
4 import lombok.Getter;
5 import lombok.ToString;
6 import lombok.extern.slf4j.Slf4j;
7 import reactor.core.publisher.Flux;
8 import reactor.core.publisher.Mono;
9 import reactor.core.publisher.Sinks;
10
11 import java.time.Clock;
12 import java.time.LocalDateTime;
13 import java.util.*;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17
18 @Slf4j
19 @EqualsAndHashCode(of = { "id" })
20 @ToString(of = { "id", "name" })
21 public class ChatRoom
22 {
23   public final static Pattern VALID_USER = Pattern.compile("^[a-z0-9-]{2,}$");
24   @Getter
25   private final UUID id;
26   @Getter
27   private final String name;
28   private final Clock clock;
29   private final ChatRoomService service;
30   private final int bufferSize;
31   private Sinks.Many<Message> sink;
32
33
34   public ChatRoom(
35       UUID id,
36       String name,
37       Clock clock,
38       ChatRoomService service,
39       int bufferSize)
40   {
41     log.info("Created ChatRoom {} with buffer-size {}", id, bufferSize);
42     this.id = id;
43     this.name = name;
44     this.clock = clock;
45     this.service = service;
46     this.bufferSize = bufferSize;
47     // @RequiredArgsConstructor unfortunately not possible, because
48     // the `bufferSize` is not set, if `createSink()` is called
49     // from the variable declaration!
50     this.sink = createSink();
51   }
52
53
54   synchronized public Mono<Message> addMessage(
55       Long id,
56       String user,
57       String text)
58   {
59     Matcher matcher = VALID_USER.matcher(user);
60     if (!matcher.matches())
61       throw new InvalidUsernameException(user);
62
63     Message.MessageKey key = Message.MessageKey.of(user, id);
64     return service
65         .getMessage(key)
66         .flatMap(existing -> text.equals(existing.getMessageText())
67             ? Mono.just(existing)
68             : Mono.error(() -> new MessageMutationException(existing, text)))
69         .switchIfEmpty(
70             Mono
71                 .fromSupplier(() ->service.persistMessage(key, LocalDateTime.now(clock), text))
72                 .doOnNext(m ->
73                 {
74                   Sinks.EmitResult result = sink.tryEmitNext(m);
75                   if (result.isFailure())
76                   {
77                     log.warn("Emitting of message failed with {} for {}", result.name(), m);
78                   }
79                 }));
80   }
81
82
83   public Mono<Message> getMessage(String username, Long messageId)
84   {
85     Message.MessageKey key = Message.MessageKey.of(username, messageId);
86     return service.getMessage(key);
87   }
88
89   synchronized public Flux<Message> listen()
90   {
91     return sink
92         .asFlux()
93         .doOnCancel(() -> sink = createSink()); // Sink hast to be recreated on auto-cancel!
94   }
95
96   public Flux<Message> getMessages()
97   {
98     return getMessages(0, Long.MAX_VALUE);
99   }
100
101   public Flux<Message> getMessages(long first, long last)
102   {
103     return service.getMessages(first, last);
104   }
105
106   private Sinks.Many<Message> createSink()
107   {
108     return Sinks
109         .many()
110         .multicast()
111         .onBackpressureBuffer(bufferSize);
112   }
113 }