diff --git a/rsocket-core/src/main/java/io/rsocket/internal/UnicastMonoProcessor.java b/rsocket-core/src/main/java/io/rsocket/internal/UnicastMonoProcessor.java index d5958028a..35d4906ec 100644 --- a/rsocket-core/src/main/java/io/rsocket/internal/UnicastMonoProcessor.java +++ b/rsocket-core/src/main/java/io/rsocket/internal/UnicastMonoProcessor.java @@ -1,300 +1,175 @@ package io.rsocket.internal; import java.util.Objects; -import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.stream.Stream; import org.reactivestreams.Processor; -import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Disposable; -import reactor.core.Exceptions; import reactor.core.Scannable; import reactor.core.publisher.Mono; +import reactor.core.publisher.MonoProcessor; import reactor.core.publisher.Operators; import reactor.util.annotation.Nullable; import reactor.util.context.Context; +import reactor.util.function.Tuple2; public class UnicastMonoProcessor extends Mono implements Processor, CoreSubscriber, Disposable, Subscription, Scannable { - /** - * Create a {@link UnicastMonoProcessor} that will eagerly request 1 on {@link - * #onSubscribe(Subscription)}, cache and emit the eventual result for 1 or N subscribers. - * - * @param type of the expected value - * @return A {@link UnicastMonoProcessor}. - */ - public static UnicastMonoProcessor create() { - return new UnicastMonoProcessor<>(); - } - - volatile CoreSubscriber actual; - - @SuppressWarnings("rawtypes") - static final AtomicReferenceFieldUpdater ACTUAL = - AtomicReferenceFieldUpdater.newUpdater( - UnicastMonoProcessor.class, CoreSubscriber.class, "actual"); - - volatile int once; - @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater ONCE = AtomicIntegerFieldUpdater.newUpdater(UnicastMonoProcessor.class, "once"); - Throwable error; - volatile boolean terminated; - O value; + private final MonoProcessor processor; - volatile Subscription subscription; - static final AtomicReferenceFieldUpdater UPSTREAM = - AtomicReferenceFieldUpdater.newUpdater( - UnicastMonoProcessor.class, Subscription.class, "subscription"); + @SuppressWarnings("unused") + private volatile int once; - @Override - public final void cancel() { - if (isTerminated()) { - return; - } + private UnicastMonoProcessor() { + this.processor = MonoProcessor.create(); + } - final Subscription s = UPSTREAM.getAndSet(this, Operators.cancelledSubscription()); - if (s == Operators.cancelledSubscription()) { - return; - } + public static UnicastMonoProcessor create() { + return new UnicastMonoProcessor<>(); + } - if (s != null) { - s.cancel(); - } + @Override + public Stream actuals() { + return processor.actuals(); } @Override - @SuppressWarnings("unchecked") - public void dispose() { - final Subscription s = UPSTREAM.getAndSet(this, Operators.cancelledSubscription()); - if (s == Operators.cancelledSubscription()) { - return; - } + public boolean isScanAvailable() { + return processor.isScanAvailable(); + } - final CancellationException e = new CancellationException("Disposed"); - error = e; - value = null; - terminated = true; - if (s != null) { - s.cancel(); - } + @Override + public String name() { + return processor.name(); + } - final CoreSubscriber a = this.actual; - ACTUAL.lazySet(this, null); - if (a != null) { - a.onError(e); - } + @Override + public String stepName() { + return processor.stepName(); } - /** - * Return the produced {@link Throwable} error if any or null - * - * @return the produced {@link Throwable} error if any or null - */ - @Nullable - public final Throwable getError() { - return isTerminated() ? error : null; + @Override + public Stream steps() { + return processor.steps(); } - /** - * Indicates whether this {@code UnicastMonoProcessor} has been interrupted via cancellation. - * - * @return {@code true} if this {@code UnicastMonoProcessor} is cancelled, {@code false} - * otherwise. - */ - public boolean isCancelled() { - return isDisposed() && !isTerminated(); + @Override + public Stream parents() { + return processor.parents(); } - /** - * Indicates whether this {@code UnicastMonoProcessor} has been completed with an error. - * - * @return {@code true} if this {@code UnicastMonoProcessor} was completed with an error, {@code - * false} otherwise. - */ - public final boolean isError() { - return getError() != null; + @Override + @Nullable + public T scan(Attr key) { + return processor.scan(key); } - /** - * Indicates whether this {@code UnicastMonoProcessor} has been terminated by the source producer - * with a success or an error. - * - * @return {@code true} if this {@code UnicastMonoProcessor} is successful, {@code false} - * otherwise. - */ - public final boolean isTerminated() { - return terminated; + @Override + public T scanOrDefault(Attr key, T defaultValue) { + return processor.scanOrDefault(key, defaultValue); } @Override - public boolean isDisposed() { - return subscription == Operators.cancelledSubscription(); + public Stream> tags() { + return processor.tags(); } @Override - public final void onComplete() { - onNext(null); + public void onSubscribe(Subscription s) { + processor.onSubscribe(s); } @Override - @SuppressWarnings("unchecked") - public final void onError(Throwable cause) { - Objects.requireNonNull(cause, "onError cannot be null"); - - if (UPSTREAM.getAndSet(this, Operators.cancelledSubscription()) - == Operators.cancelledSubscription()) { - Operators.onErrorDropped(cause, currentContext()); - return; - } + public void onNext(O o) { + processor.onNext(o); + } - error = cause; - value = null; - terminated = true; + @Override + public void onError(Throwable t) { + processor.onError(t); + } - final CoreSubscriber a = actual; - ACTUAL.lazySet(this, null); - if (a != null) { - a.onError(cause); - } + @Nullable + public Throwable getError() { + return processor.getError(); } - @Override - @SuppressWarnings("unchecked") - public final void onNext(@Nullable O value) { - final Subscription s; - if ((s = UPSTREAM.getAndSet(this, Operators.cancelledSubscription())) - == Operators.cancelledSubscription()) { - if (value != null) { - Operators.onNextDropped(value, currentContext()); - } - return; - } + public boolean isCancelled() { + return processor.isCancelled(); + } - this.value = value; - terminated = true; + public boolean isError() { + return processor.isError(); + } - final CoreSubscriber a = actual; - ACTUAL.lazySet(this, null); - if (value == null) { - if (a != null) { - a.onComplete(); - } - } else { - if (s != null) { - s.cancel(); - } - - if (a != null) { - a.onNext(value); - a.onComplete(); - } - } + public boolean isSuccess() { + return processor.isSuccess(); } - @Override - public final void onSubscribe(Subscription subscription) { - if (Operators.setOnce(UPSTREAM, this, subscription)) { - subscription.request(Long.MAX_VALUE); - } + public boolean isTerminated() { + return processor.isTerminated(); } - /** - * Returns the value that completed this {@link UnicastMonoProcessor}. Returns {@code null} if the - * {@link UnicastMonoProcessor} has not been completed. If the {@link UnicastMonoProcessor} is - * completed with an error a RuntimeException that wraps the error is thrown. - * - * @return the value that completed the {@link UnicastMonoProcessor}, or {@code null} if it has - * not been completed - * @throws RuntimeException if the {@link UnicastMonoProcessor} was completed with an error - */ @Nullable public O peek() { - if (!isTerminated()) { - return null; - } + return processor.peek(); + } - if (value != null) { - return value; - } + public long downstreamCount() { + return processor.downstreamCount(); + } - if (error != null) { - RuntimeException re = Exceptions.propagate(error); - re = Exceptions.addSuppressed(re, new Exception("Mono#peek terminated with an error")); - throw re; - } + public boolean hasDownstreams() { + return processor.hasDownstreams(); + } - return null; + @Override + public void onComplete() { + processor.onComplete(); } @Override - public final void request(long n) { - Operators.validate(n); + public void request(long n) { + processor.request(n); } @Override - public Context currentContext() { - final CoreSubscriber a = this.actual; - return a != null ? a.currentContext() : Context.empty(); + public void cancel() { + processor.cancel(); } @Override - @Nullable - public Object scanUnsafe(Attr key) { - // touch guard - boolean c = isCancelled(); + public void dispose() { + processor.dispose(); + } - if (key == Attr.TERMINATED) { - return isTerminated(); - } - if (key == Attr.PARENT) { - return subscription; - } - if (key == Attr.ERROR) { - return error; - } - if (key == Attr.PREFETCH) { - return Integer.MAX_VALUE; - } - if (key == Attr.CANCELLED) { - return c; - } - return null; + @Override + public Context currentContext() { + return processor.currentContext(); + } + + @Override + public boolean isDisposed() { + return processor.isDisposed(); } - /** - * Return true if any {@link Subscriber} is actively subscribed - * - * @return true if any {@link Subscriber} is actively subscribed - */ - public final boolean hasDownstream() { - return actual != null; + @Override + public Object scanUnsafe(Attr key) { + return processor.scanUnsafe(key); } @Override public void subscribe(CoreSubscriber actual) { Objects.requireNonNull(actual, "subscribe"); if (once == 0 && ONCE.compareAndSet(this, 0, 1)) { - actual.onSubscribe(this); - ACTUAL.lazySet(this, actual); - if (isTerminated()) { - Throwable ex = error; - if (ex != null) { - actual.onError(ex); - } else { - O v = value; - if (v != null) { - actual.onNext(v); - } - actual.onComplete(); - } - ACTUAL.lazySet(this, null); - } + processor.subscribe(actual); } else { Operators.error( actual, diff --git a/rsocket-core/src/test/java/io/rsocket/internal/UnicastMonoProcessorTest.java b/rsocket-core/src/test/java/io/rsocket/internal/UnicastMonoProcessorTest.java deleted file mode 100644 index 20ed4b469..000000000 --- a/rsocket-core/src/test/java/io/rsocket/internal/UnicastMonoProcessorTest.java +++ /dev/null @@ -1,661 +0,0 @@ -package io.rsocket.internal; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assumptions.assumeThat; - -import java.lang.ref.WeakReference; -import java.time.Duration; -import java.util.Date; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import reactor.core.Scannable; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.publisher.MonoProcessor; -import reactor.core.publisher.Operators; -import reactor.test.StepVerifier; -import reactor.test.publisher.TestPublisher; -import reactor.util.function.Tuple2; - -public class UnicastMonoProcessorTest { - - @Test - public void noRetentionOnTermination() throws InterruptedException { - Date date = new Date(); - CompletableFuture future = new CompletableFuture<>(); - - WeakReference refDate = new WeakReference<>(date); - WeakReference> refFuture = new WeakReference<>(future); - - Mono source = Mono.fromFuture(future); - Mono data = - source.map(Date::toString).log().subscribeWith(UnicastMonoProcessor.create()).log(); - - future.complete(date); - assertThat(data.block()).isEqualTo(date.toString()); - - date = null; - future = null; - source = null; - System.gc(); - - int cycles; - for (cycles = 10; cycles > 0; cycles--) { - if (refDate.get() == null && refFuture.get() == null) break; - Thread.sleep(100); - } - - assumeThat(refFuture.get()).isNull(); - assertThat(refDate.get()).isNull(); - assertThat(cycles).isNotZero().isPositive(); - } - - @Test - public void noRetentionOnTerminationError() throws InterruptedException { - CompletableFuture future = new CompletableFuture<>(); - - WeakReference> refFuture = new WeakReference<>(future); - UnicastMonoProcessor processor = UnicastMonoProcessor.create(); - - Mono source = Mono.fromFuture(future); - Mono data = source.map(Date::toString).subscribeWith(processor); - - future.completeExceptionally(new IllegalStateException()); - - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(data::block); - - future = null; - source = null; - System.gc(); - - int cycles; - for (cycles = 10; cycles > 0; cycles--) { - if (refFuture.get() == null) break; - Thread.sleep(100); - } - - assumeThat(refFuture.get()).isNull(); - assertThat(cycles).isNotZero().isPositive(); - } - - @Test - public void noRetentionOnTerminationCancel() throws InterruptedException { - CompletableFuture future = new CompletableFuture<>(); - - WeakReference> refFuture = new WeakReference<>(future); - UnicastMonoProcessor processor = UnicastMonoProcessor.create(); - - Mono source = Mono.fromFuture(future); - Mono data = - source.map(Date::toString).transformDeferred((s) -> s.subscribeWith(processor)); - - future = null; - source = null; - - data.subscribe().dispose(); - processor.dispose(); - - data = null; - - System.gc(); - - int cycles; - for (cycles = 10; cycles > 0; cycles--) { - if (refFuture.get() == null) break; - Thread.sleep(100); - } - - assumeThat(refFuture.get()).isNull(); - assertThat(cycles).isNotZero().isPositive(); - } - - @Test(expected = IllegalStateException.class) - public void MonoProcessorResultNotAvailable() { - MonoProcessor mp = MonoProcessor.create(); - mp.block(Duration.ofMillis(1)); - } - - @Test - public void MonoProcessorRejectedDoOnSuccessOrError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.doOnSuccessOrError((s, f) -> ref.set(f)).subscribe(); - mp.onError(new Exception("test")); - - assertThat(ref.get()).hasMessage("test"); - assertThat(mp.isError()).isTrue(); - } - - @Test - public void MonoProcessorRejectedDoOnTerminate() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicInteger invoked = new AtomicInteger(); - - mp.doOnTerminate(invoked::incrementAndGet).subscribe(); - mp.onError(new Exception("test")); - - assertThat(invoked.get()).isEqualTo(1); - assertThat(mp.isError()).isTrue(); - } - - @Test - public void MonoProcessorRejectedSubscribeCallback() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.subscribe(v -> {}, ref::set); - mp.onError(new Exception("test")); - - assertThat(ref.get()).hasMessage("test"); - assertThat(mp.isError()).isTrue(); - } - - @Test - public void MonoProcessorSuccessDoOnSuccessOrError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.doOnSuccessOrError((s, f) -> ref.set(s)).subscribe(); - mp.onNext("test"); - - assertThat(ref.get()).isEqualToIgnoringCase("test"); - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.isError()).isFalse(); - } - - @Test - public void MonoProcessorSuccessDoOnTerminate() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicInteger invoked = new AtomicInteger(); - - mp.doOnTerminate(invoked::incrementAndGet).subscribe(); - mp.onNext("test"); - - assertThat(invoked.get()).isEqualTo(1); - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.isError()).isFalse(); - } - - @Test - public void MonoProcessorSuccessSubscribeCallback() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.subscribe(ref::set); - mp.onNext("test"); - - assertThat(ref.get()).isEqualToIgnoringCase("test"); - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.isError()).isFalse(); - } - - @Test - public void MonoProcessorRejectedDoOnError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.doOnError(ref::set).subscribe(); - mp.onError(new Exception("test")); - - assertThat(ref.get()).hasMessage("test"); - assertThat(mp.isError()).isTrue(); - } - - @Test(expected = NullPointerException.class) - public void MonoProcessorRejectedSubscribeCallbackNull() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.subscribe((Subscriber) null); - } - - @Test - public void MonoProcessorSuccessDoOnSuccess() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - mp.doOnSuccess(ref::set).subscribe(); - mp.onNext("test"); - - assertThat(ref.get()).isEqualToIgnoringCase("test"); - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.isError()).isFalse(); - } - - @Test - public void MonoProcessorSuccessChainTogether() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - mp.subscribe(mp2); - - mp.onNext("test"); - - assertThat(mp2.peek()).isEqualToIgnoringCase("test"); - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.isError()).isFalse(); - } - - @Test - public void MonoProcessorRejectedChainTogether() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - mp.subscribe(mp2); - - mp.onError(new Exception("test")); - - assertThat(mp2.getError()).hasMessage("test"); - assertThat(mp.isError()).isTrue(); - } - - @Test - public void MonoProcessorDoubleFulfill() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - StepVerifier.create(mp) - .then( - () -> { - mp.onNext("test1"); - mp.onNext("test2"); - }) - .expectNext("test1") - .expectComplete() - .verifyThenAssertThat() - .hasDroppedExactly("test2"); - } - - @Test - public void MonoProcessorNullFulfill() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onNext(null); - - assertThat(mp.isTerminated()).isTrue(); - assertThat(mp.peek()).isNull(); - } - - @Test - public void MonoProcessorMapFulfill() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onNext(1); - - UnicastMonoProcessor mp2 = - mp.map(s -> s * 2).subscribeWith(UnicastMonoProcessor.create()); - mp2.subscribe(); - - assertThat(mp2.isTerminated()).isTrue(); - assertThat(mp2.peek()).isEqualTo(2); - } - - @Test - public void MonoProcessorThenFulfill() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onNext(1); - - UnicastMonoProcessor mp2 = - mp.flatMap(s -> Mono.just(s * 2)).subscribeWith(UnicastMonoProcessor.create()); - mp2.subscribe(); - - assertThat(mp2.isTerminated()).isTrue(); - assertThat(mp2.peek()).isEqualTo(2); - } - - @Test - public void MonoProcessorMapError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onNext(1); - - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - - StepVerifier.create( - mp.map( - s -> { - throw new RuntimeException("test"); - }) - .subscribeWith(mp2), - 0) - .thenRequest(1) - .then( - () -> { - assertThat(mp2.isTerminated()).isTrue(); - assertThat(mp2.getError()).hasMessage("test"); - }) - .verifyErrorMessage("test"); - } - - @Test(expected = Exception.class) - public void MonoProcessorDoubleError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onError(new Exception("test")); - mp.onError(new Exception("test")); - } - - @Test(expected = Exception.class) - public void MonoProcessorDoubleSignal() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - - mp.onNext("test"); - mp.onError(new Exception("test")); - } - - @Test - public void zipMonoProcessor() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - UnicastMonoProcessor> mp3 = UnicastMonoProcessor.create(); - - StepVerifier.create(Mono.zip(mp, mp2).subscribeWith(mp3)) - .then(() -> assertThat(mp3.isTerminated()).isFalse()) - .then(() -> mp.onNext(1)) - .then(() -> assertThat(mp3.isTerminated()).isFalse()) - .then(() -> mp2.onNext(2)) - .then( - () -> { - assertThat(mp3.isTerminated()).isTrue(); - assertThat(mp3.peek().getT1()).isEqualTo(1); - assertThat(mp3.peek().getT2()).isEqualTo(2); - }) - .expectNextMatches(t -> t.getT1() == 1 && t.getT2() == 2) - .verifyComplete(); - } - - @Test - public void zipMonoProcessor2() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp3 = UnicastMonoProcessor.create(); - - StepVerifier.create(Mono.zip(d -> (Integer) d[0], mp).subscribeWith(mp3)) - .then(() -> assertThat(mp3.isTerminated()).isFalse()) - .then(() -> mp.onNext(1)) - .then( - () -> { - assertThat(mp3.isTerminated()).isTrue(); - assertThat(mp3.peek()).isEqualTo(1); - }) - .expectNext(1) - .verifyComplete(); - } - - @Test - public void zipMonoProcessorRejected() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - UnicastMonoProcessor> mp3 = UnicastMonoProcessor.create(); - - StepVerifier.create(Mono.zip(mp, mp2).subscribeWith(mp3)) - .then(() -> assertThat(mp3.isTerminated()).isFalse()) - .then(() -> mp.onError(new Exception("test"))) - .then( - () -> { - assertThat(mp3.isTerminated()).isTrue(); - assertThat(mp3.getError()).hasMessage("test"); - }) - .verifyErrorMessage("test"); - } - - @Test - public void filterMonoProcessor() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - StepVerifier.create(mp.filter(s -> s % 2 == 0).subscribeWith(mp2)) - .then(() -> mp.onNext(2)) - .then(() -> assertThat(mp2.isError()).isFalse()) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .then(() -> assertThat(mp2.peek()).isEqualTo(2)) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .expectNext(2) - .verifyComplete(); - } - - @Test - public void filterMonoProcessorNot() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - StepVerifier.create(mp.filter(s -> s % 2 == 0).subscribeWith(mp2)) - .then(() -> mp.onNext(1)) - .then(() -> assertThat(mp2.isError()).isFalse()) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .then(() -> assertThat(mp2.peek()).isNull()) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .verifyComplete(); - } - - @Test - public void filterMonoProcessorError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - StepVerifier.create( - mp.filter( - s -> { - throw new RuntimeException("test"); - }) - .subscribeWith(mp2)) - .then(() -> mp.onNext(2)) - .then(() -> assertThat(mp2.isError()).isTrue()) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .then(() -> assertThat(mp2.getError()).hasMessage("test")) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .verifyErrorMessage("test"); - } - - @Test - public void doOnSuccessMonoProcessorError() { - UnicastMonoProcessor mp = UnicastMonoProcessor.create(); - UnicastMonoProcessor mp2 = UnicastMonoProcessor.create(); - AtomicReference ref = new AtomicReference<>(); - - StepVerifier.create( - mp.doOnSuccess( - s -> { - throw new RuntimeException("test"); - }) - .doOnError(ref::set) - .subscribeWith(mp2)) - .then(() -> mp.onNext(2)) - .then(() -> assertThat(mp2.isError()).isTrue()) - .then(() -> assertThat(ref.get()).hasMessage("test")) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .then(() -> assertThat(mp2.getError()).hasMessage("test")) - .then(() -> assertThat(mp2.isTerminated()).isTrue()) - .verifyErrorMessage("test"); - } - - @Test - public void fluxCancelledByMonoProcessor() { - AtomicLong cancelCounter = new AtomicLong(); - Flux.range(1, 10) - .doOnCancel(cancelCounter::incrementAndGet) - .transformDeferred((s) -> s.subscribeWith(UnicastMonoProcessor.create())) - .subscribe(); - - assertThat(cancelCounter.get()).isEqualTo(1); - } - - @Test - public void cancelledByMonoProcessor() { - AtomicLong cancelCounter = new AtomicLong(); - UnicastMonoProcessor monoProcessor = - Mono.just("foo") - .doOnCancel(cancelCounter::incrementAndGet) - .subscribeWith(UnicastMonoProcessor.create()); - monoProcessor.subscribe(); - - assertThat(cancelCounter.get()).isEqualTo(1); - } - - @Test - public void scanProcessor() { - UnicastMonoProcessor test = UnicastMonoProcessor.create(); - Subscription subscription = Operators.emptySubscription(); - test.onSubscribe(subscription); - - assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE); - assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); - assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); - - test.onComplete(); - assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); - assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); - } - - @Test - public void scanProcessorCancelled() { - UnicastMonoProcessor test = UnicastMonoProcessor.create(); - Subscription subscription = Operators.emptySubscription(); - test.onSubscribe(subscription); - - assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE); - assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); - assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); - - test.cancel(); - assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); - assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); - } - - @Test - public void scanProcessorSubscription() { - UnicastMonoProcessor test = UnicastMonoProcessor.create(); - Subscription subscription = Operators.emptySubscription(); - test.onSubscribe(subscription); - - assertThat(test.scan(Scannable.Attr.ACTUAL)).isNull(); - assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(subscription); - } - - @Test - public void scanProcessorError() { - UnicastMonoProcessor test = UnicastMonoProcessor.create(); - Subscription subscription = Operators.emptySubscription(); - test.onSubscribe(subscription); - - test.onError(new IllegalStateException("boom")); - - assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom"); - assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); - } - - @Test - public void monoToProcessorConnects() { - TestPublisher tp = TestPublisher.create(); - UnicastMonoProcessor connectedProcessor = - tp.mono().subscribeWith(UnicastMonoProcessor.create()); - - assertThat(connectedProcessor.subscription).isNotNull(); - } - - @Test - public void monoToProcessorChain() { - StepVerifier.withVirtualTime( - () -> - Mono.just("foo") - .subscribeWith(UnicastMonoProcessor.create()) - .delayElement(Duration.ofMillis(500))) - .expectSubscription() - .expectNoEvent(Duration.ofMillis(500)) - .expectNext("foo") - .verifyComplete(); - } - - @Test - public void monoToProcessorChainColdToHot() { - AtomicInteger subscriptionCount = new AtomicInteger(); - Mono coldToHot = - Mono.just("foo") - .doOnSubscribe(sub -> subscriptionCount.incrementAndGet()) - .transformDeferred(s -> s.subscribeWith(UnicastMonoProcessor.create())) - .subscribeWith(UnicastMonoProcessor.create()) // this actually subscribes - .filter(s -> s.length() < 4); - - assertThat(subscriptionCount.get()).isEqualTo(1); - - coldToHot.block(); - assertThatThrownBy(coldToHot::block) - .hasMessage("UnicastMonoProcessor allows only a single Subscriber"); - assertThatThrownBy(coldToHot::block) - .hasMessage("UnicastMonoProcessor allows only a single Subscriber"); - - assertThat(subscriptionCount.get()).isEqualTo(1); - } - - @Test - public void monoProcessorBlockIsUnbounded() { - long start = System.nanoTime(); - - String result = - Mono.just("foo") - .delayElement(Duration.ofMillis(500)) - .subscribeWith(UnicastMonoProcessor.create()) - .block(); - - assertThat(result).isEqualTo("foo"); - assertThat(Duration.ofNanos(System.nanoTime() - start)) - .isGreaterThanOrEqualTo(Duration.ofMillis(500)); - } - - @Test - public void monoProcessorBlockNegativeIsImmediateTimeout() { - long start = System.nanoTime(); - - assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy( - () -> - Mono.just("foo") - .delayElement(Duration.ofMillis(500)) - .subscribeWith(UnicastMonoProcessor.create()) - .block(Duration.ofSeconds(-1))) - .withMessage("Timeout on blocking read for -1000 MILLISECONDS"); - - assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofMillis(500)); - } - - @Test - public void monoProcessorBlockZeroIsImmediateTimeout() { - long start = System.nanoTime(); - - assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy( - () -> - Mono.just("foo") - .delayElement(Duration.ofMillis(500)) - .subscribeWith(UnicastMonoProcessor.create()) - .block(Duration.ZERO)) - .withMessage("Timeout on blocking read for 0 MILLISECONDS"); - - assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofMillis(500)); - } - - @Test - public void disposeBeforeValueSendsCancellationException() { - UnicastMonoProcessor processor = UnicastMonoProcessor.create(); - AtomicReference e1 = new AtomicReference<>(); - AtomicReference e2 = new AtomicReference<>(); - AtomicReference e3 = new AtomicReference<>(); - AtomicReference late = new AtomicReference<>(); - - processor.subscribe(v -> Assertions.fail("expected first subscriber to error"), e1::set); - processor.subscribe(v -> Assertions.fail("expected second subscriber to error"), e2::set); - processor.subscribe(v -> Assertions.fail("expected third subscriber to error"), e3::set); - - processor.dispose(); - - assertThat(e1.get()).isInstanceOf(CancellationException.class); - assertThat(e2.get()).isInstanceOf(IllegalStateException.class); - assertThat(e3.get()).isInstanceOf(IllegalStateException.class); - - processor.subscribe(v -> Assertions.fail("expected late subscriber to error"), late::set); - assertThat(late.get()).isInstanceOf(IllegalStateException.class); - } -}