reactor.core.publisher.Operators Java Examples

The following examples show how to use reactor.core.publisher.Operators. 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: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 7 votes vote down vote up
@Test
public void assertDroppedErrorsFailureWrongCount() {
	Throwable err1 = new IllegalStateException("boom1");
	Throwable err2 = new IllegalStateException("boom2");
	Throwable err3 = new IllegalStateException("boom3");
	try {
		StepVerifier.create(Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			s.onError(err1);
			s.onError(err2);
			s.onError(err3);
		}).buffer(1))
		            .expectError()
		            .verifyThenAssertThat()
		            .hasDroppedErrors()
		            .hasDroppedErrors(3);
		fail("expected an AssertionError");
	}
	catch (AssertionError ae) {
		assertThat(ae).hasMessage("Expected exactly 3 dropped errors, 2 found.");
	}
}
 
Example #2
Source File: BaseOperatorTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
final PO fluxState(OperatorScenario<I, PI, O, PO> scenario, boolean conditional) {
	Flux<I> source = Flux.from(s -> {
		Scannable t = Scannable.from(s);
		assertThat(t.scan(Attr.ERROR)).isNull();
		assertThat(t.scanOrDefault(Attr.TERMINATED, false)).isFalse();

			if (scenario.prefetch() != -1) {
				assertThat(t.scan(Attr.PREFETCH)).isEqualTo(scenario.prefetch());
			}

		touchTreeState(s);

		s.onSubscribe(Operators.emptySubscription());
		s.onSubscribe(Operators.emptySubscription()); //noop path
		s.onSubscribe(Operators.cancelledSubscription()); //noop path
		s.onComplete();
		touchTreeState(s);
		if (scenario.shouldAssertPostTerminateState()) {
			assertThat(t.scanOrDefault(Attr.TERMINATED, true)).isTrue();
		}
	});

	return applyStateScenario(scenario, conditional, source);
}
 
Example #3
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
private void updateRequested(Event<?> event) {
	RequestEvent requestEvent = null;
	if (event instanceof RequestEvent) requestEvent = (RequestEvent) event;
	else if (event instanceof SubscriptionTaskEvent) {
		SubscriptionTaskEvent ste = (SubscriptionTaskEvent) event;
		if (ste.delegate instanceof RequestEvent) {
			requestEvent = (RequestEvent) ste.delegate;
		}
	}

	if (requestEvent == null) {
		return;
	}
	else if (requestEvent.isBounded()) {
		Operators.addCap(REQUESTED, this, requestEvent.getRequestAmount());

	}
	else {
		REQUESTED.set(this, Long.MAX_VALUE);
	}
}
 
Example #4
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(CoreSubscriber<? super Void> s) {
	if (!parent.markSentHeaders()) {
		Operators.error(s,
				new IllegalStateException("headers have already been sent"));
		return;
	}
	Subscription subscription = Operators.emptySubscription();
	s.onSubscribe(subscription);
	if (parent.channel()
	          .eventLoop()
	          .inEventLoop()) {
		_subscribe(s);
	}
	else {
		parent.channel()
		      .eventLoop()
		      .execute(() -> _subscribe(s));
	}
}
 
Example #5
Source File: ReconnectMono.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete() {
  final Subscription s = this.s;
  final T value = this.value;

  if (s == Operators.cancelledSubscription() || !S.compareAndSet(this, s, null)) {
    this.doFinally();
    return;
  }

  final ResolvingInner<T> p = this.parent;
  if (value == null) {
    p.terminate(new IllegalStateException("Source completed empty"));
  } else {
    p.complete(value);
  }
}
 
Example #6
Source File: AssertSubscriber.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the Subscription once but does not request anything.
 *
 * @param s the Subscription to set
 * @return true if successful, false if the current subscription is not null
 */
protected final boolean setWithoutRequesting(Subscription s) {
  Objects.requireNonNull(s, "s");
  for (; ; ) {
    Subscription a = this.s;
    if (a == Operators.cancelledSubscription()) {
      s.cancel();
      return false;
    }
    if (a != null) {
      s.cancel();
      Operators.reportSubscriptionSet();
      return false;
    }

    if (S.compareAndSet(this, null, s)) {
      return true;
    }
  }
}
 
Example #7
Source File: MonoSendMany.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void onInterruptionCleanup() {
	//"FutureReturnValueIgnored" this is deliberate
	ctx.channel()
	   .closeFuture()
	   .removeListener(this);

	Queue<I> queue = this.queue;
	if (queue == null) {
		return;
	}
	Context context = null;
	while (!queue.isEmpty()) {
		I sourceMessage = queue.poll();
		if (sourceMessage != null) {
			parent.sourceCleanup.accept(sourceMessage);
			if (context == null) {
				context = actual.currentContext();
			}
			Operators.onDiscard(sourceMessage, context);
		}
	}
}
 
Example #8
Source File: UnboundedProcessor.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
  if (done || cancelled) {
    Operators.onNextDropped(t, currentContext());
    release(t);
    return;
  }

  if (!queue.offer(t)) {
    Throwable ex =
        Operators.onOperatorError(null, Exceptions.failWithOverflow(), t, currentContext());
    onError(Operators.onOperatorError(null, ex, t, currentContext()));
    release(t);
    return;
  }
  drain();
}
 
Example #9
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void assertDroppedElementsFailureOneExtra() {
	try {
		StepVerifier.create(Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			s.onNext("foo");
			s.onComplete();
			s.onNext("bar");
			s.onNext("baz");
		}).take(3))
		            .expectNext("foo")
		            .expectComplete()
		            .verifyThenAssertThat()
		            .hasDropped("foo");
		fail("expected an AssertionError");
	}
	catch (AssertionError ae) {
		assertThat(ae).hasMessage("Expected dropped elements to contain <[foo]>, was <[bar, baz]>.");
	}
}
 
Example #10
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void assertDroppedElementsAllPass() {
	StepVerifier.create(Flux.from(s -> {
		s.onSubscribe(Operators.emptySubscription());
		s.onNext("foo");
		s.onComplete();
		s.onNext("bar");
		s.onNext("baz");
	}).take(3))
	            .expectNext("foo")
	            .expectComplete()
	            .verifyThenAssertThat()
	            .hasDroppedElements()
	            .hasDropped("baz")
	            .hasDroppedExactly("baz", "bar");
}
 
Example #11
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable t) {
  final Subscription s = this.s;

  if (s == Operators.cancelledSubscription()
      || S.getAndSet(this, Operators.cancelledSubscription())
          == Operators.cancelledSubscription()) {
    this.doFinally();
    Operators.onErrorDropped(t, Context.empty());
    return;
  }

  this.doFinally();
  // terminate upstream which means retryBackoff has exhausted
  this.terminate(t);
}
 
Example #12
Source File: SimplePool.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable throwable) {
    QueuePooledRef<T> slot = pooledRef;
    pooledRef = null;
    if (slot == null) {
        Operators.onErrorDropped(throwable, actual.currentContext());
        return;
    }

    //some operators might immediately produce without request (eg. fromRunnable)
    // we decrement ACQUIRED EXACTLY ONCE to indicate that the poolable was released by the user
    if (ONCE.compareAndSet(this, 0, 1)) {
        ACQUIRED.decrementAndGet(pool);
    }

    //TODO should we separate reset errors?
    pool.metricsRecorder.recordResetLatency(pool.clock.millis() - start);

    if (slot.markInvalidate()) {
        pool.destroyPoolable(slot).subscribe(null, null, pool::drain); //TODO manage errors?
    }

    actual.onError(throwable);
}
 
Example #13
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void assertNotDroppedElementsFailureOneDrop() {
	try {
		StepVerifier.create(Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			s.onNext("foo");
			s.onComplete();
			s.onNext("bar");
		}).take(2))
		            .expectNext("foo")
		            .expectComplete()
		            .verifyThenAssertThat()
		            .hasNotDroppedElements();
		fail("expected an AssertionError");
	}
	catch (AssertionError ae) {
		assertThat(ae).hasMessage("Expected no dropped elements, found <[bar]>.");
	}
}
 
Example #14
Source File: AssertSubscriber.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
protected final void normalRequest(long n) {
  Subscription a = s;
  if (a != null) {
    a.request(n);
  } else {
    Operators.addCap(REQUESTED, this, n);

    a = s;

    if (a != null) {
      long r = REQUESTED.getAndSet(this, 0L);

      if (r != 0L) {
        a.request(r);
      }
    }
  }
}
 
Example #15
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete() {
  final Subscription s = this.s;
  final RSocket value = this.value;

  if (s == Operators.cancelledSubscription() || !S.compareAndSet(this, s, null)) {
    this.doFinally();
    return;
  }

  if (value == null) {
    this.terminate(new IllegalStateException("Source completed empty"));
  } else {
    this.complete(value);
  }
}
 
Example #16
Source File: MonoAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #17
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void assertOperatorErrorsNotSatisfying() {
	Throwable err1 = new IllegalStateException("boom1");
	Throwable err2 = new IllegalStateException("boom2");
	Throwable err3 = new IllegalStateException("boom3");
	try {
		StepVerifier.create(Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			s.onError(err1);
			Operators.onOperatorError(err2, Context.empty());
			Operators.onOperatorError(err3, Context.empty());
		}).buffer(1))
		            .expectError()
		            .verifyThenAssertThat()
		            .hasOperatorErrorsSatisfying(c -> assertThat(c).hasSize(3));
		fail("expected an AssertionError");
	}
	catch (AssertionError ae) {
		assertThat(ae).hasMessageStartingWith("\nExpected size:<3> but was:<2> in:\n")
		              .hasMessageContaining("boom2")
		              .hasMessageContaining("boom3");
	}
}
 
Example #18
Source File: MonoSendMany.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
void trySchedule(@Nullable Object data) {
	if (WIP.getAndIncrement(this) == 0) {
		try {
			if (eventLoop.inEventLoop()) {
				run();
				return;
			}
			eventLoop.execute(this);
		}
		catch (Throwable t) {
			if(Operators.terminate(SUBSCRIPTION, this)) {
				onInterruptionCleanup();
				actual.onError(Operators.onRejectedExecution(t, null, null, data, actual.currentContext()));
			}
		}
	}
}
 
Example #19
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
public static <T>
    Function<SpanContext, Function<? super Publisher<T>, ? extends Publisher<T>>> traceAsChild(
        Tracer tracer, String name, Tag... tags) {
  return (spanContext) -> {
    if (spanContext == null) {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber, subscriber.currentContext(), tracer, null, name, tags));
    } else {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber,
                  subscriber.currentContext(),
                  tracer,
                  null,
                  spanContext,
                  name,
                  tags));
    }
  };
}
 
Example #20
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void assertDroppedErrorsNotMatching() {
	Throwable err1 = new IllegalStateException("boom1");
	Throwable err2 = new IllegalStateException("boom2");
	Throwable err3 = new IllegalStateException("boom3");
	try {
		StepVerifier.create(Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			s.onError(err1);
			s.onError(err2);
			s.onError(err3);
		}).buffer(1))
		            .expectError()
		            .verifyThenAssertThat()
		            .hasDroppedErrorsMatching(c -> c.size() == 3);
		fail("expected an AssertionError");
	}
	catch (AssertionError ae) {
		assertThat(ae).hasMessage("Expected collection of dropped errors matching the " +
				"given predicate, did not match: <[java.lang.IllegalStateException: boom2, " +
				"java.lang.IllegalStateException: boom3]>.");
	}
}
 
Example #21
Source File: MonoSendMany.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void cancel() {
	if (!Operators.terminate(SUBSCRIPTION, this)) {
		return;
	}
	if (WIP.getAndIncrement(this) == 0) {
		onInterruptionCleanup();
	}
}
 
Example #22
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Subscription s) {
  if (Operators.validate(this.s, s)) {
    this.s = s;
    this.actual.onSubscribe(this.second);
  }
}
 
Example #23
Source File: InheritableBaseSubscriber.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete() {
    if (S.getAndSet(this, Operators.cancelledSubscription()) != Operators
        .cancelledSubscription()) {
        //we're sure it has not been concurrently cancelled
        try {
            hookOnComplete();
        } catch (Throwable throwable) {
            //onError itself will short-circuit due to the CancelledSubscription being push above
            hookOnError(Operators.onOperatorError(throwable, currentContext()));
        } finally {
            safeHookFinally(SignalType.ON_COMPLETE);
        }
    }
}
 
Example #24
Source File: InheritableBaseSubscriber.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(Throwable t) {
    Objects.requireNonNull(t, "onError");

    if (S.getAndSet(this, Operators.cancelledSubscription()) == Operators
        .cancelledSubscription()) {
        // Already cancelled concurrently

        // Workaround for Sentinel BlockException:
        // Here we add a predicate method to decide whether exception should be dropped implicitly
        // or call the {@code onErrorDropped} hook.
        if (shouldCallErrorDropHook()) {
            Operators.onErrorDropped(t, currentContext());
        }

        return;
    }

    try {
        hookOnError(t);
    } catch (Throwable e) {
        e = Exceptions.addSuppressed(e, t);
        Operators.onErrorDropped(e, currentContext());
    } finally {
        safeHookFinally(SignalType.ON_ERROR);
    }
}
 
Example #25
Source File: InheritableBaseSubscriber.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public final void request(long n) {
    if (Operators.validate(n)) {
        Subscription s = this.subscription;
        if (s != null) {
            s.request(n);
        }
    }
}
 
Example #26
Source File: MonoRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
    long waitDuration = rateLimiter.reservePermission();
    if (waitDuration >= 0) {
        if (waitDuration > 0) {
            Mono.delay(Duration.ofNanos(waitDuration))
                .subscribe(delay -> source.subscribe(new RateLimiterSubscriber<>(actual)));
        } else {
            source.subscribe(new RateLimiterSubscriber<>(actual));
        }
    } else {
        Operators.error(actual, createRequestNotPermitted(rateLimiter));
    }
}
 
Example #27
Source File: TestCallStreamObserverProducer.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static long add(TestCallStreamObserverProducer o, long n) {
    for (;;) {
        long r = REQUESTED.get(o);
        if (r == Long.MAX_VALUE) {
            return Long.MAX_VALUE;
        }
        long u = Operators.addCap(r, n);
        if ((REQUESTED).compareAndSet(o, r, u)) {
            return r;
        }
    }
}
 
Example #28
Source File: AssertSubscriber.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Atomically sets the single subscription and requests the missed amount from it.
 *
 * @param s
 * @return false if this arbiter is cancelled or there was a subscription already set
 */
protected final boolean set(Subscription s) {
	Objects.requireNonNull(s, "s");
	Subscription a = this.s;
	if (a == Operators.cancelledSubscription()) {
		s.cancel();
		return false;
	}
	if (a != null) {
		s.cancel();
		Operators.reportSubscriptionSet();
		return false;
	}

	if (S.compareAndSet(this, null, s)) {

		long r = REQUESTED.getAndSet(this, 0L);

		if (r != 0L) {
			s.request(r);
		}

		return true;
	}

	a = this.s;

	if (a != Operators.cancelledSubscription()) {
		s.cancel();
		return false;
	}

	Operators.reportSubscriptionSet();
	return false;
}
 
Example #29
Source File: ResolvingOperator.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void request(long n) {
  if (Operators.validate(n)) {
    long r = this.requested; // volatile read beforehand

    if (r > STATE_SUBSCRIBED) { // works only in case onSubscribe has not happened
      long u;
      for (; ; ) { // normal CAS loop with overflow protection
        if (r == Long.MAX_VALUE) {
          // if r == Long.MAX_VALUE then we dont care and we can loose this
          // request just in case of racing
          return;
        }
        u = Operators.addCap(r, n);
        if (REQUESTED.compareAndSet(this, r, u)) {
          // Means increment happened before onSubscribe
          return;
        } else {
          // Means increment happened after onSubscribe

          // update new state to see what exactly happened (onSubscribe |cancel | requestN)
          r = this.requested;

          // check state (expect -1 | -2 to exit, otherwise repeat)
          if (r < 0) {
            break;
          }
        }
      }
    }

    if (r == STATE_CANCELLED) { // if canceled, just exit
      return;
    }

    // if onSubscribe -> subscription exists (and we sure of that because volatile read
    // after volatile write) so we can execute requestN on the subscription
    this.s.request(n);
  }
}
 
Example #30
Source File: MetricsSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Subscription s) {
  if (Operators.validate(this.s, s)) {
    this.s = s;
    this.start = System.nanoTime();

    actual.onSubscribe(this);
  }
}