reactor.core.publisher.SignalType Java Examples

The following examples show how to use reactor.core.publisher.SignalType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GrpcClusterMembershipLeaderNameResolver.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Listener listener) {
    this.listener = listener;

    Duration retryInterval = Duration.ofMillis(configuration.getRetryIntervalMs());
    this.eventStreamDisposable = resolver.resolve()
            .materialize()
            .flatMap(signal -> {
                if (signal.getType() == SignalType.ON_NEXT) {
                    return Mono.just(signal.get());
                }
                if (signal.getType() == SignalType.ON_COMPLETE) {
                    return Mono.error(new IllegalStateException("Unexpected end of stream"));
                }
                if (signal.getType() == SignalType.ON_ERROR) {
                    return Mono.error(signal.getThrowable());
                }
                return Mono.empty();
            })
            .retryBackoff(Long.MAX_VALUE, retryInterval, retryInterval)
            .subscribe(
                    this::refresh,
                    e -> logger.warn("Cluster membership event stream terminated with an error", e),
                    () -> logger.info("Cluster membership event stream terminated")
            );
}
 
Example #2
Source File: ReactorMergeOperations.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public static <K> Mono<Map<K, Optional<Throwable>>> merge(Map<K, Mono<Void>> monos, int concurrencyLimit, Scheduler scheduler) {
    List<Flux<Pair<K, Optional<Throwable>>>> m2 = new ArrayList<>();
    monos.forEach((key, mono) -> {

        Flux<Pair<K, Optional<Throwable>>> x = mono.toProcessor().ignoreElement().materialize().map(result -> {
                    Optional<Throwable> error = result.getType() == SignalType.ON_ERROR
                            ? Optional.of(result.getThrowable())
                            : Optional.empty();
                    return Pair.of(key, error);
                }
        ).flux();
        m2.add(x);
    });

    return Flux.merge(Flux.fromIterable(m2), concurrencyLimit)
            .subscribeOn(scheduler)
            .collectList()
            .map(list -> list.stream().collect(Collectors.toMap(Pair::getLeft, Pair::getRight)));
}
 
Example #3
Source File: MicrometerResponderRSocket.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(SignalType signalType) {
	switch (signalType) {
	case CANCEL:
		if (this.cancel != null) {
			this.cancel.increment();
		}
		break;
	case ON_COMPLETE:
		if (this.onComplete != null) {
			this.onComplete.increment();
		}
		break;
	case ON_ERROR:
		if (this.onError != null) {
			this.onError.increment();
		}
		break;
	}
}
 
Example #4
Source File: MicrometerResponderRSocket.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Timer.Sample sample, SignalType signalType) {
	switch (signalType) {
	case CANCEL:
		if (this.cancel != null) {
			sample.stop(this.cancel);
		}
		break;
	case ON_COMPLETE:
		if (this.onComplete != null) {
			sample.stop(this.onComplete);
		}
		break;
	case ON_ERROR:
		if (this.onError != null) {
			sample.stop(this.onError);
		}
		break;
	}
}
 
Example #5
Source File: DynamoDBPositionsStorage.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public CompletionStage<Map<Integer, Long>> findAll(String topic, GroupId groupId) {
    var request = GetItemRequest.builder()
            .tableName(tableName)
            .consistentRead(true)
            .key(toKey(topic, groupId))
            .build();

    return Mono.fromCompletionStage(() -> dynamoDB.getItem(request))
            .<Map<Integer, Long>>handle((result, sink) -> {
                try {
                    var positions = toPositions(result.item());

                    if (positions == null) {
                        sink.complete();
                    } else {
                        sink.next(positions);
                    }
                } catch (Exception e) {
                    sink.error(e);
                }
            })
            .log(this.getClass().getName(), Level.WARNING, SignalType.ON_ERROR)
            .retryWhen(it -> it.delayElements(Duration.ofSeconds(1)))
            .toFuture();
}
 
Example #6
Source File: GuideTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void errorHandlingDoFinally() {
	LongAdder statsCancel = new LongAdder(); // <1>

	Flux<String> flux =
			Flux.just("foo", "bar")
			    .doFinally(type -> {
				    if (type == SignalType.CANCEL) // <2>
					    statsCancel.increment(); // <3>
			    })
			    .take(1); // <4>

	StepVerifier.create(flux)
                .expectNext("foo")
                .verifyComplete();

	assertThat(statsCancel.intValue()).isEqualTo(1);
}
 
Example #7
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("fireAndForget gathers metrics")
@Test
void fireAndForget() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.fireAndForget(payload)).thenReturn(Mono.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .fireAndForget(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("request.fnf", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #8
Source File: DefaultDockerRegistryClientMain.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static Flux<String> newResolveAction(String imageName, String imageTag, DefaultDockerRegistryClient client) {
    return client.getImageDigest(imageName, imageTag)
            .materialize()
            .map(signal ->
                    signal.getType() == SignalType.ON_NEXT
                            ? "Result=" + signal.get()
                            : "Error=" + signal.getThrowable().getCause().getMessage())
            .flux();
}
 
Example #9
Source File: ReactorExt.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * Ignore all elements, and emit empty {@link Optional#empty()} if stream completes normally or
 * {@link Optional#of(Object)} with the exception.
 */
public static Mono<Optional<Throwable>> emitError(Mono<?> source) {
    return source.ignoreElement().materialize().map(result ->
            result.getType() == SignalType.ON_ERROR
                    ? Optional.of(result.getThrowable())
                    : Optional.empty()
    );
}
 
Example #10
Source File: RecommendationServiceTests.java    From event-sourcing-microservices-example with GNU General Public License v3.0 5 votes vote down vote up
@Test
@Transactional
public void testSendReceive() {
	User kenny = new User(1L, "Kenny", "Bastani"),
			john = new User(2L, "John", "Doe"),
			paul = new User(3L, "Paul", "Doe"),
			ringo = new User(4L, "Ringo", "Doe"),
			george = new User(5L, "George", "Doe"),
			alice = new User(6L, "Alice", "Doe");

	userRepository.saveAll(Arrays.asList(kenny, john, paul, ringo, george, alice));

	friendRepository.addFriend(kenny.getId(), john.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(john.getId(), paul.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(paul.getId(), kenny.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(john.getId(), ringo.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(paul.getId(), ringo.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(john.getId(), george.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(john.getId(), alice.getId(), new Date().getTime(), new Date().getTime());
	friendRepository.addFriend(paul.getId(), alice.getId(), new Date().getTime(), new Date().getTime());

	RankedUser[] rankedUser = friendRepository.recommendedFriends(1L).toList().toArray(RankedUser[]::new);

	Flux.fromArray(rankedUser).map(RankedUser::toString).log(LOG, Level.INFO, true, SignalType.ON_NEXT)
			.subscribe();

	Assert.notEmpty(rankedUser, "Friend recommendation must not return an empty list or null");

	org.junit.Assert.assertArrayEquals(rankedUser,
			new RankedUser[]{new RankedUser(ringo, 2),
					new RankedUser(alice, 2),
					new RankedUser(george, 1)});
}
 
Example #11
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue940() {
	AtomicInteger counter = new AtomicInteger();
	Flux<String> response =
			Flux.interval(Duration.ofMillis(200))
			    .map(l -> "" + counter.getAndIncrement())
			    .doFinally(sig -> {
			        if (SignalType.ON_ERROR.equals(sig)) {
			            counter.getAndDecrement();
			        }
			    });

	disposableServer =
			HttpServer.create()
			          .port(0)
			          .wiretap(true)
			          .handle((req, res) -> res.sendString(response))
			          .bindNow();

	HttpClient client =
			HttpClient.create()
			          .port(disposableServer.port());

	doTestIssue940(client, "0", "1");

	doTestIssue940(client, "2", "3");
}
 
Example #12
Source File: HttpSendFileTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void sendFileAsync1024() throws IOException, URISyntaxException {
	doTestSendFileAsync((req, resp) -> resp.sendByteArray(req.receive()
	                                                         .asByteArray()
	                                                         .log("reply", Level.INFO, SignalType.REQUEST)),
			1024, null);
}
 
Example #13
Source File: RequestStream.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void next(SignalType signal) {
    Mono<Long> timer = sleepTime.isZero() ? Mono.just(0L) : Mono.delay(sleepTime, timedTaskScheduler);
    timer.subscribe(l -> {
        if (log.isDebugEnabled()) {
            log.debug("[B:{}] Ready to consume next request after {}", id.toString(), signal);
        }
        sleepTime = Duration.ZERO;
        request(1);
    }, t -> log.error("[B:{}] Error while scheduling next request", id.toString(), t));
}
 
Example #14
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(SignalType signalType) {
  switch (signalType) {
    case CANCEL:
      cancel.increment();
      break;
    case ON_COMPLETE:
      onComplete.increment();
      break;
    case ON_ERROR:
      onError.increment();
      break;
  }
}
 
Example #15
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Sample sample, SignalType signalType) {
  switch (signalType) {
    case CANCEL:
      sample.stop(cancel);
      break;
    case ON_COMPLETE:
      sample.stop(onComplete);
      break;
    case ON_ERROR:
      sample.stop(onError);
      break;
  }
}
 
Example #16
Source File: ReactorRabbitMQChannelPoolTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void notUsedChannelShouldBeClosedWhenPoolIsClosed() {
    ChannelPool channelPool = generateChannelPool(2);
    Channel channel = channelPool.getChannelMono().block();
    assertThat(channel.isOpen()).isTrue();
    channelPool.getChannelCloseHandler().accept(SignalType.ON_NEXT, channel);
    channelPool.close();
    assertThat(channel.isOpen()).isFalse();
}
 
Example #17
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("metadataPush gathers metrics")
@Test
void metadataPush() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.metadataPush(payload)).thenReturn(Mono.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .metadataPush(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("metadata.push", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #18
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("requestChannel gathers metrics")
@Test
void requestChannel() {
  Mono<Payload> payload = Mono.just(DefaultPayload.create("test-metadata", "test-data"));
  when(delegate.requestChannel(payload)).thenReturn(Flux.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .requestChannel(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("request.channel", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #19
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("requestResponse gathers metrics")
@Test
void requestResponse() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.requestResponse(payload)).thenReturn(Mono.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .requestResponse(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findTimer("request.response", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #20
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("requestStream gathers metrics")
@Test
void requestStream() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.requestStream(payload)).thenReturn(Flux.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .requestStream(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("request.stream", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #21
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
private Counter findCounter(String interactionModel, SignalType signalType) {
  return meterRegistry
      .get(String.format("rsocket.%s", interactionModel))
      .tag("signal.type", signalType.name())
      .tag("test-key", "test-value")
      .counter();
}
 
Example #22
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
private Timer findTimer(String interactionModel, SignalType signalType) {
  return meterRegistry
      .get(String.format("rsocket.%s", interactionModel))
      .tag("signal.type", signalType.name())
      .tag("test-key", "test-value")
      .timer();
}
 
Example #23
Source File: RequestOperator.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(Throwable t) {
  this.actual.onError(t);
  try {
    this.hookOnTerminal(SignalType.ON_ERROR);
  } catch (Throwable throwable) {
    Operators.onErrorDropped(throwable, currentContext());
  }
}
 
Example #24
Source File: RequestOperator.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete() {
  this.actual.onComplete();
  try {
    this.hookOnTerminal(SignalType.ON_COMPLETE);
  } catch (Throwable throwable) {
    Operators.onErrorDropped(throwable, currentContext());
  }
}
 
Example #25
Source File: ReactorRabbitMQChannelPool.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public BiConsumer<SignalType, Channel> getChannelCloseHandler() {
    return (signalType, channel) -> {
        borrowedChannels.remove(channel);
        if (!channel.isOpen() || signalType != SignalType.ON_COMPLETE) {
            invalidateObject(channel);
            return;
        }
        pool.returnObject(channel);
    };
}
 
Example #26
Source File: ReactorRabbitMQChannelPool.java    From james-project with Apache License 2.0 5 votes vote down vote up
@PreDestroy
@Override
public void close() {
    sender.close();
    borrowedChannels.forEach(channel -> getChannelCloseHandler().accept(SignalType.ON_NEXT, channel));
    borrowedChannels.clear();
    pool.close();
}
 
Example #27
Source File: InheritableBaseSubscriber.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public final void cancel() {
    if (Operators.terminate(S, this)) {
        try {
            hookOnCancel();
        } catch (Throwable throwable) {
            hookOnError(Operators.onOperatorError(subscription, throwable, currentContext()));
        } finally {
            safeHookFinally(SignalType.CANCEL);
        }
    }
}
 
Example #28
Source File: LiiklusService.java    From liiklus with MIT License 5 votes vote down vote up
public Mono<GetOffsetsReply> getOffsets(Mono<GetOffsetsRequest> request) {
    return request.flatMap(getOffsets -> Mono
            .fromCompletionStage(positionsStorage.findAll(
                    getOffsets.getTopic(),
                    GroupId.of(
                            getOffsets.getGroup(),
                            getOffsets.getGroupVersion()
                    )
            ))
            .defaultIfEmpty(emptyMap())
            .map(offsets -> GetOffsetsReply.newBuilder().putAllOffsets(offsets).build())
            .log("getOffsets", Level.SEVERE, SignalType.ON_ERROR)
    );
}
 
Example #29
Source File: LiiklusService.java    From liiklus with MIT License 5 votes vote down vote up
public Mono<Empty> ack(Mono<AckRequest> request) {
    return request
            .flatMap(ack -> {
                String topic;
                GroupId groupId;
                int partition;

                @SuppressWarnings("deprecation")
                var hasAssignment = ack.hasAssignment();
                if (hasAssignment) {
                    @SuppressWarnings("deprecation")
                    var assignment = ack.getAssignment();
                    var subscription = subscriptions.get(assignment.getSessionId());

                    if (subscription == null) {
                        log.warn("Subscription is null, returning empty Publisher. Request: {}", ack.toString().replace("\n", "\\n"));
                        return Mono.empty();
                    }

                    topic = subscription.getTopic();
                    groupId = subscription.getGroupId();
                    partition = assignment.getPartition();
                } else {
                    topic = ack.getTopic();
                    groupId = GroupId.of(ack.getGroup(), ack.getGroupVersion());
                    partition = ack.getPartition();
                }

                return Mono.fromCompletionStage(positionsStorage.update(
                        topic,
                        groupId,
                        partition,
                        ack.getOffset()
                ));
            })
            .thenReturn(Empty.getDefaultInstance())
            .log("ack", Level.SEVERE, SignalType.ON_ERROR);
}
 
Example #30
Source File: LiiklusService.java    From liiklus with MIT License 5 votes vote down vote up
public Flux<ReceiveReply> receive(Mono<ReceiveRequest> requestMono) {
    return requestMono
            .flatMapMany(request -> {
                String sessionId = request.getAssignment().getSessionId();
                int partition = request.getAssignment().getPartition();
                // TODO auto ack to the last known offset
                long lastKnownOffset = request.getLastKnownOffset();

                var storedSource = sources.containsKey(sessionId) ? sources.get(sessionId).get(partition) : null;

                if (storedSource == null) {
                    log.warn("Source is null, returning empty Publisher. Request: {}", request.toString().replace("\n", "\\n"));
                    return Mono.empty();
                }
                return getLatestOffsetsOfGroup(storedSource.getTopic(), storedSource.getGroupId().getName())
                        .map(it -> it.getOrDefault(partition, Optional.empty()).orElse(-1L))
                        .flatMapMany(latestAckedOffset -> {
                            return storedSource.getRecords()
                                    .as(flux -> {
                                        for (RecordPostProcessor processor : recordPostProcessorChain.getAll()) {
                                            flux = flux.transform(processor::postProcess);
                                        }
                                        return flux;
                                    })
                                    .map(record -> toReply(request.getFormat(), record, latestAckedOffset));
                        });
            })
            .log("receive", Level.SEVERE, SignalType.ON_ERROR);
}