refactor: A `ChatRoom` does not have to remember its shard any more
[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     this.id = id;
42     this.name = name;
43     this.clock = clock;
44     this.service = service;
45     this.bufferSize = bufferSize;
46     // @RequiredArgsConstructor unfortunately not possible, because
47     // the `bufferSize` is not set, if `createSink()` is called
48     // from the variable declaration!
49     this.sink = createSink();
50   }
51
52
53   synchronized public Mono<Message> addMessage(
54       Long id,
55       String user,
56       String text)
57   {
58     Matcher matcher = VALID_USER.matcher(user);
59     if (!matcher.matches())
60       throw new InvalidUsernameException(user);
61
62     Message.MessageKey key = Message.MessageKey.of(user, id);
63     return service
64         .getMessage(key)
65         .flatMap(existing -> text.equals(existing.getMessageText())
66             ? Mono.just(existing)
67             : Mono.error(() -> new MessageMutationException(existing, text)))
68         .switchIfEmpty(
69             Mono
70                 .fromSupplier(() ->service.persistMessage(key, LocalDateTime.now(clock), text))
71                 .doOnNext(m ->
72                 {
73                   Sinks.EmitResult result = sink.tryEmitNext(m);
74                   if (result.isFailure())
75                   {
76                     log.warn("Emitting of message failed with {} for {}", result.name(), m);
77                   }
78                 }));
79   }
80
81
82   public Mono<Message> getMessage(String username, Long messageId)
83   {
84     Message.MessageKey key = Message.MessageKey.of(username, messageId);
85     return service.getMessage(key);
86   }
87
88   synchronized public Flux<Message> listen()
89   {
90     return sink
91         .asFlux()
92         .doOnCancel(() -> sink = createSink()); // Sink hast to be recreated on auto-cancel!
93   }
94
95   public Flux<Message> getMessages()
96   {
97     return getMessages(0, Long.MAX_VALUE);
98   }
99
100   public Flux<Message> getMessages(long first, long last)
101   {
102     return service.getMessages(first, last);
103   }
104
105   private Sinks.Many<Message> createSink()
106   {
107     return Sinks
108         .many()
109         .multicast()
110         .onBackpressureBuffer(bufferSize);
111   }
112 }