X-Git-Url: http://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fde%2Fjuplo%2Fkafka%2Fchat%2Fbackend%2Fdomain%2FChatRoom.java;h=da5eba2a94306ff187a08be4d0ff9dddb817aee8;hb=7281b4220170f451062bb32e0d5f63ec48d141d3;hp=58efa54f09971174cb3659cf4a68cfa4e9765bcb;hpb=972a1f2c248a51740091c1fdf3526f0eb676639e;p=demos%2Fkafka%2Fchat diff --git a/src/main/java/de/juplo/kafka/chat/backend/domain/ChatRoom.java b/src/main/java/de/juplo/kafka/chat/backend/domain/ChatRoom.java index 58efa54f..da5eba2a 100644 --- a/src/main/java/de/juplo/kafka/chat/backend/domain/ChatRoom.java +++ b/src/main/java/de/juplo/kafka/chat/backend/domain/ChatRoom.java @@ -7,10 +7,13 @@ import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; +import reactor.core.publisher.SynchronousSink; import java.time.Clock; import java.time.LocalDateTime; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @Slf4j @@ -18,27 +21,37 @@ import java.util.*; @ToString(of = { "id", "name" }) public class ChatRoom { + public final static Pattern VALID_USER = Pattern.compile("^[a-z0-9-]{2,}$"); @Getter private final UUID id; @Getter private final String name; + @Getter + private final int shard; private final Clock clock; private final ChatRoomService service; private final int bufferSize; private Sinks.Many sink; + public ChatRoom( UUID id, String name, + int shard, Clock clock, ChatRoomService service, int bufferSize) { + log.info("Created ChatRoom {} with buffer-size {}", id, bufferSize); this.id = id; this.name = name; + this.shard = shard; this.clock = clock; this.service = service; this.bufferSize = bufferSize; + // @RequiredArgsConstructor unfortunately not possible, because + // the `bufferSize` is not set, if `createSink()` is called + // from the variable declaration! this.sink = createSink(); } @@ -48,15 +61,27 @@ public class ChatRoom String user, String text) { + Matcher matcher = VALID_USER.matcher(user); + if (!matcher.matches()) + throw new InvalidUsernameException(user); + Message.MessageKey key = Message.MessageKey.of(user, id); return service .getMessage(key) - .flatMap(existing -> text.equals(existing.getMessageText()) - ? Mono.just(existing) - : Mono.error(() -> new MessageMutationException(existing, text))) + .handle((Message existing, SynchronousSink sink) -> + { + if (existing.getMessageText().equals(text)) + { + sink.next(existing); + } + else + { + sink.error(new MessageMutationException(existing, text)); + } + }) .switchIfEmpty( Mono - .just(service.persistMessage(key, LocalDateTime.now(clock), text)) + .defer(() -> service.persistMessage(key, LocalDateTime.now(clock), text)) .doOnNext(m -> { Sinks.EmitResult result = sink.tryEmitNext(m);