Search in sources :

Example 1 with ConnectionFactoryFilter

use of io.servicetalk.client.api.ConnectionFactoryFilter 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 2 with ConnectionFactoryFilter

use of io.servicetalk.client.api.ConnectionFactoryFilter 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)

Aggregations

Buffer (io.servicetalk.buffer.api.Buffer)2 ConnectionFactoryFilter (io.servicetalk.client.api.ConnectionFactoryFilter)2 Single (io.servicetalk.concurrent.api.Single)2 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)2 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)2 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)2 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)2 TransportObserver (io.servicetalk.transport.api.TransportObserver)2 InetSocketAddress (java.net.InetSocketAddress)2 Nullable (javax.annotation.Nullable)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 Matchers.is (org.hamcrest.Matchers.is)2 Channel (io.netty.channel.Channel)1 Sharable (io.netty.channel.ChannelHandler.Sharable)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelOutboundHandler (io.netty.channel.ChannelOutboundHandler)1 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)1 ChannelPromise (io.netty.channel.ChannelPromise)1 Http2MultiplexHandler (io.netty.handler.codec.http2.Http2MultiplexHandler)1 ReferenceCountUtil (io.netty.util.ReferenceCountUtil)1