1 package de.juplo.kafka.chat.backend.domain;
3 import lombok.EqualsAndHashCode;
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;
11 import java.time.Clock;
12 import java.time.LocalDateTime;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
19 @EqualsAndHashCode(of = { "id" })
20 @ToString(of = { "id", "name" })
23 public final static Pattern VALID_USER = Pattern.compile("^[a-z0-9-]{2,}$");
25 private final UUID id;
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;
38 ChatRoomService service,
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();
53 synchronized public Mono<Message> addMessage(
58 Matcher matcher = VALID_USER.matcher(user);
59 if (!matcher.matches())
60 throw new InvalidUsernameException(user);
62 Message.MessageKey key = Message.MessageKey.of(user, id);
65 .flatMap(existing -> text.equals(existing.getMessageText())
67 : Mono.error(() -> new MessageMutationException(existing, text)))
70 .fromSupplier(() ->service.persistMessage(key, LocalDateTime.now(clock), text))
73 Sinks.EmitResult result = sink.tryEmitNext(m);
74 if (result.isFailure())
76 log.warn("Emitting of message failed with {} for {}", result.name(), m);
82 public Mono<Message> getMessage(String username, Long messageId)
84 Message.MessageKey key = Message.MessageKey.of(username, messageId);
85 return service.getMessage(key);
88 synchronized public Flux<Message> listen()
92 .doOnCancel(() -> sink = createSink()); // Sink hast to be recreated on auto-cancel!
95 public Flux<Message> getMessages()
97 return getMessages(0, Long.MAX_VALUE);
100 public Flux<Message> getMessages(long first, long last)
102 return service.getMessages(first, last);
105 private Sinks.Many<Message> createSink()
110 .onBackpressureBuffer(bufferSize);