Search in sources :

Example 1 with Multi

use of io.smallrye.mutiny.Multi in project smallrye-mutiny by smallrye.

the class ExponentialBackoff method randomExponentialBackoffFunctionExpireAt.

/**
 * Computes a method that would delay <em>ticks</em> using an exponential backoff.
 * Will keep retrying until an expiration time.
 * The last attempt will start before the expiration time.
 *
 * @param expireAt absolute time in millis that specifies when to give up.
 * @param firstBackoff the delay of the first backoff
 * @param maxBackoff the max backoff
 * @param jitterFactor the jitter factor in [0, 1]
 * @param executor the executor used for the delay
 * @return the function
 */
public static Function<Multi<Throwable>, Publisher<Long>> randomExponentialBackoffFunctionExpireAt(long expireAt, Duration firstBackoff, Duration maxBackoff, double jitterFactor, ScheduledExecutorService executor) {
    validate(firstBackoff, maxBackoff, jitterFactor, executor);
    AtomicInteger index = new AtomicInteger();
    return t -> t.onItem().transformToUni(failure -> {
        int iteration = index.incrementAndGet();
        Duration delay = getNextDelay(firstBackoff, maxBackoff, jitterFactor, iteration);
        long checkTime = System.currentTimeMillis() + delay.toMillis();
        if (checkTime > expireAt) {
            return Uni.createFrom().failure(new IllegalStateException("Retries exhausted : " + iteration + " attempts against " + checkTime + "/" + expireAt + " expiration", failure));
        }
        return Uni.createFrom().item((long) iteration).onItem().delayIt().onExecutor(executor).by(delay);
    }).concatenate();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Publisher(org.reactivestreams.Publisher) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Function(java.util.function.Function) Multi(io.smallrye.mutiny.Multi) Uni(io.smallrye.mutiny.Uni) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration)

Example 2 with Multi

use of io.smallrye.mutiny.Multi in project smallrye-mutiny by smallrye.

the class MultiReplayTest method raceBetweenPushAndCancel.

@Test
void raceBetweenPushAndCancel() throws InterruptedException, TimeoutException {
    ExecutorService pool = Executors.newCachedThreadPool();
    try {
        final int N = 32;
        CountDownLatch startLatch = new CountDownLatch(N);
        CountDownLatch endLatch = new CountDownLatch(N);
        Multi<Long> upstream = Multi.createFrom().<Long>emitter(emitter -> {
            try {
                startLatch.await();
            } catch (InterruptedException e) {
                emitter.fail(e);
            }
            long i = 0;
            while (endLatch.getCount() != 0) {
                emitter.emit(i++);
            }
            emitter.complete();
        }).runSubscriptionOn(pool);
        Multi<Long> replay = Multi.createBy().replaying().ofMulti(upstream).runSubscriptionOn(pool);
        CopyOnWriteArrayList<List<Long>> items = new CopyOnWriteArrayList<>();
        for (int i = 0; i < N; i++) {
            AssertSubscriber<Long> sub = replay.subscribe().withSubscriber(AssertSubscriber.create());
            pool.submit(() -> {
                startLatch.countDown();
                randomSleep();
                sub.request(Long.MAX_VALUE);
                randomSleep();
                sub.cancel();
                items.add(sub.getItems());
                endLatch.countDown();
            });
        }
        if (!endLatch.await(10, TimeUnit.SECONDS)) {
            throw new TimeoutException("The test did not finish within 10 seconds");
        }
        assertThat(items).hasSize(N);
        items.forEach(list -> {
            if (list.isEmpty()) {
                // Might happen due to subscriber timing
                return;
            }
            assertThat(list).isNotEmpty();
            AtomicLong prev = new AtomicLong(list.get(0));
            list.stream().skip(1).forEach(n -> {
                assertThat(n).isEqualTo(prev.get() + 1);
                prev.set(n);
            });
        });
    } finally {
        pool.shutdownNow();
    }
}
Also used : AssertSubscriber(io.smallrye.mutiny.helpers.test.AssertSubscriber) Awaitility.await(org.awaitility.Awaitility.await) Arrays(java.util.Arrays) java.util.concurrent(java.util.concurrent) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) Random(java.util.Random) Context(io.smallrye.mutiny.Context) Multi(io.smallrye.mutiny.Multi) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Subscription(org.reactivestreams.Subscription) MultiSubscriber(io.smallrye.mutiny.subscription.MultiSubscriber) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 3 with Multi

use of io.smallrye.mutiny.Multi in project smallrye-mutiny by smallrye.

the class MultiFromResourceFromUniTest method testThatStreamSupplierEmittingAFailureCallsOnFailure.

@Test
public void testThatStreamSupplierEmittingAFailureCallsOnFailure() {
    FakeTransactionalResource resource = new FakeTransactionalResource();
    Multi<String> multi = Multi.createFrom().<FakeTransactionalResource, String>resource(() -> resource, r -> Multi.createFrom().failure(new IOException("boom"))).withFinalizer(FakeTransactionalResource::commit, FakeTransactionalResource::rollback, FakeTransactionalResource::cancel);
    multi.subscribe().withSubscriber(AssertSubscriber.create(20)).assertFailedWith(IOException.class, "boom");
    assertThat(resource.subscribed).isFalse();
    assertThat(resource.onCompleteSubscribed).isFalse();
    assertThat(resource.onCancelSubscribed).isFalse();
    assertThat(resource.onFailureSubscribed).isTrue();
    assertThat(resource.failure.get()).isInstanceOf(IOException.class);
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) AssertSubscriber(io.smallrye.mutiny.helpers.test.AssertSubscriber) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BiFunction(java.util.function.BiFunction) Publisher(org.reactivestreams.Publisher) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UniOnCancellationSpy(io.smallrye.mutiny.helpers.spies.UniOnCancellationSpy) IOException(java.io.IOException) ResourceLock(org.junit.jupiter.api.parallel.ResourceLock) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) InfrastructureResource(junit5.support.InfrastructureResource) Multi(io.smallrye.mutiny.Multi) ArrayList(java.util.ArrayList) Uni(io.smallrye.mutiny.Uni) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) CompositeException(io.smallrye.mutiny.CompositeException) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Spy(io.smallrye.mutiny.helpers.spies.Spy) ResourceAccessMode(org.junit.jupiter.api.parallel.ResourceAccessMode) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 4 with Multi

use of io.smallrye.mutiny.Multi in project smallrye-mutiny by smallrye.

the class MultiCacheTest method testCachingWithFailure.

@Test
public void testCachingWithFailure() {
    AtomicInteger count = new AtomicInteger();
    Multi<Integer> multi = Multi.createFrom().<Integer>emitter(emitter -> emitter.emit(count.incrementAndGet()).emit(count.incrementAndGet()).fail(new IOException("boom-" + count.incrementAndGet()))).cache();
    multi.subscribe().withSubscriber(AssertSubscriber.create(2)).assertItems(1, 2).assertFailedWith(IOException.class, "boom-3");
    multi.subscribe().withSubscriber(AssertSubscriber.create(Long.MAX_VALUE)).assertItems(1, 2).assertFailedWith(IOException.class, "boom-3");
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.jupiter.api.Test) AssertSubscriber(io.smallrye.mutiny.helpers.test.AssertSubscriber) MultiEmitter(io.smallrye.mutiny.subscription.MultiEmitter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IOException(java.io.IOException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Multi(io.smallrye.mutiny.Multi) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 5 with Multi

use of io.smallrye.mutiny.Multi in project smallrye-mutiny by smallrye.

the class MultiConvertFromTest method testCreatingFromAMaybeNeverEmitting.

@Test
public void testCreatingFromAMaybeNeverEmitting() {
    AtomicBoolean cancelled = new AtomicBoolean();
    Multi<Integer> multi = Multi.createFrom().converter(MultiRx3Converters.fromMaybe(), Maybe.<Integer>never().doOnDispose(() -> cancelled.set(true)));
    assertThat(multi).isNotNull();
    multi.subscribe().with(i -> {
    }).cancel();
    assertThat(cancelled).isTrue();
}
Also used : Test(org.junit.jupiter.api.Test) AssertSubscriber(io.smallrye.mutiny.helpers.test.AssertSubscriber) Maybe(io.reactivex.rxjava3.core.Maybe) Single(io.reactivex.rxjava3.core.Single) Flowable(io.reactivex.rxjava3.core.Flowable) Observable(io.reactivex.rxjava3.core.Observable) MultiRx3Converters(io.smallrye.mutiny.converters.multi.MultiRx3Converters) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) Completable(io.reactivex.rxjava3.core.Completable) Multi(io.smallrye.mutiny.Multi) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.jupiter.api.Test)

Aggregations

Multi (io.smallrye.mutiny.Multi)57 Test (org.junit.jupiter.api.Test)43 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)42 AssertSubscriber (io.smallrye.mutiny.helpers.test.AssertSubscriber)41 Uni (io.smallrye.mutiny.Uni)38 List (java.util.List)34 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)34 IOException (java.io.IOException)33 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)31 Function (java.util.function.Function)29 Duration (java.time.Duration)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)27 AtomicReference (java.util.concurrent.atomic.AtomicReference)25 Consumer (java.util.function.Consumer)25 InfrastructureResource (junit5.support.InfrastructureResource)22 ResourceAccessMode (org.junit.jupiter.api.parallel.ResourceAccessMode)22 ResourceLock (org.junit.jupiter.api.parallel.ResourceLock)22 Supplier (java.util.function.Supplier)20 CompositeException (io.smallrye.mutiny.CompositeException)19 ArrayList (java.util.ArrayList)18