Search in sources :

Example 1 with TransportObserver

use of io.servicetalk.transport.api.TransportObserver in project servicetalk by apple.

the class HttpTransportObserverTest method setUp.

private void setUp(HttpProtocol protocol) {
    this.protocol = protocol;
    protocol(protocol.config);
    connectionAcceptor(ctx -> {
        ctx.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
        return completed();
    });
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(HttpServiceContext ctx, StreamingHttpRequest request, StreamingHttpResponseFactory responseFactory) {
            requestReceived.countDown();
            try {
                processRequest.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throwException(e);
            }
            return delegate().handle(ctx, request, responseFactory);
        }
    });
    clientTransportObserver = mock(TransportObserver.class, "clientTransportObserver");
    clientConnectionObserver = mock(ConnectionObserver.class, "clientConnectionObserver");
    clientDataObserver = mock(DataObserver.class, "clientDataObserver");
    clientMultiplexedObserver = mock(MultiplexedObserver.class, "clientMultiplexedObserver");
    clientStreamObserver = mock(StreamObserver.class, "clientStreamObserver");
    clientReadObserver = mock(ReadObserver.class, "clientReadObserver");
    clientWriteObserver = mock(WriteObserver.class, "clientWriteObserver");
    when(clientTransportObserver.onNewConnection(any(), any())).thenReturn(clientConnectionObserver);
    lenient().when(clientConnectionObserver.connectionEstablished(any(ConnectionInfo.class))).thenReturn(clientDataObserver);
    lenient().when(clientConnectionObserver.multiplexedConnectionEstablished(any(ConnectionInfo.class))).thenReturn(clientMultiplexedObserver);
    lenient().when(clientMultiplexedObserver.onNewStream()).thenReturn(clientStreamObserver);
    lenient().when(clientStreamObserver.streamEstablished()).thenReturn(clientDataObserver);
    lenient().when(clientDataObserver.onNewRead()).thenReturn(clientReadObserver);
    lenient().when(clientDataObserver.onNewWrite()).thenReturn(clientWriteObserver);
    serverTransportObserver = mock(TransportObserver.class, "serverTransportObserver");
    serverConnectionObserver = mock(ConnectionObserver.class, "serverConnectionObserver");
    serverDataObserver = mock(DataObserver.class, "serverDataObserver");
    serverMultiplexedObserver = mock(MultiplexedObserver.class, "serverMultiplexedObserver");
    serverStreamObserver = mock(StreamObserver.class, "serverStreamObserver");
    serverReadObserver = mock(ReadObserver.class, "serverReadObserver");
    serverWriteObserver = mock(WriteObserver.class, "serverWriteObserver");
    when(serverTransportObserver.onNewConnection(any(), any())).thenReturn(serverConnectionObserver);
    lenient().when(serverConnectionObserver.connectionEstablished(any(ConnectionInfo.class))).thenReturn(serverDataObserver);
    lenient().when(serverConnectionObserver.multiplexedConnectionEstablished(any(ConnectionInfo.class))).thenReturn(serverMultiplexedObserver);
    lenient().when(serverMultiplexedObserver.onNewStream()).thenReturn(serverStreamObserver);
    lenient().when(serverStreamObserver.streamEstablished()).thenReturn(serverDataObserver);
    lenient().when(serverDataObserver.onNewRead()).thenReturn(serverReadObserver);
    lenient().when(serverDataObserver.onNewWrite()).thenReturn(serverWriteObserver);
    transportObserver(clientTransportObserver, serverTransportObserver);
    setUp(CACHED, CACHED_SERVER);
}
Also used : StreamObserver(io.servicetalk.transport.api.ConnectionObserver.StreamObserver) MultiplexedObserver(io.servicetalk.transport.api.ConnectionObserver.MultiplexedObserver) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) TransportObserver(io.servicetalk.transport.api.TransportObserver) WriteObserver(io.servicetalk.transport.api.ConnectionObserver.WriteObserver) DataObserver(io.servicetalk.transport.api.ConnectionObserver.DataObserver) ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) ConnectionInfo(io.servicetalk.transport.api.ConnectionInfo) ReadObserver(io.servicetalk.transport.api.ConnectionObserver.ReadObserver)

Example 2 with TransportObserver

use of io.servicetalk.transport.api.TransportObserver in project servicetalk by apple.

the class ConnectionFactoryFilterTest method testAppend.

@Test
void testAppend() throws Exception {
    Deque<Integer> createOrder = new ArrayDeque<>();
    Deque<Integer> connectOrder = new ArrayDeque<>();
    class FactoryOrder implements ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> {

        final int order;

        ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> original;

        FactoryOrder(int order, ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> original) {
            this.order = order;
            this.original = original;
        }

        @Override
        public Single<ListenableAsyncCloseable> newConnection(final InetSocketAddress unused, @Nullable final TransportObserver observer) {
            connectOrder.add(order);
            return original.newConnection(unused, observer);
        }

        @Override
        public Completable closeAsync() {
            return Completable.completed();
        }

        @Override
        public Completable onClose() {
            return Completable.completed();
        }
    }
    class FilterOrder implements ConnectionFactoryFilter<InetSocketAddress, ListenableAsyncCloseable> {

        final int order;

        FilterOrder(int order) {
            this.order = order;
        }

        @Override
        public ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> create(final ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> original) {
            createOrder.add(order);
            return new FactoryOrder(order, original);
        }
    }
    FilterOrder first = new FilterOrder(1);
    FilterOrder second = new FilterOrder(2);
    ConnectionFactoryFilter<InetSocketAddress, ListenableAsyncCloseable> combined = first.append(second);
    ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> root = new FactoryOrder(999, new ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable>() {

        @Override
        public Single<ListenableAsyncCloseable> newConnection(final InetSocketAddress unused, @Nullable final TransportObserver observer) {
            return Single.succeeded(DUMMY_CLOSABLE);
        }

        @Override
        public Completable onClose() {
            return Completable.completed();
        }

        @Override
        public Completable closeAsync() {
            return Completable.completed();
        }
    });
    ConnectionFactory<InetSocketAddress, ListenableAsyncCloseable> factory = combined.create(root);
    ListenableAsyncCloseable connection = factory.newConnection(mock(InetSocketAddress.class), null).toFuture().get();
    assertThat(connection, is(sameInstance(DUMMY_CLOSABLE)));
    assertThat(createOrder, is(hasSize(2)));
    assertThat(createOrder, is(containsInRelativeOrder(2, 1)));
    assertThat(connectOrder, is(hasSize(3)));
    assertThat(connectOrder, is(containsInRelativeOrder(1, 2, 999)));
}
Also used : Completable(io.servicetalk.concurrent.api.Completable) InetSocketAddress(java.net.InetSocketAddress) TransportObserver(io.servicetalk.transport.api.TransportObserver) ArrayDeque(java.util.ArrayDeque) Single(io.servicetalk.concurrent.api.Single) ListenableAsyncCloseable(io.servicetalk.concurrent.api.ListenableAsyncCloseable) Nullable(javax.annotation.Nullable) Test(org.junit.jupiter.api.Test)

Example 3 with TransportObserver

use of io.servicetalk.transport.api.TransportObserver in project servicetalk by apple.

the class RetryRequestWithNonRepeatablePayloadTest method setUp.

private void setUp(HttpProtocol protocol, TestPublisher<Buffer> payloadBody, Queue<Throwable> errors, boolean offloading) {
    protocol(protocol.config);
    ChannelOutboundHandler firstWriteHandler = new FailingFirstWriteHandler();
    connectionFactoryFilter(ConnectionFactoryFilter.withStrategy(factory -> new DelegatingConnectionFactory<InetSocketAddress, FilterableStreamingHttpConnection>(factory) {

        @Override
        public Single<FilterableStreamingHttpConnection> newConnection(InetSocketAddress address, @Nullable TransportObserver observer) {
            return delegate().newConnection(address, observer).map(c -> {
                final Channel channel = ((NettyConnectionContext) c.connectionContext()).nettyChannel();
                if (protocol == HTTP_1) {
                    // Insert right before HttpResponseDecoder to avoid seeing failed frames on wire logs
                    channel.pipeline().addBefore(HttpRequestEncoder.class.getSimpleName() + "#0", null, firstWriteHandler);
                } else if (protocol == HTTP_2) {
                    // Insert right before Http2MultiplexHandler to avoid failing connection-level frames and
                    // seeing failed stream frames on frame/wire logs
                    channel.pipeline().addBefore(Http2MultiplexHandler.class.getSimpleName() + "#0", null, firstWriteHandler);
                }
                return new StreamingHttpConnectionFilter(c) {

                    @Override
                    public Single<StreamingHttpResponse> request(StreamingHttpRequest request) {
                        return delegate().request(request).whenOnError(t -> {
                            try {
                                assertThat("Unexpected exception type", t, instanceOf(RetryableException.class));
                                assertThat("Unexpected exception type", t.getCause(), instanceOf(DeliberateException.class));
                                assertThat("Unexpected subscribe to payload body", payloadBody.isSubscribed(), is(false));
                            } catch (Throwable error) {
                                errors.add(error);
                            }
                        });
                    }
                };
            });
        }
    }, ExecutionStrategy.offloadNone()));
    setUp(offloading ? CACHED : IMMEDIATE, offloading ? CACHED_SERVER : IMMEDIATE);
}
Also used : ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Sharable(io.netty.channel.ChannelHandler.Sharable) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) Nullable(javax.annotation.Nullable) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) MethodSource(org.junit.jupiter.params.provider.MethodSource) IMMEDIATE(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.IMMEDIATE) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) Single(io.servicetalk.concurrent.api.Single) Collection(java.util.Collection) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) RetryableException(io.servicetalk.transport.api.RetryableException) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) TransportObserver(io.servicetalk.transport.api.TransportObserver) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) HTTP_1(io.servicetalk.http.netty.HttpProtocol.HTTP_1) InetSocketAddress(java.net.InetSocketAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Channel(io.netty.channel.Channel) TransportObserver(io.servicetalk.transport.api.TransportObserver) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) RetryableException(io.servicetalk.transport.api.RetryableException) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Nullable(javax.annotation.Nullable)

Example 4 with TransportObserver

use of io.servicetalk.transport.api.TransportObserver in project servicetalk by apple.

the class AbstractNettyHttpServerTest method startServer.

private void startServer() throws Exception {
    final InetSocketAddress bindAddress = localAddress(0);
    service(new TestServiceStreaming(publisherSupplier));
    // A small SNDBUF is needed to test that the server defers closing the connection until writes are complete.
    // However, if it is too small, tests that expect certain chunks of data will see those chunks broken up
    // differently.
    final HttpServerBuilder serverBuilder = HttpServers.forAddress(bindAddress).executor(serverExecutor).socketOption(StandardSocketOptions.SO_SNDBUF, 100).protocols(protocol).transportObserver(serverTransportObserver).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true);
    configureServerBuilder(serverBuilder);
    if (sslEnabled) {
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    }
    if (nonOffloadingServiceFilterFactory != null) {
        serverBuilder.appendNonOffloadingServiceFilter(nonOffloadingServiceFilterFactory);
    }
    if (serviceFilterFactory != null) {
        serverBuilder.appendServiceFilter(serviceFilterFactory);
    }
    if (serverLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        serverBuilder.lifecycleObserver(serverLifecycleObserver);
    }
    serverContext = awaitIndefinitelyNonNull(listen(serverBuilder.ioExecutor(serverIoExecutor).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(connectionAcceptor))).beforeOnSuccess(ctx -> LOGGER.debug("Server started on {}.", ctx.listenAddress())).beforeOnError(throwable -> LOGGER.debug("Failed starting server on {}.", bindAddress)));
    final SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = newClientBuilder();
    if (sslEnabled) {
        clientBuilder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build());
    }
    if (connectionFactoryFilter != null) {
        clientBuilder.appendConnectionFactoryFilter(connectionFactoryFilter);
    }
    if (connectionFilterFactory != null) {
        clientBuilder.appendConnectionFilter(connectionFilterFactory);
    }
    if (clientTransportObserver != NoopTransportObserver.INSTANCE) {
        clientBuilder.appendConnectionFactoryFilter(new TransportObserverConnectionFactoryFilter<>(clientTransportObserver));
    }
    if (clientLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        clientBuilder.appendClientFilter(new HttpLifecycleObserverRequesterFilter(clientLifecycleObserver));
    }
    if (clientFilterFactory != null) {
        clientBuilder.appendClientFilter(clientFilterFactory);
    }
    httpClient = clientBuilder.ioExecutor(clientIoExecutor).executor(clientExecutor).executionStrategy(defaultStrategy()).protocols(protocol).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).buildStreaming();
    httpConnection = httpClient.reserveConnection(httpClient.get("/")).toFuture().get();
}
Also used : HttpLifecycleObserver(io.servicetalk.http.api.HttpLifecycleObserver) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) StreamingHttpConnectionFilterFactory(io.servicetalk.http.api.StreamingHttpConnectionFilterFactory) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BeforeAll(org.junit.jupiter.api.BeforeAll) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Executor(io.servicetalk.concurrent.api.Executor) HttpProtocolConfig(io.servicetalk.http.api.HttpProtocolConfig) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) StandardSocketOptions(java.net.StandardSocketOptions) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) InetSocketAddress(java.net.InetSocketAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) Matchers.is(org.hamcrest.Matchers.is) Strictness(org.mockito.quality.Strictness) Assertions.fail(org.junit.jupiter.api.Assertions.fail) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) MockitoSettings(org.mockito.junit.jupiter.MockitoSettings) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpServerContext(io.servicetalk.http.api.HttpServerContext) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpProtocolVersion(io.servicetalk.http.api.HttpProtocolVersion) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DefaultThreadFactory(io.servicetalk.concurrent.api.DefaultThreadFactory) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ACCEPT_ALL(io.servicetalk.transport.api.ConnectionAcceptor.ACCEPT_ALL) NettyIoExecutors(io.servicetalk.transport.netty.NettyIoExecutors) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) ServerContext(io.servicetalk.transport.api.ServerContext) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single(io.servicetalk.concurrent.api.Single) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ExecutionException(java.util.concurrent.ExecutionException) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) IoExecutor(io.servicetalk.transport.api.IoExecutor) AfterEach(org.junit.jupiter.api.AfterEach) Boolean.parseBoolean(java.lang.Boolean.parseBoolean) TransportObserverConnectionFactoryFilter(io.servicetalk.client.api.TransportObserverConnectionFactoryFilter) Executors.newCachedThreadExecutor(io.servicetalk.concurrent.api.Executors.newCachedThreadExecutor) NORM_PRIORITY(java.lang.Thread.NORM_PRIORITY) Executors(io.servicetalk.concurrent.api.Executors) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) NoopTransportObserver(io.servicetalk.transport.netty.internal.NoopTransportObserver) HostAndPort(io.servicetalk.transport.api.HostAndPort) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 5 with TransportObserver

use of io.servicetalk.transport.api.TransportObserver in project servicetalk by apple.

the class ConnectionFactoryOffloadingTest method testFactoryOffloading.

@ParameterizedTest(name = "offload={0} httpStrategy={1}")
@MethodSource("testCases")
void testFactoryOffloading(boolean offload, HttpExecutionStrategy httpStrategy) throws Exception {
    AtomicReference<Thread> factoryThread = new AtomicReference<>();
    Thread appThread = Thread.currentThread();
    try (ServerContext server = HttpServers.forPort(0).listenAndAwait(this::helloWorld)) {
        SocketAddress serverAddress = server.listenAddress();
        ConnectionFactoryFilter<SocketAddress, FilterableStreamingHttpConnection> factory = ConnectionFactoryFilter.withStrategy(original -> new ConnectionFactory<SocketAddress, FilterableStreamingHttpConnection>() {

            private final ListenableAsyncCloseable close = emptyAsyncCloseable();

            @Override
            public Single<FilterableStreamingHttpConnection> newConnection(final SocketAddress socketAddress, @Nullable final TransportObserver observer) {
                factoryThread.set(Thread.currentThread());
                return original.newConnection(socketAddress, observer);
            }

            @Override
            public Completable onClose() {
                return close.onClose();
            }

            @Override
            public Completable closeAsync() {
                return close.closeAsync();
            }

            @Override
            public Completable closeAsyncGracefully() {
                return close.closeAsyncGracefully();
            }
        }, new ConnectAndHttpExecutionStrategy(offload ? ConnectExecutionStrategy.offloadAll() : ConnectExecutionStrategy.offloadNone(), httpStrategy));
        try (HttpClient client = HttpClients.forResolvedAddress(serverAddress).appendConnectionFactoryFilter(factory).build()) {
            assertThat(client.executionContext().executionStrategy().missing(httpStrategy), is(HttpExecutionStrategies.offloadNone()));
            Single<HttpResponse> single = client.request(client.get("/sayHello"));
            HttpResponse response = single.toFuture().get();
            assertThat("unexpected status", response.status(), is(HttpResponseStatus.OK));
        }
    }
    assertTrue((offload && !IoThreadFactory.IoThread.isIoThread(factoryThread.get())) || (!offload && factoryThread.get() == appThread), "incorrect offloading, offload=" + offload + " thread=" + factoryThread.get());
}
Also used : Completable(io.servicetalk.concurrent.api.Completable) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) TransportObserver(io.servicetalk.transport.api.TransportObserver) HttpResponse(io.servicetalk.http.api.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) ConnectAndHttpExecutionStrategy(io.servicetalk.http.api.ConnectAndHttpExecutionStrategy) HttpClient(io.servicetalk.http.api.HttpClient) ListenableAsyncCloseable(io.servicetalk.concurrent.api.ListenableAsyncCloseable) SocketAddress(java.net.SocketAddress) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

Single (io.servicetalk.concurrent.api.Single)5 TransportObserver (io.servicetalk.transport.api.TransportObserver)5 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)3 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)3 InetSocketAddress (java.net.InetSocketAddress)3 Nullable (javax.annotation.Nullable)3 Buffer (io.servicetalk.buffer.api.Buffer)2 ConnectionFactoryFilter (io.servicetalk.client.api.ConnectionFactoryFilter)2 Completable (io.servicetalk.concurrent.api.Completable)2 ListenableAsyncCloseable (io.servicetalk.concurrent.api.ListenableAsyncCloseable)2 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)2 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)2 ServerContext (io.servicetalk.transport.api.ServerContext)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 Matchers.is (org.hamcrest.Matchers.is)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 MethodSource (org.junit.jupiter.params.provider.MethodSource)2 Channel (io.netty.channel.Channel)1 Sharable (io.netty.channel.ChannelHandler.Sharable)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1