From f6c05e77f4a117a38a14fa94abe4da8317c2083b Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Sat, 21 Mar 2020 21:41:43 +0200 Subject: [PATCH 01/10] provides a reconnectable Mono feature Signed-off-by: Oleh Dokuka --- rsocket-core/build.gradle | 1 + .../src/main/java/io/rsocket/Invalidate.java | 21 + .../main/java/io/rsocket/RSocketFactory.java | 144 ++- .../main/java/io/rsocket/ReconnectMono.java | 472 +++++++++ .../java/io/rsocket/RSocketReconnectTest.java | 170 ++++ .../java/io/rsocket/ReconnectMonoTests.java | 932 ++++++++++++++++++ .../test/java/io/rsocket/RetryTestUtils.java | 140 +++ 7 files changed, 1879 insertions(+), 1 deletion(-) create mode 100644 rsocket-core/src/main/java/io/rsocket/Invalidate.java create mode 100644 rsocket-core/src/main/java/io/rsocket/ReconnectMono.java create mode 100644 rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java create mode 100644 rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java create mode 100644 rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java diff --git a/rsocket-core/build.gradle b/rsocket-core/build.gradle index ca2ae0e65..899fa31a5 100644 --- a/rsocket-core/build.gradle +++ b/rsocket-core/build.gradle @@ -43,6 +43,7 @@ dependencies { // TODO: Remove after JUnit5 migration testCompileOnly 'junit:junit' testImplementation 'org.hamcrest:hamcrest-library' + testImplementation 'io.projectreactor.addons:reactor-extra' testRuntimeOnly 'org.junit.vintage:junit-vintage-engine' } diff --git a/rsocket-core/src/main/java/io/rsocket/Invalidate.java b/rsocket-core/src/main/java/io/rsocket/Invalidate.java new file mode 100644 index 000000000..ff7f74905 --- /dev/null +++ b/rsocket-core/src/main/java/io/rsocket/Invalidate.java @@ -0,0 +1,21 @@ +/* + * Copyright 2015-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.rsocket; + +interface Invalidate { + + void expire(); +} diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 44f64e550..8bf298fab 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -47,6 +47,9 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import org.reactivestreams.Publisher; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** Factory for creating RSocket clients and servers. */ @@ -95,6 +98,9 @@ default Start transport(ServerTransport transport) { public static class ClientRSocketFactory implements ClientTransportAcceptor { private static final String CLIENT_TAG = "client"; + private static final Function, ? extends Publisher> FAIL_WHEN_FACTORY = + f -> f.concatMap(Mono::error); + private SocketAcceptor acceptor = (setup, sendingSocket) -> Mono.just(new AbstractRSocket() {}); private Consumer errorConsumer = Throwable::printStackTrace; @@ -125,6 +131,8 @@ public static class ClientRSocketFactory implements ClientTransportAcceptor { private boolean multiSubscriberRequester = true; private boolean leaseEnabled; private Supplier> leasesSupplier = Leases::new; + private boolean reconnectEnabled; + private Function, ? extends Publisher> whenFactory = FAIL_WHEN_FACTORY; private ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; @@ -230,6 +238,129 @@ public ClientRSocketFactory singleSubscriberRequester() { return this; } + /** + * Enables a reconnectable, shared instance of {@code Mono} so every subscriber will + * observe the same RSocket instance up on connection establishment.
+ * For example: + * + *
{@code
+     * Mono sharedRSocketMono =
+     *   RSocketFactory
+     *                .connect()
+     *                .singleSubscriberRequester()
+     *                .reconnect()
+     *                .transport(transport)
+     *                .start();
+     *
+     *  RSocket r1 = sharedRSocketMono.block();
+     *  RSocket r2 = sharedRSocketMono.block();
+     *
+     *  assert r1 == r2;
+     *
+     * }
+ * + * Apart of the shared behavior, once the previous connection has been expired (e.g. connection + * has been disposed), the same instance of {@code Mono} reestablish connection without + * any extra effort.
+ * For example: + * + *
{@code
+     * Mono sharedRSocketMono =
+     *   RSocketFactory
+     *                .connect()
+     *                .singleSubscriberRequester()
+     *                .reconnect()
+     *                .transport(transport)
+     *                .start();
+     *
+     *  RSocket r1 = sharedRSocketMono.block();
+     *  RSocket r2 = sharedRSocketMono.block();
+     *
+     *  assert r1 == r2;
+     *
+     *  r1.dispose()
+     *
+     *  assert r2.isDisposed()
+     *
+     *  RSocket r3 = sharedRSocketMono.block();
+     *  RSocket r4 = sharedRSocketMono.block();
+     *
+     *
+     *  assert r1 != r3;
+     *  assert r4 == r3;
+     *
+     * }
+ * + * @return a shared instance of {@code Mono}. + */ + public ClientRSocketFactory reconnect() { + this.reconnectEnabled = true; + return this; + } + + /** + * Enables a reconnectable, shared instance of {@code Mono} so every subscriber will + * observe the same RSocket instance up on connection establishment.
+ * For example: + * + *
{@code
+     * Mono sharedRSocketMono =
+     *   RSocketFactory
+     *                .connect()
+     *                .singleSubscriberRequester()
+     *                .reconnect(fluxOfThrowables -> flux.concatMap(t -> Mono.delay(Duration.ofSeconds(1)).take(5))
+     *                .transport(transport)
+     *                .start();
+     *
+     *  RSocket r1 = sharedRSocketMono.block();
+     *  RSocket r2 = sharedRSocketMono.block();
+     *
+     *  assert r1 == r2;
+     *
+     * }
+ * + * Apart of the shared behavior, once the previous connection has been expired (e.g. connection + * has been disposed), the same instance of {@code Mono} reestablish connection without + * any extra effort.
+ * For example: + * + *
{@code
+     * Mono sharedRSocketMono =
+     *   RSocketFactory
+     *                .connect()
+     *                .singleSubscriberRequester()
+     *                .reconnect(fluxOfThrowables -> flux.concatMap(t -> Mono.delay(Duration.ofSeconds(1)).take(5))
+     *                .transport(transport)
+     *                .start();
+     *
+     *  RSocket r1 = sharedRSocketMono.block();
+     *  RSocket r2 = sharedRSocketMono.block();
+     *
+     *  assert r1 == r2;
+     *
+     *  r1.dispose()
+     *
+     *  assert r2.isDisposed()
+     *
+     *  RSocket r3 = sharedRSocketMono.block();
+     *  RSocket r4 = sharedRSocketMono.block();
+     *
+     *
+     *  assert r1 != r3;
+     *  assert r4 == r3;
+     *
+     * }
+ * + * @param whenFactory a retry factory applied for {@link Mono.retryWhen(whenFactory)} + * @return a shared instance of {@code Mono}. + */ + public ClientRSocketFactory reconnect( + Function, ? extends Publisher> whenFactory) { + this.whenFactory = Objects.requireNonNull(whenFactory); + this.reconnectEnabled = true; + return this; + } + public ClientRSocketFactory resume() { this.resumeEnabled = true; return this; @@ -392,6 +523,17 @@ public Mono start() { .sendOne(setupFrame) .thenReturn(wrappedRSocketRequester); }); + }) + .as( + source -> { + if (reconnectEnabled) { + return new ReconnectMono<>( + source.retryWhen(whenFactory), + Disposable::dispose, + (r, i) -> r.onClose().subscribe(null, null, i::expire)); + } else { + return source; + } }); } @@ -422,7 +564,7 @@ private ClientSetup clientSetup(DuplexConnection startConnection) { } private Mono newConnection() { - return transportClient.get().connect(mtu); + return Mono.fromSupplier(transportClient).flatMap(t -> t.connect(mtu)); } } } diff --git a/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java new file mode 100644 index 000000000..afe1dfd55 --- /dev/null +++ b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java @@ -0,0 +1,472 @@ +/* + * Copyright 2015-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket; + +import java.time.Duration; +import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +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.Operators; +import reactor.core.publisher.Operators.MonoSubscriber; +import reactor.util.annotation.Nullable; +import reactor.util.context.Context; + +final class ReconnectMono extends Mono implements Invalidate, Disposable, Scannable { + + final Mono source; + final BiConsumer onValueReceived; + final Consumer onValueExpired; + final ReconnectMainSubscriber mainSubscriber; + + volatile int wip; + + @SuppressWarnings("rawtypes") + static final AtomicIntegerFieldUpdater WIP = + AtomicIntegerFieldUpdater.newUpdater(ReconnectMono.class, "wip"); + + volatile ReconnectInner[] subscribers; + + @SuppressWarnings("rawtypes") + static final AtomicReferenceFieldUpdater SUBSCRIBERS = + AtomicReferenceFieldUpdater.newUpdater( + ReconnectMono.class, ReconnectInner[].class, "subscribers"); + + @SuppressWarnings("rawtypes") + static final ReconnectInner[] EMPTY_UNSUBSCRIBED = new ReconnectInner[0]; + + @SuppressWarnings("rawtypes") + static final ReconnectInner[] EMPTY_SUBSCRIBED = new ReconnectInner[0]; + + @SuppressWarnings("rawtypes") + static final ReconnectInner[] READY = new ReconnectInner[0]; + + @SuppressWarnings("rawtypes") + static final ReconnectInner[] TERMINATED = new ReconnectInner[0]; + + static final int ADDED_STATE = 0; + static final int READY_STATE = 1; + static final int TERMINATED_STATE = 2; + + T value; + Throwable t; + + ReconnectMono( + Mono source, + Consumer onValueExpired, + BiConsumer onValueReceived) { + this.source = source; + this.onValueExpired = onValueExpired; + this.onValueReceived = onValueReceived; + this.mainSubscriber = new ReconnectMainSubscriber<>(this); + + SUBSCRIBERS.lazySet(this, EMPTY_UNSUBSCRIBED); + } + + @Override + public Object scanUnsafe(Attr key) { + if (key == Attr.PARENT) return source; + if (key == Attr.PREFETCH) return Integer.MAX_VALUE; + + final boolean isDisposed = isDisposed(); + if (key == Attr.TERMINATED) return isDisposed; + if (key == Attr.ERROR) return t; + + return null; + } + + @Override + public void dispose() { + this.terminate(new CancellationException("ReconnectMono has already been disposed")); + } + + @Override + public boolean isDisposed() { + return this.subscribers == TERMINATED; + } + + @Override + @SuppressWarnings("uncheked") + public void subscribe(CoreSubscriber actual) { + final ReconnectInner inner = new ReconnectInner<>(actual, this); + actual.onSubscribe(inner); + + final int state = this.add(inner); + + if (state == READY_STATE) { + inner.complete(this.value); + } else if (state == TERMINATED_STATE) { + inner.onError(this.t); + } + } + + /** + * Block the calling thread indefinitely, waiting for the completion of this {@code + * ReconnectMono}. If the {@link ReconnectMono} is completed with an error a RuntimeException that + * wraps the error is thrown. + * + * @return the value of this {@code ReconnectMono} + */ + @Override + @Nullable + public T block() { + return block(null); + } + + /** + * Block the calling thread for the specified time, waiting for the completion of this {@code + * ReconnectMono}. If the {@link ReconnectMono} is completed with an error a RuntimeException that + * wraps the error is thrown. + * + * @param timeout the timeout value as a {@link Duration} + * @return the value of this {@code ReconnectMono} or {@code null} if the timeout is reached and + * the {@code ReconnectMono} has not completed + */ + @Override + @Nullable + @SuppressWarnings("uncheked") + public T block(@Nullable Duration timeout) { + try { + ReconnectInner[] subscribers = this.subscribers; + if (subscribers == READY) { + return this.value; + } + + if (subscribers == TERMINATED) { + RuntimeException re = Exceptions.propagate(this.t); + re = Exceptions.addSuppressed(re, new Exception("ReconnectMono terminated with an error")); + throw re; + } + + // connect once + if (subscribers == EMPTY_UNSUBSCRIBED + && SUBSCRIBERS.compareAndSet(this, EMPTY_UNSUBSCRIBED, EMPTY_SUBSCRIBED)) { + this.source.subscribe(this.mainSubscriber); + } + + long delay; + if (null == timeout) { + delay = 0L; + } else { + delay = System.nanoTime() + timeout.toNanos(); + } + for (; ; ) { + ReconnectInner[] inners = this.subscribers; + + if (inners == READY) { + return this.value; + } + if (inners == TERMINATED) { + RuntimeException re = Exceptions.propagate(this.t); + re = + Exceptions.addSuppressed(re, new Exception("ReconnectMono terminated with an error")); + throw re; + } + if (timeout != null && delay < System.nanoTime()) { + throw new IllegalStateException("Timeout on Mono blocking read"); + } + + Thread.sleep(1); + } + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + + throw new IllegalStateException("Thread Interruption on Mono blocking read"); + } + } + + @SuppressWarnings("unchecked") + void terminate(Throwable t) { + if (isDisposed()) { + return; + } + + // writes happens before volatile write + this.t = t; + + final ReconnectInner[] subscribers = SUBSCRIBERS.getAndSet(this, TERMINATED); + if (subscribers == TERMINATED) { + Operators.onErrorDropped(t, Context.empty()); + return; + } + + this.mainSubscriber.dispose(); + + this.doFinally(); + + for (CoreSubscriber consumer : subscribers) { + consumer.onError(t); + } + } + + void complete() { + ReconnectInner[] subscribers = this.subscribers; + if (subscribers == TERMINATED) { + return; + } + + final T value = this.value; + + for (; ; ) { + // ensures TERMINATE is going to be replaced with READY + if (SUBSCRIBERS.compareAndSet(this, subscribers, READY)) { + break; + } + + subscribers = this.subscribers; + + if (subscribers == TERMINATED) { + this.doFinally(); + return; + } + } + + this.onValueReceived.accept(value, this); + + for (ReconnectInner consumer : subscribers) { + consumer.complete(value); + } + } + + void doFinally() { + if (WIP.getAndIncrement(this) != 0) { + return; + } + + int m = 1; + T value; + + for (; ; ) { + value = this.value; + + if (value != null && isDisposed()) { + this.value = null; + this.onValueExpired.accept(value); + return; + } + + m = WIP.addAndGet(this, -m); + if (m == 0) { + return; + } + } + } + + // Check RSocket is not good + @Override + public void expire() { + if (this.subscribers == TERMINATED) { + return; + } + + final ReconnectInner[] subscribers = this.subscribers; + + if (subscribers == READY && SUBSCRIBERS.compareAndSet(this, READY, EMPTY_UNSUBSCRIBED)) { + final T value = this.value; + this.value = null; + + if (value != null) { + this.onValueExpired.accept(value); + } + } + } + + int add(ReconnectInner ps) { + for (; ; ) { + ReconnectInner[] a = this.subscribers; + + if (a == TERMINATED) { + return TERMINATED_STATE; + } + + if (a == READY) { + return READY_STATE; + } + + int n = a.length; + @SuppressWarnings("unchecked") + ReconnectInner[] b = new ReconnectInner[n + 1]; + System.arraycopy(a, 0, b, 0, n); + b[n] = ps; + + if (SUBSCRIBERS.compareAndSet(this, a, b)) { + if (a == EMPTY_UNSUBSCRIBED) { + this.source.subscribe(this.mainSubscriber); + } + return ADDED_STATE; + } + } + } + + @SuppressWarnings("unchecked") + void remove(ReconnectInner ps) { + for (; ; ) { + ReconnectInner[] a = this.subscribers; + int n = a.length; + if (n == 0) { + return; + } + + int j = -1; + for (int i = 0; i < n; i++) { + if (a[i] == ps) { + j = i; + break; + } + } + + if (j < 0) { + return; + } + + ReconnectInner[] b; + + if (n == 1) { + b = EMPTY_SUBSCRIBED; + } else { + b = new ReconnectInner[n - 1]; + System.arraycopy(a, 0, b, 0, j); + System.arraycopy(a, j + 1, b, j, n - j - 1); + } + if (SUBSCRIBERS.compareAndSet(this, a, b)) { + return; + } + } + } + + static final class ReconnectMainSubscriber implements CoreSubscriber { + + final ReconnectMono parent; + + volatile Subscription s; + + @SuppressWarnings("rawtypes") + static final AtomicReferenceFieldUpdater S = + AtomicReferenceFieldUpdater.newUpdater( + ReconnectMainSubscriber.class, Subscription.class, "s"); + + ReconnectMainSubscriber(ReconnectMono parent) { + this.parent = parent; + } + + @Override + public void onSubscribe(Subscription s) { + if (Operators.setOnce(S, this, s)) { + s.request(Long.MAX_VALUE); + } + } + + @Override + public void onComplete() { + final Subscription s = this.s; + final ReconnectMono p = this.parent; + final T value = p.value; + + if (s == Operators.cancelledSubscription() || !S.compareAndSet(this, s, null)) { + p.doFinally(); + return; + } + + if (value == null) { + p.terminate(new IllegalStateException("Unexpected Completion of the Upstream")); + } else { + p.complete(); + } + } + + @Override + public void onError(Throwable t) { + final Subscription s = this.s; + final ReconnectMono p = this.parent; + + if (s == Operators.cancelledSubscription() + || S.getAndSet(this, Operators.cancelledSubscription()) + == Operators.cancelledSubscription()) { + p.doFinally(); + Operators.onErrorDropped(t, Context.empty()); + return; + } + + // terminate upstream which means retryBackoff has exhausted + p.terminate(t); + } + + @Override + public void onNext(T value) { + if (this.s == Operators.cancelledSubscription()) { + this.parent.onValueExpired.accept(value); + return; + } + + final ReconnectMono p = this.parent; + + p.value = value; + // volatile write and check on racing + p.doFinally(); + } + + void dispose() { + Operators.terminate(S, this); + } + } + + static final class ReconnectInner extends MonoSubscriber { + final ReconnectMono parent; + + ReconnectInner(CoreSubscriber actual, ReconnectMono parent) { + super(actual); + this.parent = parent; + } + + @Override + public void cancel() { + if (!isCancelled()) { + super.cancel(); + this.parent.remove(this); + } + } + + @Override + public void onComplete() { + if (!isCancelled()) { + this.actual.onComplete(); + } + } + + @Override + public void onError(Throwable t) { + if (isCancelled()) { + Operators.onErrorDropped(t, currentContext()); + } else { + this.actual.onError(t); + } + } + + @Override + public Object scanUnsafe(Attr key) { + if (key == Attr.PARENT) return this.parent; + return super.scanUnsafe(key); + } + } +} diff --git a/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java b/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java new file mode 100644 index 000000000..5bdb3e341 --- /dev/null +++ b/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java @@ -0,0 +1,170 @@ +/* + * Copyright 2015-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.rsocket; + +import static org.junit.Assert.assertEquals; + +import io.rsocket.test.util.TestClientTransport; +import io.rsocket.transport.ClientTransport; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.util.Iterator; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import reactor.core.publisher.Mono; +import reactor.retry.Retry; +import reactor.retry.RetryContext; +import reactor.retry.RetryExhaustedException; + +public class RSocketReconnectTest { + + private Queue> retries = new ConcurrentLinkedQueue<>(); + + @Test + public void shouldBeASharedReconnectableInstanceOfRSocketMono() { + TestClientTransport[] testClientTransport = + new TestClientTransport[] {new TestClientTransport()}; + Mono rSocketMono = + RSocketFactory.connect() + .singleSubscriberRequester() + .reconnect() + .transport( + () -> { + return testClientTransport[0]; + }) + .start(); + + RSocket rSocket1 = rSocketMono.block(); + RSocket rSocket2 = rSocketMono.block(); + + Assertions.assertThat(rSocket1).isEqualTo(rSocket2); + + testClientTransport[0].testConnection().dispose(); + testClientTransport[0] = new TestClientTransport(); + + RSocket rSocket3 = rSocketMono.block(); + RSocket rSocket4 = rSocketMono.block(); + + Assertions.assertThat(rSocket3).isEqualTo(rSocket4).isNotEqualTo(rSocket2); + } + + @Test + @SuppressWarnings({"rawtype", "unchecked"}) + public void shouldBeRetrieableConnectionSharedReconnectableInstanceOfRSocketMono() { + Supplier mockTransportSupplier = Mockito.mock(Supplier.class); + Mockito.when(mockTransportSupplier.get()) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenReturn(new TestClientTransport()); + Mono rSocketMono = + RSocketFactory.connect() + .singleSubscriberRequester() + .reconnect( + Retry.any() + .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) + .retryMax(4) + .doOnRetry(onRetry())) + .transport(mockTransportSupplier) + .start(); + + RSocket rSocket1 = rSocketMono.block(); + RSocket rSocket2 = rSocketMono.block(); + + Assertions.assertThat(rSocket1).isEqualTo(rSocket2); + assertRetries( + UncheckedIOException.class, + UncheckedIOException.class, + UncheckedIOException.class, + UncheckedIOException.class); + RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); + } + + @Test + @SuppressWarnings({"rawtype", "unchecked"}) + public void shouldBeExaustedRetrieableConnectionSharedReconnectableInstanceOfRSocketMono() { + Supplier mockTransportSupplier = Mockito.mock(Supplier.class); + Mockito.when(mockTransportSupplier.get()) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenThrow(UncheckedIOException.class) + .thenReturn(new TestClientTransport()); + Mono rSocketMono = + RSocketFactory.connect() + .singleSubscriberRequester() + .reconnect( + Retry.any() + .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) + .retryMax(4) + .doOnRetry(onRetry())) + .transport(mockTransportSupplier) + .start(); + + Assertions.assertThatThrownBy(rSocketMono::block) + .isInstanceOf(RetryExhaustedException.class) + .hasCauseInstanceOf(UncheckedIOException.class); + + Assertions.assertThatThrownBy(rSocketMono::block) + .isInstanceOf(RetryExhaustedException.class) + .hasCauseInstanceOf(UncheckedIOException.class); + + assertRetries( + UncheckedIOException.class, + UncheckedIOException.class, + UncheckedIOException.class, + UncheckedIOException.class); + RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); + } + + @Test + public void shouldBeNotBeASharedReconnectableInstanceOfRSocketMono() { + + Mono rSocketMono = + RSocketFactory.connect() + .singleSubscriberRequester() + .transport(new TestClientTransport()) + .start(); + + RSocket rSocket1 = rSocketMono.block(); + RSocket rSocket2 = rSocketMono.block(); + + Assertions.assertThat(rSocket1).isNotEqualTo(rSocket2); + } + + @SafeVarargs + private final void assertRetries(Class... exceptions) { + assertEquals(exceptions.length, retries.size()); + int index = 0; + for (Iterator> it = retries.iterator(); it.hasNext(); ) { + RetryContext retryContext = it.next(); + assertEquals(index + 1, retryContext.iteration()); + assertEquals(exceptions[index], retryContext.exception().getClass()); + index++; + } + } + + Consumer> onRetry() { + return context -> retries.add(context); + } +} diff --git a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java new file mode 100644 index 000000000..805c8f0aa --- /dev/null +++ b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java @@ -0,0 +1,932 @@ +/* + * Copyright 2015-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.SocketException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Semaphore; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.mockito.Mockito; +import org.reactivestreams.Subscription; +import reactor.core.CoreSubscriber; +import reactor.core.Scannable; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; +import reactor.core.publisher.MonoProcessor; +import reactor.core.scheduler.Schedulers; +import reactor.retry.Retry; +import reactor.retry.RetryContext; +import reactor.retry.RetryExhaustedException; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; +import reactor.test.util.RaceTestUtils; +import reactor.util.function.Tuple2; +import reactor.util.function.Tuples; + +public class ReconnectMonoTests { + + private Queue> retries = new ConcurrentLinkedQueue<>(); + private Queue> received = new ConcurrentLinkedQueue<>(); + private Queue expired = new ConcurrentLinkedQueue<>(); + + @Test + public void shouldExpireValueOnRacingDisposeAndNext() { + Hooks.onErrorDropped(t -> {}); + Hooks.onNextDropped(System.out::println); + for (int i = 0; i < 100000; i++) { + final int index = i; + final CoreSubscriber[] monoSubscribers = new CoreSubscriber[1]; + Subscription mockSubscription = Mockito.mock(Subscription.class); + final Mono stringMono = + new Mono() { + @Override + public void subscribe(CoreSubscriber actual) { + actual.onSubscribe(mockSubscription); + monoSubscribers[0] = actual; + } + }; + + final ReconnectMono reconnectMono = + stringMono + .doOnDiscard(Object.class, System.out::println) + .as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + RaceTestUtils.race(() -> monoSubscribers[0].onNext("value" + index), reconnectMono::dispose); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + Mockito.verify(mockSubscription).cancel(); + + if (processor.isError()) { + Assertions.assertThat(processor.getError()) + .isInstanceOf(CancellationException.class) + .hasMessage("ReconnectMono has already been disposed"); + + Assertions.assertThat(expired).containsOnly("value" + i); + } else { + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + } + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldNotifyAllTheSubscribersUnderRacingBetweenSubscribeAndComplete() { + Hooks.onErrorDropped(t -> {}); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + final MonoProcessor racerProcessor = MonoProcessor.create(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + cold.next("value" + i); + + RaceTestUtils.race(cold::complete, () -> reconnectMono.subscribe(racerProcessor)); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + Assertions.assertThat(racerProcessor.peek()).isEqualTo("value" + i); + + Assertions.assertThat(reconnectMono.subscribers).isEqualTo(ReconnectMono.READY); + + Assertions.assertThat( + reconnectMono.add(new ReconnectMono.ReconnectInner<>(processor, reconnectMono))) + .isEqualTo(ReconnectMono.READY_STATE); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + + received.clear(); + } + } + + @Test + public void shouldEstablishValueOnceInCaseOfRacingBetweenSubscribers() { + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = TestPublisher.createCold(); + cold.next("value" + i); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = MonoProcessor.create(); + final MonoProcessor racerProcessor = MonoProcessor.create(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + Assertions.assertThat(cold.subscribeCount()).isZero(); + + RaceTestUtils.race( + () -> reconnectMono.subscribe(processor), () -> reconnectMono.subscribe(racerProcessor)); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + Assertions.assertThat(racerProcessor.isTerminated()).isTrue(); + + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + Assertions.assertThat(racerProcessor.peek()).isEqualTo("value" + i); + + Assertions.assertThat(reconnectMono.subscribers).isEqualTo(ReconnectMono.READY); + + Assertions.assertThat(cold.subscribeCount()).isOne(); + + Assertions.assertThat( + reconnectMono.add(new ReconnectMono.ReconnectInner<>(processor, reconnectMono))) + .isEqualTo(ReconnectMono.READY_STATE); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + + received.clear(); + } + } + + @Test + public void shouldEstablishValueOnceInCaseOfRacingBetweenSubscribeAndBlock() { + Duration timeout = Duration.ofMillis(100); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = TestPublisher.createCold(); + cold.next("value" + i); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = MonoProcessor.create(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + Assertions.assertThat(cold.subscribeCount()).isZero(); + + String[] values = new String[1]; + + RaceTestUtils.race( + () -> values[0] = reconnectMono.block(timeout), () -> reconnectMono.subscribe(processor)); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + Assertions.assertThat(values).containsExactly("value" + i); + + Assertions.assertThat(reconnectMono.subscribers).isEqualTo(ReconnectMono.READY); + + Assertions.assertThat(cold.subscribeCount()).isOne(); + + Assertions.assertThat( + reconnectMono.add(new ReconnectMono.ReconnectInner<>(processor, reconnectMono))) + .isEqualTo(ReconnectMono.READY_STATE); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + + received.clear(); + } + } + + @Test + public void shouldEstablishValueOnceInCaseOfRacingBetweenBlocks() { + Duration timeout = Duration.ofMillis(100); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = TestPublisher.createCold(); + cold.next("value" + i); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + Assertions.assertThat(cold.subscribeCount()).isZero(); + + String[] values1 = new String[1]; + String[] values2 = new String[1]; + + RaceTestUtils.race( + () -> values1[0] = reconnectMono.block(timeout), + () -> values2[0] = reconnectMono.block(timeout)); + + Assertions.assertThat(values2).containsExactly("value" + i); + Assertions.assertThat(values1).containsExactly("value" + i); + + Assertions.assertThat(reconnectMono.subscribers).isEqualTo(ReconnectMono.READY); + + Assertions.assertThat(cold.subscribeCount()).isOne(); + + Assertions.assertThat( + reconnectMono.add( + new ReconnectMono.ReconnectInner<>(MonoProcessor.create(), reconnectMono))) + .isEqualTo(ReconnectMono.READY_STATE); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + + received.clear(); + } + } + + @Test + public void shouldExpireValueOnRacingDisposeAndNoValueComplete() { + Hooks.onErrorDropped(t -> {}); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + RaceTestUtils.race(cold::complete, reconnectMono::dispose); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + Throwable error = processor.getError(); + + if (error instanceof CancellationException) { + Assertions.assertThat(error) + .isInstanceOf(CancellationException.class) + .hasMessage("ReconnectMono has already been disposed"); + } else { + Assertions.assertThat(error) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Unexpected Completion of the Upstream"); + } + + Assertions.assertThat(expired).isEmpty(); + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldExpireValueOnRacingDisposeAndComplete() { + Hooks.onErrorDropped(t -> {}); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + cold.next("value" + i); + + RaceTestUtils.race(cold::complete, reconnectMono::dispose); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + if (processor.isError()) { + Assertions.assertThat(processor.getError()) + .isInstanceOf(CancellationException.class) + .hasMessage("ReconnectMono has already been disposed"); + } else { + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + } + + Assertions.assertThat(expired).hasSize(1).containsOnly("value" + i); + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldExpireValueOnRacingDisposeAndError() { + Hooks.onErrorDropped(t -> {}); + RuntimeException runtimeException = new RuntimeException("test"); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + cold.next("value" + i); + + RaceTestUtils.race(() -> cold.error(runtimeException), reconnectMono::dispose); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + if (processor.isError()) { + if (processor.getError() instanceof CancellationException) { + Assertions.assertThat(processor.getError()) + .isInstanceOf(CancellationException.class) + .hasMessage("ReconnectMono has already been disposed"); + } else { + Assertions.assertThat(processor.getError()) + .isInstanceOf(RuntimeException.class) + .hasMessage("test"); + } + } else { + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + } + + Assertions.assertThat(expired).hasSize(1).containsOnly("value" + i); + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldExpireValueOnRacingDisposeAndErrorWithNoBackoff() { + Hooks.onErrorDropped(t -> {}); + RuntimeException runtimeException = new RuntimeException("test"); + for (int i = 0; i < 100000; i++) { + final TestPublisher cold = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + cold.mono() + .retryWhen( + Retry.anyOf(Exception.class) + .retryMax(1) + .withBackoffScheduler(Schedulers.immediate()) + .noBackoff()) + .as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + + cold.next("value" + i); + + RaceTestUtils.race(() -> cold.error(runtimeException), reconnectMono::dispose); + + Assertions.assertThat(processor.isTerminated()).isTrue(); + + if (processor.isError()) { + + if (processor.getError() instanceof CancellationException) { + Assertions.assertThat(processor.getError()) + .isInstanceOf(CancellationException.class) + .hasMessage("ReconnectMono has already been disposed"); + } else { + Assertions.assertThat(processor.getError()) + .isInstanceOf(RetryExhaustedException.class) + .hasCause(runtimeException); + } + + Assertions.assertThat(expired).hasSize(1).containsOnly("value" + i); + } else { + Assertions.assertThat(received) + .hasSize(1) + .containsOnly(Tuples.of("value" + i, reconnectMono)); + Assertions.assertThat(processor.peek()).isEqualTo("value" + i); + } + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldThrowOnBlocking() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + Assertions.assertThatThrownBy(() -> reconnectMono.block(Duration.ofMillis(100))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Timeout on Mono blocking read"); + } + + @Test + public void shouldThrowOnBlockingIfHasAlreadyTerminated() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + publisher.error(new RuntimeException("test")); + + Assertions.assertThatThrownBy(() -> reconnectMono.block(Duration.ofMillis(100))) + .isInstanceOf(RuntimeException.class) + .hasMessage("test") + .hasSuppressedException(new Exception("ReconnectMono terminated with an error")); + } + + @Test + public void shouldBeScannable() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final Mono parent = publisher.mono(); + final ReconnectMono reconnectMono = + parent.as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final Scannable scannableOfReconnect = Scannable.from(reconnectMono); + + Assertions.assertThat( + (List) + scannableOfReconnect.parents().map(s -> s.getClass()).collect(Collectors.toList())) + .hasSize(1) + .containsExactly(publisher.mono().getClass()); + Assertions.assertThat(scannableOfReconnect.scanUnsafe(Scannable.Attr.TERMINATED)) + .isEqualTo(false); + Assertions.assertThat(scannableOfReconnect.scanUnsafe(Scannable.Attr.ERROR)).isNull(); + + final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); + + final Scannable scannableOfMonoProcessor = Scannable.from(processor); + + Assertions.assertThat( + (List) + scannableOfMonoProcessor + .parents() + .map(s -> s.getClass()) + .collect(Collectors.toList())) + .hasSize(3) + .containsExactly( + ReconnectMono.ReconnectInner.class, ReconnectMono.class, publisher.mono().getClass()); + + reconnectMono.dispose(); + + Assertions.assertThat(scannableOfReconnect.scanUnsafe(Scannable.Attr.TERMINATED)) + .isEqualTo(true); + Assertions.assertThat(scannableOfReconnect.scanUnsafe(Scannable.Attr.ERROR)) + .isInstanceOf(CancellationException.class); + } + + @Test + public void shouldNotExpiredIfNotCompleted() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + MonoProcessor processor = MonoProcessor.create(); + + reconnectMono.subscribe(processor); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + publisher.next("test"); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + reconnectMono.expire(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + publisher.assertSubscribers(1); + Assertions.assertThat(publisher.subscribeCount()).isEqualTo(1); + + publisher.complete(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).hasSize(1); + Assertions.assertThat(processor.isTerminated()).isTrue(); + + publisher.assertSubscribers(0); + Assertions.assertThat(publisher.subscribeCount()).isEqualTo(1); + } + + @Test + public void shouldNotEmitUntilCompletion() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + MonoProcessor processor = MonoProcessor.create(); + + reconnectMono.subscribe(processor); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + publisher.next("test"); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + publisher.complete(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).hasSize(1); + Assertions.assertThat(processor.isTerminated()).isTrue(); + Assertions.assertThat(processor.peek()).isEqualTo("test"); + } + + @Test + public void shouldBePossibleToRemoveThemSelvesFromTheList_CancellationTest() { + final TestPublisher publisher = + TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW); + // given + final int minBackoff = 1; + final int maxBackoff = 5; + final int timeout = 10; + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + MonoProcessor processor = MonoProcessor.create(); + + reconnectMono.subscribe(processor); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + publisher.next("test"); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(processor.isTerminated()).isFalse(); + + processor.cancel(); + + Assertions.assertThat(reconnectMono.subscribers).isEqualTo(ReconnectMono.EMPTY_SUBSCRIBED); + + publisher.complete(); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).hasSize(1); + Assertions.assertThat(processor.isTerminated()).isFalse(); + Assertions.assertThat(processor.peek()).isNull(); + } + + @Test + public void shouldExpireValueOnDispose() { + final TestPublisher publisher = TestPublisher.create(); + // given + final int minBackoff = 1; + final int maxBackoff = 5; + final int timeout = 10; + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + StepVerifier.create(reconnectMono) + .expectSubscription() + .then(() -> publisher.next("value")) + .expectNext("value") + .expectComplete() + .verify(Duration.ofSeconds(timeout)); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).hasSize(1); + + reconnectMono.dispose(); + + Assertions.assertThat(expired).hasSize(1); + Assertions.assertThat(received).hasSize(1); + Assertions.assertThat(reconnectMono.isDisposed()).isTrue(); + + StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic())) + .expectSubscription() + .expectError(CancellationException.class) + .verify(Duration.ofSeconds(timeout)); + } + + @Test + public void shouldNotifyAllTheSubscribers() { + final TestPublisher publisher = TestPublisher.create(); + // given + final int minBackoff = 1; + final int maxBackoff = 5; + final int timeout = 10; + + final ReconnectMono reconnectMono = + publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + final MonoProcessor sub1 = MonoProcessor.create(); + final MonoProcessor sub2 = MonoProcessor.create(); + final MonoProcessor sub3 = MonoProcessor.create(); + final MonoProcessor sub4 = MonoProcessor.create(); + + reconnectMono.subscribe(sub1); + reconnectMono.subscribe(sub2); + reconnectMono.subscribe(sub3); + reconnectMono.subscribe(sub4); + + Assertions.assertThat(reconnectMono.subscribers).hasSize(4); + + final ArrayList> processors = new ArrayList<>(200); + + for (int i = 0; i < 100; i++) { + final MonoProcessor subA = MonoProcessor.create(); + final MonoProcessor subB = MonoProcessor.create(); + processors.add(subA); + processors.add(subB); + RaceTestUtils.race(() -> reconnectMono.subscribe(subA), () -> reconnectMono.subscribe(subB)); + } + + Assertions.assertThat(reconnectMono.subscribers).hasSize(204); + + sub1.dispose(); + + Assertions.assertThat(reconnectMono.subscribers).hasSize(203); + + publisher.next("value"); + + Assertions.assertThatThrownBy(sub1::peek).isInstanceOf(CancellationException.class); + Assertions.assertThat(sub2.peek()).isEqualTo("value"); + Assertions.assertThat(sub3.peek()).isEqualTo("value"); + Assertions.assertThat(sub4.peek()).isEqualTo("value"); + + for (MonoProcessor sub : processors) { + Assertions.assertThat(sub.peek()).isEqualTo("value"); + Assertions.assertThat(sub.isTerminated()).isTrue(); + } + + Assertions.assertThat(publisher.subscribeCount()).isEqualTo(1); + } + + @Test + public void shouldExpireValueExactlyOnce() { + for (int i = 0; i < 1000; i++) { + final TestPublisher cold = TestPublisher.createCold(); + cold.next("value"); + // given + final int minBackoff = 1; + final int maxBackoff = 5; + final int timeout = 10; + + final ReconnectMono reconnectMono = + cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue())); + + StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic())) + .expectSubscription() + .expectNext("value") + .expectComplete() + .verify(Duration.ofSeconds(timeout)); + + Assertions.assertThat(expired).isEmpty(); + Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono)); + RaceTestUtils.race(reconnectMono::expire, reconnectMono::expire); + + Assertions.assertThat(expired).hasSize(1).containsOnly("value"); + Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono)); + + StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic())) + .expectSubscription() + .expectNext("value") + .expectComplete() + .verify(Duration.ofSeconds(timeout)); + + Assertions.assertThat(expired).hasSize(1).containsOnly("value"); + Assertions.assertThat(received) + .hasSize(2) + .containsOnly(Tuples.of("value", reconnectMono), Tuples.of("value", reconnectMono)); + + Assertions.assertThat(cold.subscribeCount()).isEqualTo(2); + + expired.clear(); + received.clear(); + } + } + + @Test + public void shouldTimeoutRetryWithVirtualTime() { + // given + final int minBackoff = 1; + final int maxBackoff = 5; + final int timeout = 10; + + // then + StepVerifier.withVirtualTime( + () -> + Mono.error(new RuntimeException("Something went wrong")) + .retryWhen( + Retry.anyOf(Exception.class) + .exponentialBackoffWithJitter( + Duration.ofSeconds(minBackoff), Duration.ofSeconds(maxBackoff)) + .timeout(Duration.ofSeconds(timeout))) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue())) + .subscribeOn(Schedulers.elastic())) + .expectSubscription() + .thenAwait(Duration.ofSeconds(timeout)) + .expectError(RetryExhaustedException.class) + .verify(Duration.ofSeconds(timeout)); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + @Test + public void monoRetryNoBackoff() { + Mono mono = + Mono.error(new IOException()) + .retryWhen(Retry.any().noBackoff().retryMax(2).doOnRetry(onRetry())) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); + + StepVerifier.create(mono).verifyError(RetryExhaustedException.class); + assertRetries(IOException.class, IOException.class); + RetryTestUtils.assertDelays(retries, 0L, 0L); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + @Test + public void monoRetryFixedBackoff() { + Mono mono = + Mono.error(new IOException()) + .retryWhen( + Retry.any().fixedBackoff(Duration.ofMillis(500)).retryOnce().doOnRetry(onRetry())) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); + + StepVerifier.withVirtualTime(() -> mono) + .expectSubscription() + .expectNoEvent(Duration.ofMillis(300)) + .thenAwait(Duration.ofMillis(300)) + .verifyError(RetryExhaustedException.class); + + assertRetries(IOException.class); + RetryTestUtils.assertDelays(retries, 500L); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + @Test + public void monoRetryExponentialBackoff() { + Mono mono = + Mono.error(new IOException()) + .retryWhen( + Retry.any() + .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) + .retryMax(4) + .doOnRetry(onRetry())) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); + + StepVerifier.withVirtualTime(() -> mono) + .expectSubscription() + .thenAwait(Duration.ofMillis(100)) + .thenAwait(Duration.ofMillis(200)) + .thenAwait(Duration.ofMillis(400)) + .thenAwait(Duration.ofMillis(500)) + .verifyError(RetryExhaustedException.class); + + assertRetries(IOException.class, IOException.class, IOException.class, IOException.class); + RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + @Test + public void monoRetryRandomBackoff() { + Mono mono = + Mono.error(new IOException()) + .retryWhen( + Retry.any() + .randomBackoff(Duration.ofMillis(100), Duration.ofMillis(2000)) + .retryMax(4) + .doOnRetry(onRetry())) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); + + StepVerifier.withVirtualTime(() -> mono) + .expectSubscription() + .thenAwait(Duration.ofMillis(100)) + .thenAwait(Duration.ofMillis(2000)) + .thenAwait(Duration.ofMillis(2000)) + .thenAwait(Duration.ofMillis(2000)) + .verifyError(RetryExhaustedException.class); + + assertRetries(IOException.class, IOException.class, IOException.class, IOException.class); + RetryTestUtils.assertRandomDelays(retries, 100, 2000); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + @Test + public void doOnRetry() { + Semaphore semaphore = new Semaphore(0); + Retry retry = + Retry.any() + .retryOnce() + .fixedBackoff(Duration.ofMillis(500)) + .doOnRetry(context -> semaphore.release()); + + StepVerifier.withVirtualTime( + () -> + Mono.error(new SocketException()) + .retryWhen(retry) + .as(m -> new ReconnectMono<>(m, onExpire(), onValue()))) + .then(() -> semaphore.acquireUninterruptibly()) + .expectNoEvent(Duration.ofMillis(400)) + .thenAwait(Duration.ofMillis(200)) + .verifyErrorMatches(e -> isRetryExhausted(e, SocketException.class)); + + StepVerifier.withVirtualTime( + () -> Mono.error(new SocketException()).retryWhen(retry.noBackoff())) + .then(() -> semaphore.acquireUninterruptibly()) + .verifyErrorMatches(e -> isRetryExhausted(e, SocketException.class)); + + Assertions.assertThat(received).isEmpty(); + Assertions.assertThat(expired).isEmpty(); + } + + Consumer> onRetry() { + return context -> retries.add(context); + } + + BiConsumer onValue() { + return (v, __) -> received.add(Tuples.of(v, __)); + } + + Consumer onExpire() { + return (v) -> expired.add(v); + } + + @SafeVarargs + private final void assertRetries(Class... exceptions) { + assertEquals(exceptions.length, retries.size()); + int index = 0; + for (Iterator> it = retries.iterator(); it.hasNext(); ) { + RetryContext retryContext = it.next(); + assertEquals(index + 1, retryContext.iteration()); + assertEquals(exceptions[index], retryContext.exception().getClass()); + index++; + } + } + + static boolean isRetryExhausted(Throwable e, Class cause) { + return e instanceof RetryExhaustedException && cause.isInstance(e.getCause()); + } +} diff --git a/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java b/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java new file mode 100644 index 000000000..39e1618d0 --- /dev/null +++ b/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java @@ -0,0 +1,140 @@ +/* + * Copyright 2015-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Copyright (c) 2017 Pivotal Software Inc, All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Function; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; +import reactor.retry.Backoff; +import reactor.retry.BackoffDelay; +import reactor.retry.IterationContext; + +public class RetryTestUtils { + + static void assertDelays(Queue> retries, Long... delayMs) { + assertEquals(delayMs.length, retries.size()); + int index = 0; + for (Iterator> it = retries.iterator(); it.hasNext(); ) { + IterationContext repeatContext = it.next(); + assertEquals(delayMs[index].longValue(), repeatContext.backoff().toMillis()); + index++; + } + } + + static void assertRandomDelays( + Queue> retries, int firstMs, int maxMs) { + long prevMs = 0; + int randomValues = 0; + for (IterationContext context : retries) { + long backoffMs = context.backoff().toMillis(); + assertTrue("Unexpected delay " + backoffMs, backoffMs >= firstMs && backoffMs <= maxMs); + if (backoffMs != firstMs && backoffMs != prevMs) randomValues++; + prevMs = backoffMs; + } + assertTrue("Delays not random", randomValues >= 2); // Allow for at most one edge case. + } + + static void testReuseInParallel( + int threads, + int iterations, + Function, Publisher>> retryOrRepeat, + Consumer, Publisher>> testTask) + throws Exception { + int repeatCount = iterations - 1; + AtomicInteger nextBackoff = new AtomicInteger(); + // Keep track of the number of backoff invocations per instance + ConcurrentHashMap backoffCounts = new ConcurrentHashMap<>(); + // Use a countdown latch to get all instances to stop in the first backoff callback + CountDownLatch latch = new CountDownLatch(threads); + Backoff customBackoff = + new Backoff() { + @Override + public BackoffDelay apply(IterationContext context) { + Duration backoff = context.backoff(); + if (latch.getCount() > 0) { + assertNull("Wrong context, backoff must be null", backoff); + backoff = Duration.ofMillis(nextBackoff.incrementAndGet()); + backoffCounts.put(backoff.toMillis(), 1); + latch.countDown(); + try { + latch.await(10, TimeUnit.SECONDS); + } catch (Exception e) { + // ignore, errors are handled later + } + } else { + assertNotNull("Wrong context, backoff must not be null", backoff); + long index = backoff.toMillis(); + backoffCounts.put(index, backoffCounts.get(index) + 1); + } + return new BackoffDelay(backoff); + } + }; + Function, Publisher> retryFunc = retryOrRepeat.apply(customBackoff); + ExecutorService executor = Executors.newFixedThreadPool(threads); + List> futures = new ArrayList<>(); + try { + for (int i = 0; i < threads; i++) { + Runnable runnable = () -> testTask.accept(retryFunc); + futures.add(executor.submit(runnable)); + } + for (Future future : futures) future.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertEquals(0, latch.getCount()); + assertEquals(threads, backoffCounts.size()); + for (Integer count : backoffCounts.values()) { + // backoff not invoked anymore when maxIteration reached + assertEquals(repeatCount, count.intValue()); + } + } +} From 289b1e7689c8a7c2def3673b836ae662db7ba419 Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 12:12:00 +0200 Subject: [PATCH 02/10] fixes interface naming Signed-off-by: Oleh Dokuka --- .../io/rsocket/{Invalidate.java => Invalidatable.java} | 4 ++-- rsocket-core/src/main/java/io/rsocket/RSocketFactory.java | 7 ++++--- rsocket-core/src/main/java/io/rsocket/ReconnectMono.java | 8 ++++---- .../src/test/java/io/rsocket/ReconnectMonoTests.java | 8 ++++---- 4 files changed, 14 insertions(+), 13 deletions(-) rename rsocket-core/src/main/java/io/rsocket/{Invalidate.java => Invalidatable.java} (93%) diff --git a/rsocket-core/src/main/java/io/rsocket/Invalidate.java b/rsocket-core/src/main/java/io/rsocket/Invalidatable.java similarity index 93% rename from rsocket-core/src/main/java/io/rsocket/Invalidate.java rename to rsocket-core/src/main/java/io/rsocket/Invalidatable.java index ff7f74905..68ca82b22 100644 --- a/rsocket-core/src/main/java/io/rsocket/Invalidate.java +++ b/rsocket-core/src/main/java/io/rsocket/Invalidatable.java @@ -15,7 +15,7 @@ */ package io.rsocket; -interface Invalidate { +interface Invalidatable { - void expire(); + void invalidate(); } diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 8bf298fab..9c6dd6587 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -44,6 +44,7 @@ import io.rsocket.util.MultiSubscriberRSocket; import java.time.Duration; import java.util.Objects; +import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -98,6 +99,8 @@ default Start transport(ServerTransport transport) { public static class ClientRSocketFactory implements ClientTransportAcceptor { private static final String CLIENT_TAG = "client"; + private static final BiConsumer INVALIDATE_FUNCTION = + (r, i) -> r.onClose().subscribe(null, null, i::invalidate); private static final Function, ? extends Publisher> FAIL_WHEN_FACTORY = f -> f.concatMap(Mono::error); @@ -528,9 +531,7 @@ public Mono start() { source -> { if (reconnectEnabled) { return new ReconnectMono<>( - source.retryWhen(whenFactory), - Disposable::dispose, - (r, i) -> r.onClose().subscribe(null, null, i::expire)); + source.retryWhen(whenFactory), Disposable::dispose, INVALIDATE_FUNCTION); } else { return source; } diff --git a/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java index afe1dfd55..9eea9af3b 100644 --- a/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java +++ b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java @@ -33,10 +33,10 @@ import reactor.util.annotation.Nullable; import reactor.util.context.Context; -final class ReconnectMono extends Mono implements Invalidate, Disposable, Scannable { +final class ReconnectMono extends Mono implements Invalidatable, Disposable, Scannable { final Mono source; - final BiConsumer onValueReceived; + final BiConsumer onValueReceived; final Consumer onValueExpired; final ReconnectMainSubscriber mainSubscriber; @@ -75,7 +75,7 @@ final class ReconnectMono extends Mono implements Invalidate, Disposable, ReconnectMono( Mono source, Consumer onValueExpired, - BiConsumer onValueReceived) { + BiConsumer onValueReceived) { this.source = source; this.onValueExpired = onValueExpired; this.onValueReceived = onValueReceived; @@ -275,7 +275,7 @@ void doFinally() { // Check RSocket is not good @Override - public void expire() { + public void invalidate() { if (this.subscribers == TERMINATED) { return; } diff --git a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java index 805c8f0aa..57998e73e 100644 --- a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java +++ b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java @@ -53,7 +53,7 @@ public class ReconnectMonoTests { private Queue> retries = new ConcurrentLinkedQueue<>(); - private Queue> received = new ConcurrentLinkedQueue<>(); + private Queue> received = new ConcurrentLinkedQueue<>(); private Queue expired = new ConcurrentLinkedQueue<>(); @Test @@ -542,7 +542,7 @@ public void shouldNotExpiredIfNotCompleted() { Assertions.assertThat(received).isEmpty(); Assertions.assertThat(processor.isTerminated()).isFalse(); - reconnectMono.expire(); + reconnectMono.invalidate(); Assertions.assertThat(expired).isEmpty(); Assertions.assertThat(received).isEmpty(); @@ -736,7 +736,7 @@ public void shouldExpireValueExactlyOnce() { Assertions.assertThat(expired).isEmpty(); Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono)); - RaceTestUtils.race(reconnectMono::expire, reconnectMono::expire); + RaceTestUtils.race(reconnectMono::invalidate, reconnectMono::invalidate); Assertions.assertThat(expired).hasSize(1).containsOnly("value"); Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono)); @@ -906,7 +906,7 @@ Consumer> onRetry() { return context -> retries.add(context); } - BiConsumer onValue() { + BiConsumer onValue() { return (v, __) -> received.add(Tuples.of(v, __)); } From cb9e46f4946e3bab43a52caa95c91680a5b2502c Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 12:34:35 +0200 Subject: [PATCH 03/10] makes usage of retry only in case whenFactory is set up Signed-off-by: Oleh Dokuka --- rsocket-core/src/main/java/io/rsocket/RSocketFactory.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 9c6dd6587..326decc85 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -101,8 +101,6 @@ public static class ClientRSocketFactory implements ClientTransportAcceptor { private static final BiConsumer INVALIDATE_FUNCTION = (r, i) -> r.onClose().subscribe(null, null, i::invalidate); - private static final Function, ? extends Publisher> FAIL_WHEN_FACTORY = - f -> f.concatMap(Mono::error); private SocketAcceptor acceptor = (setup, sendingSocket) -> Mono.just(new AbstractRSocket() {}); @@ -135,7 +133,7 @@ public static class ClientRSocketFactory implements ClientTransportAcceptor { private boolean leaseEnabled; private Supplier> leasesSupplier = Leases::new; private boolean reconnectEnabled; - private Function, ? extends Publisher> whenFactory = FAIL_WHEN_FACTORY; + private Function, ? extends Publisher> whenFactory; private ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; @@ -531,7 +529,9 @@ public Mono start() { source -> { if (reconnectEnabled) { return new ReconnectMono<>( - source.retryWhen(whenFactory), Disposable::dispose, INVALIDATE_FUNCTION); + whenFactory == null ? source : source.retryWhen(whenFactory), + Disposable::dispose, + INVALIDATE_FUNCTION); } else { return source; } From 72ab2d7abb817941787b6caefb82a747f3515f6a Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 14:34:04 +0200 Subject: [PATCH 04/10] refactors to convenient Retry Signed-off-by: Oleh Dokuka --- .../main/java/io/rsocket/Invalidatable.java | 21 ------------------- .../main/java/io/rsocket/RSocketFactory.java | 20 +++++++++--------- .../main/java/io/rsocket/ReconnectMono.java | 5 +++++ .../java/io/rsocket/ReconnectMonoTests.java | 5 +++-- 4 files changed, 18 insertions(+), 33 deletions(-) delete mode 100644 rsocket-core/src/main/java/io/rsocket/Invalidatable.java diff --git a/rsocket-core/src/main/java/io/rsocket/Invalidatable.java b/rsocket-core/src/main/java/io/rsocket/Invalidatable.java deleted file mode 100644 index 68ca82b22..000000000 --- a/rsocket-core/src/main/java/io/rsocket/Invalidatable.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2015-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.rsocket; - -interface Invalidatable { - - void invalidate(); -} diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 326decc85..66294c7f0 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -48,10 +48,9 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -import org.reactivestreams.Publisher; import reactor.core.Disposable; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.util.retry.Retry; /** Factory for creating RSocket clients and servers. */ public class RSocketFactory { @@ -133,7 +132,7 @@ public static class ClientRSocketFactory implements ClientTransportAcceptor { private boolean leaseEnabled; private Supplier> leasesSupplier = Leases::new; private boolean reconnectEnabled; - private Function, ? extends Publisher> whenFactory; + private Retry retrySpec; private ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; @@ -355,9 +354,8 @@ public ClientRSocketFactory reconnect() { * @param whenFactory a retry factory applied for {@link Mono.retryWhen(whenFactory)} * @return a shared instance of {@code Mono}. */ - public ClientRSocketFactory reconnect( - Function, ? extends Publisher> whenFactory) { - this.whenFactory = Objects.requireNonNull(whenFactory); + public ClientRSocketFactory reconnect(Retry retrySpec) { + this.retrySpec = Objects.requireNonNull(retrySpec); this.reconnectEnabled = true; return this; } @@ -529,7 +527,7 @@ public Mono start() { source -> { if (reconnectEnabled) { return new ReconnectMono<>( - whenFactory == null ? source : source.retryWhen(whenFactory), + retrySpec == null ? source : source.retryWhen(retrySpec), Disposable::dispose, INVALIDATE_FUNCTION); } else { @@ -841,9 +839,11 @@ public Mono start() { @Override public Mono get() { - return transportServer - .get() - .start(duplexConnection -> acceptor(serverSetup, duplexConnection), mtu) + return Mono.fromSupplier(transportServer) + .flatMap( + transport -> + transport.start( + duplexConnection -> acceptor(serverSetup, duplexConnection), mtu)) .doOnNext(c -> c.onClose().doFinally(v -> serverSetup.dispose()).subscribe()); } }); diff --git a/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java index 9eea9af3b..b2c36908d 100644 --- a/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java +++ b/rsocket-core/src/main/java/io/rsocket/ReconnectMono.java @@ -470,3 +470,8 @@ public Object scanUnsafe(Attr key) { } } } + +interface Invalidatable { + + void invalidate(); +} diff --git a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java index 57998e73e..d75de1a99 100644 --- a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java +++ b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java @@ -53,7 +53,8 @@ public class ReconnectMonoTests { private Queue> retries = new ConcurrentLinkedQueue<>(); - private Queue> received = new ConcurrentLinkedQueue<>(); + private Queue> received = + new ConcurrentLinkedQueue<>(); private Queue expired = new ConcurrentLinkedQueue<>(); @Test @@ -906,7 +907,7 @@ Consumer> onRetry() { return context -> retries.add(context); } - BiConsumer onValue() { + BiConsumer onValue() { return (v, __) -> received.add(Tuples.of(v, __)); } From 6957a43451f12cb44eb067903c7699eec7a31b54 Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 14:41:40 +0200 Subject: [PATCH 05/10] removes noargs reconnect() method Signed-off-by: Oleh Dokuka --- .../main/java/io/rsocket/RSocketFactory.java | 74 ++----------------- 1 file changed, 6 insertions(+), 68 deletions(-) diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 66294c7f0..0ee5d6c53 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -248,7 +248,7 @@ public ClientRSocketFactory singleSubscriberRequester() { * RSocketFactory * .connect() * .singleSubscriberRequester() - * .reconnect() + * .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1))) * .transport(transport) * .start(); * @@ -260,8 +260,8 @@ public ClientRSocketFactory singleSubscriberRequester() { * } * * Apart of the shared behavior, once the previous connection has been expired (e.g. connection - * has been disposed), the same instance of {@code Mono} reestablish connection without - * any extra effort.
+ * has been disposed), the same instance of {@code Mono} reestablishes connection + * without any extra effort.
* For example: * *
{@code
@@ -269,7 +269,7 @@ public ClientRSocketFactory singleSubscriberRequester() {
      *   RSocketFactory
      *                .connect()
      *                .singleSubscriberRequester()
-     *                .reconnect()
+     *                .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1)))
      *                .transport(transport)
      *                .start();
      *
@@ -291,67 +291,7 @@ public ClientRSocketFactory singleSubscriberRequester() {
      *
      * }
* - * @return a shared instance of {@code Mono}. - */ - public ClientRSocketFactory reconnect() { - this.reconnectEnabled = true; - return this; - } - - /** - * Enables a reconnectable, shared instance of {@code Mono} so every subscriber will - * observe the same RSocket instance up on connection establishment.
- * For example: - * - *
{@code
-     * Mono sharedRSocketMono =
-     *   RSocketFactory
-     *                .connect()
-     *                .singleSubscriberRequester()
-     *                .reconnect(fluxOfThrowables -> flux.concatMap(t -> Mono.delay(Duration.ofSeconds(1)).take(5))
-     *                .transport(transport)
-     *                .start();
-     *
-     *  RSocket r1 = sharedRSocketMono.block();
-     *  RSocket r2 = sharedRSocketMono.block();
-     *
-     *  assert r1 == r2;
-     *
-     * }
- * - * Apart of the shared behavior, once the previous connection has been expired (e.g. connection - * has been disposed), the same instance of {@code Mono} reestablish connection without - * any extra effort.
- * For example: - * - *
{@code
-     * Mono sharedRSocketMono =
-     *   RSocketFactory
-     *                .connect()
-     *                .singleSubscriberRequester()
-     *                .reconnect(fluxOfThrowables -> flux.concatMap(t -> Mono.delay(Duration.ofSeconds(1)).take(5))
-     *                .transport(transport)
-     *                .start();
-     *
-     *  RSocket r1 = sharedRSocketMono.block();
-     *  RSocket r2 = sharedRSocketMono.block();
-     *
-     *  assert r1 == r2;
-     *
-     *  r1.dispose()
-     *
-     *  assert r2.isDisposed()
-     *
-     *  RSocket r3 = sharedRSocketMono.block();
-     *  RSocket r4 = sharedRSocketMono.block();
-     *
-     *
-     *  assert r1 != r3;
-     *  assert r4 == r3;
-     *
-     * }
- * - * @param whenFactory a retry factory applied for {@link Mono.retryWhen(whenFactory)} + * @param retrySpec a retry factory applied for {@link Mono#retryWhen(Retry)} * @return a shared instance of {@code Mono}. */ public ClientRSocketFactory reconnect(Retry retrySpec) { @@ -527,9 +467,7 @@ public Mono start() { source -> { if (reconnectEnabled) { return new ReconnectMono<>( - retrySpec == null ? source : source.retryWhen(retrySpec), - Disposable::dispose, - INVALIDATE_FUNCTION); + source.retryWhen(retrySpec), Disposable::dispose, INVALIDATE_FUNCTION); } else { return source; } From 26a35485bf31a5abd1cd0cc15c5033aff5576322 Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 15:16:34 +0200 Subject: [PATCH 06/10] fixes tests Signed-off-by: Oleh Dokuka --- rsocket-core/build.gradle | 1 - .../java/io/rsocket/RSocketReconnectTest.java | 39 +++-- .../java/io/rsocket/ReconnectMonoTests.java | 120 ++++----------- .../test/java/io/rsocket/RetryTestUtils.java | 140 ------------------ 4 files changed, 44 insertions(+), 256 deletions(-) delete mode 100644 rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java diff --git a/rsocket-core/build.gradle b/rsocket-core/build.gradle index 899fa31a5..ca2ae0e65 100644 --- a/rsocket-core/build.gradle +++ b/rsocket-core/build.gradle @@ -43,7 +43,6 @@ dependencies { // TODO: Remove after JUnit5 migration testCompileOnly 'junit:junit' testImplementation 'org.hamcrest:hamcrest-library' - testImplementation 'io.projectreactor.addons:reactor-extra' testRuntimeOnly 'org.junit.vintage:junit-vintage-engine' } diff --git a/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java b/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java index 5bdb3e341..b5ca4858e 100644 --- a/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java +++ b/rsocket-core/src/test/java/io/rsocket/RSocketReconnectTest.java @@ -29,14 +29,13 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import reactor.core.Exceptions; import reactor.core.publisher.Mono; -import reactor.retry.Retry; -import reactor.retry.RetryContext; -import reactor.retry.RetryExhaustedException; +import reactor.util.retry.Retry; public class RSocketReconnectTest { - private Queue> retries = new ConcurrentLinkedQueue<>(); + private Queue retries = new ConcurrentLinkedQueue<>(); @Test public void shouldBeASharedReconnectableInstanceOfRSocketMono() { @@ -45,7 +44,7 @@ public void shouldBeASharedReconnectableInstanceOfRSocketMono() { Mono rSocketMono = RSocketFactory.connect() .singleSubscriberRequester() - .reconnect() + .reconnect(Retry.indefinitely()) .transport( () -> { return testClientTransport[0]; @@ -80,10 +79,9 @@ public void shouldBeRetrieableConnectionSharedReconnectableInstanceOfRSocketMono RSocketFactory.connect() .singleSubscriberRequester() .reconnect( - Retry.any() - .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) - .retryMax(4) - .doOnRetry(onRetry())) + Retry.backoff(4, Duration.ofMillis(100)) + .maxBackoff(Duration.ofMillis(500)) + .doAfterRetry(onRetry())) .transport(mockTransportSupplier) .start(); @@ -96,7 +94,6 @@ public void shouldBeRetrieableConnectionSharedReconnectableInstanceOfRSocketMono UncheckedIOException.class, UncheckedIOException.class, UncheckedIOException.class); - RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); } @Test @@ -114,19 +111,18 @@ public void shouldBeExaustedRetrieableConnectionSharedReconnectableInstanceOfRSo RSocketFactory.connect() .singleSubscriberRequester() .reconnect( - Retry.any() - .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) - .retryMax(4) - .doOnRetry(onRetry())) + Retry.backoff(4, Duration.ofMillis(100)) + .maxBackoff(Duration.ofMillis(500)) + .doAfterRetry(onRetry())) .transport(mockTransportSupplier) .start(); Assertions.assertThatThrownBy(rSocketMono::block) - .isInstanceOf(RetryExhaustedException.class) + .matches(Exceptions::isRetryExhausted) .hasCauseInstanceOf(UncheckedIOException.class); Assertions.assertThatThrownBy(rSocketMono::block) - .isInstanceOf(RetryExhaustedException.class) + .matches(Exceptions::isRetryExhausted) .hasCauseInstanceOf(UncheckedIOException.class); assertRetries( @@ -134,7 +130,6 @@ public void shouldBeExaustedRetrieableConnectionSharedReconnectableInstanceOfRSo UncheckedIOException.class, UncheckedIOException.class, UncheckedIOException.class); - RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); } @Test @@ -156,15 +151,15 @@ public void shouldBeNotBeASharedReconnectableInstanceOfRSocketMono() { private final void assertRetries(Class... exceptions) { assertEquals(exceptions.length, retries.size()); int index = 0; - for (Iterator> it = retries.iterator(); it.hasNext(); ) { - RetryContext retryContext = it.next(); - assertEquals(index + 1, retryContext.iteration()); - assertEquals(exceptions[index], retryContext.exception().getClass()); + for (Iterator it = retries.iterator(); it.hasNext(); ) { + Retry.RetrySignal retryContext = it.next(); + assertEquals(index, retryContext.totalRetries()); + assertEquals(exceptions[index], retryContext.failure().getClass()); index++; } } - Consumer> onRetry() { + Consumer onRetry() { return context -> retries.add(context); } } diff --git a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java index d75de1a99..130cd4cc0 100644 --- a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java +++ b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java @@ -19,7 +19,6 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; -import java.net.SocketException; import java.time.Duration; import java.util.ArrayList; import java.util.Iterator; @@ -27,7 +26,7 @@ import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -36,25 +35,23 @@ import org.mockito.Mockito; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; +import reactor.core.Exceptions; import reactor.core.Scannable; import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.scheduler.Schedulers; -import reactor.retry.Retry; -import reactor.retry.RetryContext; -import reactor.retry.RetryExhaustedException; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import reactor.test.util.RaceTestUtils; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; +import reactor.util.retry.Retry; public class ReconnectMonoTests { - private Queue> retries = new ConcurrentLinkedQueue<>(); - private Queue> received = - new ConcurrentLinkedQueue<>(); + private Queue retries = new ConcurrentLinkedQueue<>(); + private Queue> received = new ConcurrentLinkedQueue<>(); private Queue expired = new ConcurrentLinkedQueue<>(); @Test @@ -407,11 +404,7 @@ public void shouldExpireValueOnRacingDisposeAndErrorWithNoBackoff() { final ReconnectMono reconnectMono = cold.mono() - .retryWhen( - Retry.anyOf(Exception.class) - .retryMax(1) - .withBackoffScheduler(Schedulers.immediate()) - .noBackoff()) + .retryWhen(Retry.max(1).filter(t -> t instanceof Exception)) .as(source -> new ReconnectMono<>(source, onExpire(), onValue())); final MonoProcessor processor = reconnectMono.subscribeWith(MonoProcessor.create()); @@ -433,7 +426,7 @@ public void shouldExpireValueOnRacingDisposeAndErrorWithNoBackoff() { .hasMessage("ReconnectMono has already been disposed"); } else { Assertions.assertThat(processor.getError()) - .isInstanceOf(RetryExhaustedException.class) + .matches(t -> Exceptions.isRetryExhausted(t)) .hasCause(runtimeException); } @@ -772,15 +765,15 @@ public void shouldTimeoutRetryWithVirtualTime() { () -> Mono.error(new RuntimeException("Something went wrong")) .retryWhen( - Retry.anyOf(Exception.class) - .exponentialBackoffWithJitter( - Duration.ofSeconds(minBackoff), Duration.ofSeconds(maxBackoff)) - .timeout(Duration.ofSeconds(timeout))) + Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(minBackoff)) + .doAfterRetry(onRetry()) + .maxBackoff(Duration.ofSeconds(maxBackoff))) + .timeout(Duration.ofSeconds(timeout)) .as(m -> new ReconnectMono<>(m, onExpire(), onValue())) .subscribeOn(Schedulers.elastic())) .expectSubscription() .thenAwait(Duration.ofSeconds(timeout)) - .expectError(RetryExhaustedException.class) + .expectError(TimeoutException.class) .verify(Duration.ofSeconds(timeout)); Assertions.assertThat(received).isEmpty(); @@ -791,12 +784,11 @@ public void shouldTimeoutRetryWithVirtualTime() { public void monoRetryNoBackoff() { Mono mono = Mono.error(new IOException()) - .retryWhen(Retry.any().noBackoff().retryMax(2).doOnRetry(onRetry())) + .retryWhen(Retry.max(2).doAfterRetry(onRetry())) .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); - StepVerifier.create(mono).verifyError(RetryExhaustedException.class); + StepVerifier.create(mono).verifyErrorMatches(Exceptions::isRetryExhausted); assertRetries(IOException.class, IOException.class); - RetryTestUtils.assertDelays(retries, 0L, 0L); Assertions.assertThat(received).isEmpty(); Assertions.assertThat(expired).isEmpty(); @@ -806,18 +798,16 @@ public void monoRetryNoBackoff() { public void monoRetryFixedBackoff() { Mono mono = Mono.error(new IOException()) - .retryWhen( - Retry.any().fixedBackoff(Duration.ofMillis(500)).retryOnce().doOnRetry(onRetry())) + .retryWhen(Retry.fixedDelay(1, Duration.ofMillis(500)).doAfterRetry(onRetry())) .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); StepVerifier.withVirtualTime(() -> mono) .expectSubscription() .expectNoEvent(Duration.ofMillis(300)) .thenAwait(Duration.ofMillis(300)) - .verifyError(RetryExhaustedException.class); + .verifyErrorMatches(Exceptions::isRetryExhausted); assertRetries(IOException.class); - RetryTestUtils.assertDelays(retries, 500L); Assertions.assertThat(received).isEmpty(); Assertions.assertThat(expired).isEmpty(); @@ -828,10 +818,9 @@ public void monoRetryExponentialBackoff() { Mono mono = Mono.error(new IOException()) .retryWhen( - Retry.any() - .exponentialBackoff(Duration.ofMillis(100), Duration.ofMillis(500)) - .retryMax(4) - .doOnRetry(onRetry())) + Retry.backoff(4, Duration.ofMillis(100)) + .maxBackoff(Duration.ofMillis(500)) + .doAfterRetry(onRetry())) .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); StepVerifier.withVirtualTime(() -> mono) @@ -840,74 +829,19 @@ public void monoRetryExponentialBackoff() { .thenAwait(Duration.ofMillis(200)) .thenAwait(Duration.ofMillis(400)) .thenAwait(Duration.ofMillis(500)) - .verifyError(RetryExhaustedException.class); + .verifyErrorMatches(Exceptions::isRetryExhausted); assertRetries(IOException.class, IOException.class, IOException.class, IOException.class); - RetryTestUtils.assertDelays(retries, 100L, 200L, 400L, 500L); - - Assertions.assertThat(received).isEmpty(); - Assertions.assertThat(expired).isEmpty(); - } - - @Test - public void monoRetryRandomBackoff() { - Mono mono = - Mono.error(new IOException()) - .retryWhen( - Retry.any() - .randomBackoff(Duration.ofMillis(100), Duration.ofMillis(2000)) - .retryMax(4) - .doOnRetry(onRetry())) - .as(m -> new ReconnectMono<>(m, onExpire(), onValue())); - - StepVerifier.withVirtualTime(() -> mono) - .expectSubscription() - .thenAwait(Duration.ofMillis(100)) - .thenAwait(Duration.ofMillis(2000)) - .thenAwait(Duration.ofMillis(2000)) - .thenAwait(Duration.ofMillis(2000)) - .verifyError(RetryExhaustedException.class); - - assertRetries(IOException.class, IOException.class, IOException.class, IOException.class); - RetryTestUtils.assertRandomDelays(retries, 100, 2000); - - Assertions.assertThat(received).isEmpty(); - Assertions.assertThat(expired).isEmpty(); - } - - @Test - public void doOnRetry() { - Semaphore semaphore = new Semaphore(0); - Retry retry = - Retry.any() - .retryOnce() - .fixedBackoff(Duration.ofMillis(500)) - .doOnRetry(context -> semaphore.release()); - - StepVerifier.withVirtualTime( - () -> - Mono.error(new SocketException()) - .retryWhen(retry) - .as(m -> new ReconnectMono<>(m, onExpire(), onValue()))) - .then(() -> semaphore.acquireUninterruptibly()) - .expectNoEvent(Duration.ofMillis(400)) - .thenAwait(Duration.ofMillis(200)) - .verifyErrorMatches(e -> isRetryExhausted(e, SocketException.class)); - - StepVerifier.withVirtualTime( - () -> Mono.error(new SocketException()).retryWhen(retry.noBackoff())) - .then(() -> semaphore.acquireUninterruptibly()) - .verifyErrorMatches(e -> isRetryExhausted(e, SocketException.class)); Assertions.assertThat(received).isEmpty(); Assertions.assertThat(expired).isEmpty(); } - Consumer> onRetry() { + Consumer onRetry() { return context -> retries.add(context); } - BiConsumer onValue() { + BiConsumer onValue() { return (v, __) -> received.add(Tuples.of(v, __)); } @@ -919,15 +853,15 @@ Consumer onExpire() { private final void assertRetries(Class... exceptions) { assertEquals(exceptions.length, retries.size()); int index = 0; - for (Iterator> it = retries.iterator(); it.hasNext(); ) { - RetryContext retryContext = it.next(); - assertEquals(index + 1, retryContext.iteration()); - assertEquals(exceptions[index], retryContext.exception().getClass()); + for (Iterator it = retries.iterator(); it.hasNext(); ) { + Retry.RetrySignal retryContext = it.next(); + assertEquals(index, retryContext.totalRetries()); + assertEquals(exceptions[index], retryContext.failure().getClass()); index++; } } static boolean isRetryExhausted(Throwable e, Class cause) { - return e instanceof RetryExhaustedException && cause.isInstance(e.getCause()); + return Exceptions.isRetryExhausted(e) && cause.isInstance(e.getCause()); } } diff --git a/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java b/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java deleted file mode 100644 index 39e1618d0..000000000 --- a/rsocket-core/src/test/java/io/rsocket/RetryTestUtils.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2015-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Copyright (c) 2017 Pivotal Software Inc, All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.rsocket; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.function.Function; -import org.reactivestreams.Publisher; -import reactor.core.publisher.Flux; -import reactor.retry.Backoff; -import reactor.retry.BackoffDelay; -import reactor.retry.IterationContext; - -public class RetryTestUtils { - - static void assertDelays(Queue> retries, Long... delayMs) { - assertEquals(delayMs.length, retries.size()); - int index = 0; - for (Iterator> it = retries.iterator(); it.hasNext(); ) { - IterationContext repeatContext = it.next(); - assertEquals(delayMs[index].longValue(), repeatContext.backoff().toMillis()); - index++; - } - } - - static void assertRandomDelays( - Queue> retries, int firstMs, int maxMs) { - long prevMs = 0; - int randomValues = 0; - for (IterationContext context : retries) { - long backoffMs = context.backoff().toMillis(); - assertTrue("Unexpected delay " + backoffMs, backoffMs >= firstMs && backoffMs <= maxMs); - if (backoffMs != firstMs && backoffMs != prevMs) randomValues++; - prevMs = backoffMs; - } - assertTrue("Delays not random", randomValues >= 2); // Allow for at most one edge case. - } - - static void testReuseInParallel( - int threads, - int iterations, - Function, Publisher>> retryOrRepeat, - Consumer, Publisher>> testTask) - throws Exception { - int repeatCount = iterations - 1; - AtomicInteger nextBackoff = new AtomicInteger(); - // Keep track of the number of backoff invocations per instance - ConcurrentHashMap backoffCounts = new ConcurrentHashMap<>(); - // Use a countdown latch to get all instances to stop in the first backoff callback - CountDownLatch latch = new CountDownLatch(threads); - Backoff customBackoff = - new Backoff() { - @Override - public BackoffDelay apply(IterationContext context) { - Duration backoff = context.backoff(); - if (latch.getCount() > 0) { - assertNull("Wrong context, backoff must be null", backoff); - backoff = Duration.ofMillis(nextBackoff.incrementAndGet()); - backoffCounts.put(backoff.toMillis(), 1); - latch.countDown(); - try { - latch.await(10, TimeUnit.SECONDS); - } catch (Exception e) { - // ignore, errors are handled later - } - } else { - assertNotNull("Wrong context, backoff must not be null", backoff); - long index = backoff.toMillis(); - backoffCounts.put(index, backoffCounts.get(index) + 1); - } - return new BackoffDelay(backoff); - } - }; - Function, Publisher> retryFunc = retryOrRepeat.apply(customBackoff); - ExecutorService executor = Executors.newFixedThreadPool(threads); - List> futures = new ArrayList<>(); - try { - for (int i = 0; i < threads; i++) { - Runnable runnable = () -> testTask.accept(retryFunc); - futures.add(executor.submit(runnable)); - } - for (Future future : futures) future.get(5, TimeUnit.SECONDS); - } finally { - executor.shutdownNow(); - } - - assertEquals(0, latch.getCount()); - assertEquals(threads, backoffCounts.size()); - for (Integer count : backoffCounts.values()) { - // backoff not invoked anymore when maxIteration reached - assertEquals(repeatCount, count.intValue()); - } - } -} From 27f24c3052a991583f7141c845576a564eb1933b Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Tue, 24 Mar 2020 18:27:24 +0200 Subject: [PATCH 07/10] Update rsocket-core/src/main/java/io/rsocket/RSocketFactory.java Co-Authored-By: Rossen Stoyanchev --- rsocket-core/src/main/java/io/rsocket/RSocketFactory.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java index 0ee5d6c53..8d620720e 100644 --- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java +++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java @@ -259,9 +259,8 @@ public ClientRSocketFactory singleSubscriberRequester() { * * } * - * Apart of the shared behavior, once the previous connection has been expired (e.g. connection - * has been disposed), the same instance of {@code Mono} reestablishes connection - * without any extra effort.
+ * Apart of the shared behavior, if the connection is lost, the same {@code Mono} instance + * will transparently re-establish the connection for subsequent subscribers.
* For example: * *
{@code

From 8523b1e6d3f99190277d10c6a5527d36fa9086f3 Mon Sep 17 00:00:00 2001
From: Oleh Dokuka 
Date: Tue, 24 Mar 2020 18:46:38 +0200
Subject: [PATCH 08/10] fixes docs

Signed-off-by: Oleh Dokuka 
---
 .../main/java/io/rsocket/RSocketFactory.java  | 23 +++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)

diff --git a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java
index 8d620720e..6570ed7a3 100644
--- a/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java
+++ b/rsocket-core/src/main/java/io/rsocket/RSocketFactory.java
@@ -259,8 +259,8 @@ public ClientRSocketFactory singleSubscriberRequester() {
      *
      * }
* - * Apart of the shared behavior, if the connection is lost, the same {@code Mono} instance - * will transparently re-establish the connection for subsequent subscribers.
+ * Apart of the shared behavior, if the connection is lost, the same {@code Mono} + * instance will transparently re-establish the connection for subsequent subscribers.
* For example: * *
{@code
@@ -290,6 +290,25 @@ public ClientRSocketFactory singleSubscriberRequester() {
      *
      * }
* + * Note, having reconnect() enabled does not eliminate the need to accompany each + * individual request with the corresponding retry logic.
+ * For example: + * + *
{@code
+     * Mono sharedRSocketMono =
+     *   RSocketFactory
+     *                .connect()
+     *                .singleSubscriberRequester()
+     *                .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1)))
+     *                .transport(transport)
+     *                .start();
+     *
+     *  sharedRSocket.flatMap(rSocket -> rSocket.requestResponse(...))
+     *               .retryWhen(ownRetry)
+     *               .subscribe()
+     *
+     * }
+ * * @param retrySpec a retry factory applied for {@link Mono#retryWhen(Retry)} * @return a shared instance of {@code Mono}. */ From 6ff032d71fddb77e1e3d76389b59ca9b4bfd581f Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Wed, 25 Mar 2020 10:13:39 +0200 Subject: [PATCH 09/10] provide test events logging Signed-off-by: Oleh Dokuka --- build.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index 262015af6..7e5eb9823 100644 --- a/build.gradle +++ b/build.gradle @@ -119,6 +119,10 @@ subprojects { test { useJUnitPlatform() + testLogging { + events "started", "passed", "skipped", "failed" + } + systemProperty "io.netty.leakDetection.level", "ADVANCED" } From 8c11169053a80f321811dea79af1faa3a26956c1 Mon Sep 17 00:00:00 2001 From: Oleh Dokuka Date: Wed, 25 Mar 2020 10:56:17 +0200 Subject: [PATCH 10/10] fixes test Signed-off-by: Oleh Dokuka --- rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java | 1 + 1 file changed, 1 insertion(+) diff --git a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java index 130cd4cc0..fb7707509 100644 --- a/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java +++ b/rsocket-core/src/test/java/io/rsocket/ReconnectMonoTests.java @@ -820,6 +820,7 @@ public void monoRetryExponentialBackoff() { .retryWhen( Retry.backoff(4, Duration.ofMillis(100)) .maxBackoff(Duration.ofMillis(500)) + .jitter(0.0d) .doAfterRetry(onRetry())) .as(m -> new ReconnectMono<>(m, onExpire(), onValue()));