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,
41 log.info("Created ChatRoom {} with buffer-size {}", id, bufferSize);
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();
54 synchronized public Mono<Message> addMessage(
59 Matcher matcher = VALID_USER.matcher(user);
60 if (!matcher.matches())
61 throw new InvalidUsernameException(user);
63 Message.MessageKey key = Message.MessageKey.of(user, id);
66 .flatMap(existing -> text.equals(existing.getMessageText())
68 : Mono.error(() -> new MessageMutationException(existing, text)))
71 .fromSupplier(() ->service.persistMessage(key, LocalDateTime.now(clock), text))
74 Sinks.EmitResult result = sink.tryEmitNext(m);
75 if (result.isFailure())
77 log.warn("Emitting of message failed with {} for {}", result.name(), m);
83 public Mono<Message> getMessage(String username, Long messageId)
85 Message.MessageKey key = Message.MessageKey.of(username, messageId);
86 return service.getMessage(key);
89 synchronized public Flux<Message> listen()
93 .doOnCancel(() -> sink = createSink()); // Sink hast to be recreated on auto-cancel!
96 public Flux<Message> getMessages()
98 return getMessages(0, Long.MAX_VALUE);
101 public Flux<Message> getMessages(long first, long last)
103 return service.getMessages(first, last);
106 private Sinks.Many<Message> createSink()
111 .onBackpressureBuffer(bufferSize);