/** * Handles a publish request. * * @param request The publish request to handle. * @return A completable future to be completed with the publish response. */ @SuppressWarnings("unchecked") private CompletableFuture<PublishResponse> handlePublish(PublishRequest request) { if (request.session() != id) return Futures.exceptionalFuture(new UnknownSessionException("incorrect session ID")); if (request.previousVersion() != eventVersion) { return CompletableFuture.completedFuture( PublishResponse.builder() .withStatus(Response.Status.ERROR) .withError(RaftError.Type.INTERNAL_ERROR) .withVersion(eventVersion) .build()); } eventVersion = request.eventVersion(); List<CompletableFuture<Void>> futures = new ArrayList<>(request.events().size()); for (Event<?> event : request.events()) { Listeners<Object> listeners = eventListeners.get(event.name()); if (listeners != null) { futures.add(listeners.accept(event.message())); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])) .handleAsync( (result, error) -> { completeVersion = Math.max(completeVersion, request.eventVersion()); return PublishResponse.builder() .withStatus(Response.Status.OK) .withVersion(eventVersion) .build(); }, context.executor()); }
@Override public Session publish(String event, Object message) { Assert.notNull(event, "event"); context .executor() .execute( () -> { Listeners<Object> listeners = eventListeners.get(event); if (listeners != null) { listeners.accept(message); } }); return this; }