Search in sources :

Example 1 with Subscriber

use of io.servicetalk.concurrent.PublisherSource.Subscriber in project servicetalk by apple.

the class SubscribeThrowsTest method singleSubscriberThrows.

@Test
void singleSubscriberThrows() {
    Single<String> s = new Single<String>() {

        @Override
        protected void handleSubscribe(final SingleSource.Subscriber subscriber) {
            throw DELIBERATE_EXCEPTION;
        }
    };
    Exception e = assertThrows(ExecutionException.class, () -> s.toFuture().get());
    assertThat(e.getCause(), is(DELIBERATE_EXCEPTION));
}
Also used : Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Example 2 with Subscriber

use of io.servicetalk.concurrent.PublisherSource.Subscriber in project servicetalk by apple.

the class BlockingStreamingToStreamingServiceTest method throwAfterSendMetaData.

@Test
void throwAfterSendMetaData() throws Exception {
    CountDownLatch onErrorLatch = new CountDownLatch(1);
    AtomicReference<Throwable> throwableRef = new AtomicReference<>();
    BlockingStreamingHttpService syncService = (ctx, request, response) -> {
        response.sendMetaData();
        throw DELIBERATE_EXCEPTION;
    };
    StreamingHttpService asyncService = toStreamingHttpService(syncService, offloadNone()).adaptor();
    StreamingHttpResponse asyncResponse = asyncService.handle(mockCtx, reqRespFactory.get("/"), reqRespFactory).subscribeOn(executorExtension.executor()).toFuture().get();
    assertMetaData(OK, asyncResponse);
    toSource(asyncResponse.payloadBody()).subscribe(new Subscriber<Buffer>() {

        @Override
        public void onSubscribe(final Subscription s) {
        }

        @Override
        public void onNext(final Buffer s) {
        }

        @Override
        public void onError(final Throwable t) {
            throwableRef.set(t);
            onErrorLatch.countDown();
        }

        @Override
        public void onComplete() {
        }
    });
    onErrorLatch.await();
    assertThat(throwableRef.get(), is(DELIBERATE_EXCEPTION));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) BiFunction(java.util.function.BiFunction) SingleSource(io.servicetalk.concurrent.SingleSource) ServiceAdapterHolder(io.servicetalk.http.api.HttpApiConversions.ServiceAdapterHolder) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Executor(io.servicetalk.concurrent.api.Executor) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ExecutorExtension(io.servicetalk.concurrent.api.ExecutorExtension) PayloadWriter(io.servicetalk.oio.api.PayloadWriter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) Function.identity(java.util.function.Function.identity) Matchers.is(org.hamcrest.Matchers.is) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(io.servicetalk.concurrent.Cancellable) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Mockito.lenient(org.mockito.Mockito.lenient) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) ArrayList(java.util.ArrayList) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) Nullable(javax.annotation.Nullable) TRAILER(io.servicetalk.http.api.HttpHeaderNames.TRAILER) UTF_8(java.nio.charset.StandardCharsets.UTF_8) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) OK(io.servicetalk.http.api.HttpResponseStatus.OK) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) ExecutionException(java.util.concurrent.ExecutionException) Publisher.failed(io.servicetalk.concurrent.api.Publisher.failed) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) InputStream(java.io.InputStream) Buffer(io.servicetalk.buffer.api.Buffer) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) Test(org.junit.jupiter.api.Test)

Example 3 with Subscriber

use of io.servicetalk.concurrent.PublisherSource.Subscriber in project servicetalk by apple.

the class ConnectablePayloadWriter method close0.

private void close0(@Nullable Throwable cause) {
    // Set closed before state, because the Subscriber thread depends upon this ordering in the event it needs to
    // terminate the Subscriber.
    TerminalNotification terminal = cause == null ? complete() : error(cause);
    if (closedUpdater.compareAndSet(this, null, terminal)) {
        // We need to terminate requested or else we may block indefinitely on subsequent calls to write in
        // waitForRequestNDemand.
        requested = REQUESTN_TERMINATED;
        for (; ; ) {
            final Object currState = state;
            if (currState instanceof Subscriber) {
                if (stateUpdater.compareAndSet(this, currState, State.TERMINATED)) {
                    terminal.terminate((Subscriber<?>) currState);
                    break;
                }
            } else if (currState == State.TERMINATED || stateUpdater.compareAndSet(this, currState, State.TERMINATING)) {
                assert currState != State.WAITING_FOR_CONNECTED;
                break;
            }
        }
    } else {
        Object currState = stateUpdater.getAndSet(this, State.TERMINATED);
        if (currState instanceof Subscriber) {
            final TerminalNotification currClosed = closed;
            assert currClosed != null;
            currClosed.terminate((Subscriber<?>) currState);
        }
    }
}
Also used : Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) TerminalNotification(io.servicetalk.concurrent.internal.TerminalNotification)

Example 4 with Subscriber

use of io.servicetalk.concurrent.PublisherSource.Subscriber in project servicetalk by apple.

the class ConcurrentTerminalSubscriberTest method reentrySynchronousOnNextAllowed.

private void reentrySynchronousOnNextAllowed(boolean onComplete) {
    AtomicReference<Subscription> subscriptionRef = new AtomicReference<>();
    @SuppressWarnings("unchecked") Subscriber<Integer> mockSubscriber = (Subscriber<Integer>) mock(Subscriber.class);
    doAnswer((Answer<Void>) invocation -> {
        Subscription s = invocation.getArgument(0);
        subscriptionRef.set(s);
        s.request(1);
        return null;
    }).when(mockSubscriber).onSubscribe(any());
    doAnswer((Answer<Void>) invocation -> {
        subscriptionRef.get().request(1);
        return null;
    }).when(mockSubscriber).onNext(any());
    ConcurrentTerminalSubscriber<Integer> subscriber = new ConcurrentTerminalSubscriber<>(mockSubscriber);
    publisher.subscribe(subscriber);
    publisher.onSubscribe(new Subscription() {

        private int i;

        @Override
        public void request(final long n) {
            if (i < 5) {
                publisher.onNext(++i);
            } else if (i == 5) {
                ++i;
                if (onComplete) {
                    publisher.onComplete();
                } else {
                    publisher.onError(DELIBERATE_EXCEPTION);
                }
                // This should be filtered, because we need to protect against concurrent termination this may
                // happen concurrently.
                publisher.onNext(i);
            }
        }

        @Override
        public void cancel() {
        }
    });
    ArgumentCaptor<Integer> onNextArgs = ArgumentCaptor.forClass(Integer.class);
    verify(mockSubscriber, times(5)).onNext(onNextArgs.capture());
    assertEquals(asList(1, 2, 3, 4, 5), onNextArgs.getAllValues());
    if (onComplete) {
        verify(mockSubscriber).onComplete();
    } else {
        verify(mockSubscriber).onError(same(DELIBERATE_EXCEPTION));
    }
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CyclicBarrier(java.util.concurrent.CyclicBarrier) ExecutorExtension(io.servicetalk.concurrent.api.ExecutorExtension) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mockito.times(org.mockito.Mockito.times) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Answer(org.mockito.stubbing.Answer) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito.never(org.mockito.Mockito.never) ArgumentCaptor(org.mockito.ArgumentCaptor) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Arrays.asList(java.util.Arrays.asList) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Executor(io.servicetalk.concurrent.api.Executor) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ArgumentMatchers.same(org.mockito.ArgumentMatchers.same) Mockito.mock(org.mockito.Mockito.mock) AtomicReference(java.util.concurrent.atomic.AtomicReference) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) TestSubscription(io.servicetalk.concurrent.api.TestSubscription)

Example 5 with Subscriber

use of io.servicetalk.concurrent.PublisherSource.Subscriber in project servicetalk by apple.

the class ConcurrentTerminalSubscriberTest method concurrentOnComplete.

private void concurrentOnComplete(boolean firstOnComplete, boolean secondOnComplete) throws Exception {
    CyclicBarrier terminalEnterBarrier = new CyclicBarrier(2);
    CountDownLatch terminatedLatch = new CountDownLatch(1);
    @SuppressWarnings("unchecked") Subscriber<Integer> mockSubscriber = (Subscriber<Integer>) mock(Subscriber.class);
    doAnswer((Answer<Void>) invocation -> {
        Subscription s = invocation.getArgument(0);
        s.request(1);
        return null;
    }).when(mockSubscriber).onSubscribe(any());
    doAnswer((Answer<Void>) invocation -> {
        terminalEnterBarrier.await();
        terminatedLatch.countDown();
        return null;
    }).when(mockSubscriber).onComplete();
    doAnswer((Answer<Void>) invocation -> {
        terminalEnterBarrier.await();
        terminatedLatch.countDown();
        return null;
    }).when(mockSubscriber).onError(any());
    ConcurrentTerminalSubscriber<Integer> subscriber = new ConcurrentTerminalSubscriber<>(mockSubscriber);
    publisher.subscribe(subscriber);
    publisher.onSubscribe(subscription);
    EXEC.executor().execute(() -> {
        if (firstOnComplete) {
            publisher.onComplete();
        } else {
            publisher.onError(DELIBERATE_EXCEPTION);
        }
    });
    terminalEnterBarrier.await();
    if (secondOnComplete) {
        publisher.onComplete();
    } else {
        publisher.onError(DELIBERATE_EXCEPTION);
    }
    terminatedLatch.await();
    if (firstOnComplete && secondOnComplete) {
        verify(mockSubscriber).onComplete();
    } else if (!firstOnComplete && !secondOnComplete) {
        verify(mockSubscriber).onError(same(DELIBERATE_EXCEPTION));
    } else {
        try {
            verify(mockSubscriber).onComplete();
        } catch (AssertionError e) {
            verify(mockSubscriber).onError(same(DELIBERATE_EXCEPTION));
        }
    }
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CyclicBarrier(java.util.concurrent.CyclicBarrier) ExecutorExtension(io.servicetalk.concurrent.api.ExecutorExtension) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mockito.times(org.mockito.Mockito.times) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Answer(org.mockito.stubbing.Answer) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito.never(org.mockito.Mockito.never) ArgumentCaptor(org.mockito.ArgumentCaptor) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Arrays.asList(java.util.Arrays.asList) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Executor(io.servicetalk.concurrent.api.Executor) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ArgumentMatchers.same(org.mockito.ArgumentMatchers.same) Mockito.mock(org.mockito.Mockito.mock) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) CyclicBarrier(java.util.concurrent.CyclicBarrier)

Aggregations

Subscriber (io.servicetalk.concurrent.PublisherSource.Subscriber)31 Test (org.junit.jupiter.api.Test)29 Subscription (io.servicetalk.concurrent.PublisherSource.Subscription)27 DELIBERATE_EXCEPTION (io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION)23 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 TestPublisherSubscriber (io.servicetalk.concurrent.test.internal.TestPublisherSubscriber)20 CountDownLatch (java.util.concurrent.CountDownLatch)20 Mockito.mock (org.mockito.Mockito.mock)20 SourceAdapters.toSource (io.servicetalk.concurrent.api.SourceAdapters.toSource)19 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)19 Matchers.is (org.hamcrest.Matchers.is)19 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)19 Mockito.doAnswer (org.mockito.Mockito.doAnswer)19 Publisher.from (io.servicetalk.concurrent.api.Publisher.from)18 Arrays.asList (java.util.Arrays.asList)18 PlatformDependent.throwException (io.servicetalk.utils.internal.PlatformDependent.throwException)16 ArrayList (java.util.ArrayList)16 List (java.util.List)16 Function (java.util.function.Function)16 Mockito.verify (org.mockito.Mockito.verify)16