Search in sources :

Example 1 with ExecutionStrategy

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

the class GracefulConnectionClosureHandlingTest method setUp.

void setUp(HttpProtocol protocol, boolean initiateClosureFromClient, boolean useUds, boolean viaProxy) throws Exception {
    this.protocol = protocol;
    this.initiateClosureFromClient = initiateClosureFromClient;
    if (useUds) {
        Assumptions.assumeTrue(SERVER_CTX.ioExecutor().isUnixDomainSocketSupported(), "Server's IoExecutor does not support UnixDomainSocket");
        Assumptions.assumeTrue(CLIENT_CTX.ioExecutor().isUnixDomainSocketSupported(), "Client's IoExecutor does not support UnixDomainSocket");
        assumeFalse(viaProxy, "UDS cannot be used via proxy");
    }
    assumeFalse(protocol == HTTP_2 && viaProxy, "Proxy is not supported with HTTP/2");
    HttpServerBuilder serverBuilder = (useUds ? forAddress(newSocketAddress()) : forAddress(localAddress(0))).protocols(protocol.config).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

        @Override
        public Completable accept(final ConnectionContext context) {
            if (!initiateClosureFromClient) {
                ((NettyConnectionContext) context).onClosing().whenFinally(onClosing::countDown).subscribe();
            }
            context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
            connectionAccepted.countDown();
            return completed();
        }
    });
    HostAndPort proxyAddress = null;
    if (viaProxy) {
        // Dummy proxy helps to emulate old intermediate systems that do not support half-closed TCP connections
        proxyTunnel = new ProxyTunnel();
        proxyAddress = proxyTunnel.startProxy();
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    } else {
        proxyTunnel = null;
    }
    serverContext = serverBuilder.listenBlockingStreamingAndAwait((ctx, request, response) -> {
        serverReceivedRequest.countDown();
        response.addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length()));
        serverSendResponse.await();
        try (HttpPayloadWriter<String> writer = response.sendMetaData(RAW_STRING_SERIALIZER)) {
            // Subscribe to the request payload body before response writer closes
            BlockingIterator<Buffer> iterator = request.payloadBody().iterator();
            // Consume request payload body asynchronously:
            ctx.executionContext().executor().submit(() -> {
                int receivedSize = 0;
                while (iterator.hasNext()) {
                    Buffer chunk = iterator.next();
                    assert chunk != null;
                    receivedSize += chunk.readableBytes();
                }
                serverReceivedRequestPayload.add(receivedSize);
            }).beforeOnError(cause -> {
                LOGGER.error("failure while reading request", cause);
                serverReceivedRequestPayload.add(-1);
            }).toFuture();
            serverSendResponsePayload.await();
            writer.write(RESPONSE_CONTENT);
        }
    });
    serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
    client = (viaProxy ? forSingleAddress(serverHostAndPort(serverContext)).proxyAddress(proxyAddress).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build()) : forResolvedAddress(serverContext.listenAddress())).protocols(protocol.config).executor(CLIENT_CTX.executor()).ioExecutor(CLIENT_CTX.ioExecutor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).appendConnectionFactoryFilter(ConnectionFactoryFilter.withStrategy(cf -> initiateClosureFromClient ? new OnClosingConnectionFactoryFilter<>(cf, onClosing) : cf, ExecutionStrategy.offloadNone())).buildStreaming();
    connection = client.reserveConnection(client.get("/")).toFuture().get();
    connection.onClose().whenFinally(clientConnectionClosed::countDown).subscribe();
    // wait until server accepts connection
    connectionAccepted.await();
    toClose = initiateClosureFromClient ? connection : serverContext;
}
Also used : SocketAddress(java.net.SocketAddress) HttpProtocol.values(io.servicetalk.http.netty.HttpProtocol.values) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) HttpSerializers.stringStreamingSerializer(io.servicetalk.http.api.HttpSerializers.stringStreamingSerializer) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) Future(java.util.concurrent.Future) CloseEvent(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays.asList(java.util.Arrays.asList) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MethodSource(org.junit.jupiter.params.provider.MethodSource) GRACEFUL_USER_CLOSING(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.GRACEFUL_USER_CLOSING) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) CHANNEL_CLOSED_INBOUND(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.CHANNEL_CLOSED_INBOUND) BlockingQueue(java.util.concurrent.BlockingQueue) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) HttpsProxyTest.safeClose(io.servicetalk.http.netty.HttpsProxyTest.safeClose) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) Matchers.is(org.hamcrest.Matchers.is) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) CloseEventObservedException(io.servicetalk.transport.netty.internal.CloseHandler.CloseEventObservedException) Objects.requireNonNull(java.util.Objects.requireNonNull) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) AsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseable) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) AddressUtils.newSocketAddress(io.servicetalk.transport.netty.internal.AddressUtils.newSocketAddress) ServerContext(io.servicetalk.transport.api.ServerContext) ClosedChannelException(java.nio.channels.ClosedChannelException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) IOException(java.io.IOException) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Integer.parseInt(java.lang.Integer.parseInt) ExecutionException(java.util.concurrent.ExecutionException) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Assumptions(org.junit.jupiter.api.Assumptions) Executable(org.junit.jupiter.api.function.Executable) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) HttpStreamingSerializer(io.servicetalk.http.api.HttpStreamingSerializer) HostAndPort(io.servicetalk.transport.api.HostAndPort) Buffer(io.servicetalk.buffer.api.Buffer) Completable(io.servicetalk.concurrent.api.Completable) 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) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 2 with ExecutionStrategy

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

the class DefaultMultiAddressUrlHttpClientBuilderTest method internalClientsUseDifferentExecutionContextWhenConfigured.

@Test
void internalClientsUseDifferentExecutionContextWhenConfigured() throws Exception {
    // Assert prerequisites first.
    // Use different strategies, as ExecutionContextExtension shares the same strategy.
    HttpExecutionStrategy internalExecutionStrategy = HttpExecutionStrategies.customStrategyBuilder().offloadNone().build();
    HttpExecutionStrategy externalExecutionStrategy = HttpExecutionStrategies.customStrategyBuilder().offloadAll().build();
    assertThat(internalExecutionStrategy, not(equalTo(externalExecutionStrategy)));
    BufferAllocator internalBufferAllocator = BufferAllocators.PREFER_DIRECT_ALLOCATOR;
    BufferAllocator externalBufferAllocator = BufferAllocators.PREFER_HEAP_ALLOCATOR;
    assertThat(internalBufferAllocator, not(equalTo(externalBufferAllocator)));
    assertThat(CTX.executor(), not(equalTo(INTERNAL_CLIENT_CTX.executor())));
    assertThat(CTX.ioExecutor(), not(equalTo(INTERNAL_CLIENT_CTX.ioExecutor())));
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNever()).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok()))) {
        AtomicReference<BufferAllocator> actualInternalBufferAllocator = new AtomicReference<>();
        AtomicReference<IoExecutor> actualInternalIoExecutor = new AtomicReference<>();
        AtomicReference<Executor> actualInternalExecutor = new AtomicReference<>();
        AtomicReference<ExecutionStrategy> actualInternalExecutionStrategy = new AtomicReference<>();
        final StreamingHttpClient streamingHttpClient = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> builder.executionStrategy(internalExecutionStrategy).executor(INTERNAL_CLIENT_CTX.executor()).ioExecutor(INTERNAL_CLIENT_CTX.ioExecutor()).bufferAllocator(internalBufferAllocator).executionStrategy(internalExecutionStrategy).appendClientFilter(client -> {
            HttpExecutionContext internalContext = client.executionContext();
            actualInternalBufferAllocator.set(internalContext.bufferAllocator());
            actualInternalExecutor.set(internalContext.executor());
            actualInternalIoExecutor.set(internalContext.ioExecutor());
            actualInternalExecutionStrategy.set(internalContext.executionStrategy());
            return new StreamingHttpClientFilter(client) {
            };
        })).executor(CTX.executor()).ioExecutor(CTX.ioExecutor()).executionStrategy(externalExecutionStrategy).bufferAllocator(externalBufferAllocator).buildStreaming();
        assertNotNull(streamingHttpClient);
        // Check external client
        final HttpExecutionContext executionContext = streamingHttpClient.executionContext();
        assertThat(executionContext.executor(), equalTo(CTX.executor()));
        assertThat(executionContext.executionStrategy(), equalTo(externalExecutionStrategy));
        assertThat(executionContext.ioExecutor(), equalTo(CTX.ioExecutor()));
        assertThat(executionContext.bufferAllocator(), equalTo(CTX.bufferAllocator()));
        // Make a request to trigger the filter execution that extracts the execution context.
        final HostAndPort address = HostAndPort.of((InetSocketAddress) serverContext.listenAddress());
        streamingHttpClient.reserveConnection(streamingHttpClient.get("http://" + address)).toFuture().get();
        // Check internal client
        assertThat(actualInternalBufferAllocator.get(), equalTo(internalBufferAllocator));
        assertThat(actualInternalExecutor.get(), equalTo(INTERNAL_CLIENT_CTX.executor()));
        assertThat(actualInternalIoExecutor.get(), equalTo(INTERNAL_CLIENT_CTX.ioExecutor()));
        assertThat(actualInternalExecutionStrategy.get(), equalTo(internalExecutionStrategy));
        streamingHttpClient.closeAsync().toFuture().get();
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Matchers.not(org.hamcrest.Matchers.not) ExecutionContextExtension.cached(io.servicetalk.transport.netty.internal.ExecutionContextExtension.cached) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) ServiceDiscovererEvent(io.servicetalk.client.api.ServiceDiscovererEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpRequester(io.servicetalk.http.api.HttpRequester) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies(io.servicetalk.http.api.HttpExecutionStrategies) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) Executor(io.servicetalk.concurrent.api.Executor) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) ServiceDiscoverer(io.servicetalk.client.api.ServiceDiscoverer) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) BlockingHttpRequester(io.servicetalk.http.api.BlockingHttpRequester) BlockingStreamingHttpRequester(io.servicetalk.http.api.BlockingStreamingHttpRequester) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) InetSocketAddress(java.net.InetSocketAddress) Mockito.verify(org.mockito.Mockito.verify) BufferAllocators(io.servicetalk.buffer.netty.BufferAllocators) Test(org.junit.jupiter.api.Test) IoExecutor(io.servicetalk.transport.api.IoExecutor) Mockito.never(org.mockito.Mockito.never) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) Matchers.equalTo(org.hamcrest.Matchers.equalTo) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) Mockito.mock(org.mockito.Mockito.mock) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) IoExecutor(io.servicetalk.transport.api.IoExecutor) AtomicReference(java.util.concurrent.atomic.AtomicReference) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) HostAndPort(io.servicetalk.transport.api.HostAndPort) Executor(io.servicetalk.concurrent.api.Executor) IoExecutor(io.servicetalk.transport.api.IoExecutor) ServerContext(io.servicetalk.transport.api.ServerContext) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) Test(org.junit.jupiter.api.Test)

Example 3 with ExecutionStrategy

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

the class DefaultSingleAddressHttpClientBuilder method buildStreaming.

private static <U, R> StreamingHttpClient buildStreaming(final HttpClientBuildContext<U, R> ctx) {
    final ReadOnlyHttpClientConfig roConfig = ctx.httpConfig().asReadOnly();
    final HttpExecutionContext executionContext = ctx.builder.executionContextBuilder.build();
    if (roConfig.h2Config() != null && roConfig.hasProxy()) {
        throw new IllegalStateException("Proxying is not yet supported with HTTP/2");
    }
    // Track resources that potentially need to be closed when an exception is thrown during buildStreaming
    final CompositeCloseable closeOnException = newCompositeCloseable();
    try {
        final Publisher<? extends Collection<? extends ServiceDiscovererEvent<R>>> sdEvents = ctx.serviceDiscoverer(executionContext).discover(ctx.address());
        ConnectionFactoryFilter<R, FilterableStreamingHttpConnection> connectionFactoryFilter = ctx.builder.connectionFactoryFilter;
        ExecutionStrategy connectionFactoryStrategy = ctx.builder.strategyComputation.buildForConnectionFactory();
        final SslContext sslContext = roConfig.tcpConfig().sslContext();
        if (roConfig.hasProxy() && sslContext != null) {
            assert roConfig.connectAddress() != null;
            ConnectionFactoryFilter<R, FilterableStreamingHttpConnection> proxy = new ProxyConnectConnectionFactoryFilter<>(roConfig.connectAddress());
            connectionFactoryFilter = proxy.append(connectionFactoryFilter);
            connectionFactoryStrategy = connectionFactoryStrategy.merge(proxy.requiredOffloads());
        }
        final HttpExecutionStrategy executionStrategy = executionContext.executionStrategy();
        // closed by the LoadBalancer
        final ConnectionFactory<R, LoadBalancedStreamingHttpConnection> connectionFactory;
        final StreamingHttpRequestResponseFactory reqRespFactory = defaultReqRespFactory(roConfig, executionContext.bufferAllocator());
        if (roConfig.isH2PriorKnowledge()) {
            H2ProtocolConfig h2Config = roConfig.h2Config();
            assert h2Config != null;
            connectionFactory = new H2LBHttpConnectionFactory<>(roConfig, executionContext, ctx.builder.connectionFilterFactory, reqRespFactory, connectionFactoryStrategy, connectionFactoryFilter, ctx.builder.loadBalancerFactory::toLoadBalancedConnection);
        } else if (roConfig.tcpConfig().preferredAlpnProtocol() != null) {
            H1ProtocolConfig h1Config = roConfig.h1Config();
            H2ProtocolConfig h2Config = roConfig.h2Config();
            connectionFactory = new AlpnLBHttpConnectionFactory<>(roConfig, executionContext, ctx.builder.connectionFilterFactory, new AlpnReqRespFactoryFunc(executionContext.bufferAllocator(), h1Config == null ? null : h1Config.headersFactory(), h2Config == null ? null : h2Config.headersFactory()), connectionFactoryStrategy, connectionFactoryFilter, ctx.builder.loadBalancerFactory::toLoadBalancedConnection);
        } else {
            H1ProtocolConfig h1Config = roConfig.h1Config();
            assert h1Config != null;
            connectionFactory = new PipelinedLBHttpConnectionFactory<>(roConfig, executionContext, ctx.builder.connectionFilterFactory, reqRespFactory, connectionFactoryStrategy, connectionFactoryFilter, ctx.builder.loadBalancerFactory::toLoadBalancedConnection);
        }
        final LoadBalancer<LoadBalancedStreamingHttpConnection> lb = closeOnException.prepend(ctx.builder.loadBalancerFactory.newLoadBalancer(targetAddress(ctx), sdEvents, connectionFactory));
        ContextAwareStreamingHttpClientFilterFactory currClientFilterFactory = ctx.builder.clientFilterFactory;
        if (roConfig.hasProxy() && sslContext == null) {
            // If we're talking to a proxy over http (not https), rewrite the request-target to absolute-form, as
            // specified by the RFC: https://tools.ietf.org/html/rfc7230#section-5.3.2
            currClientFilterFactory = appendFilter(currClientFilterFactory, ctx.builder.proxyAbsoluteAddressFilterFactory());
        }
        if (ctx.builder.addHostHeaderFallbackFilter) {
            currClientFilterFactory = appendFilter(currClientFilterFactory, new HostHeaderHttpRequesterFilter(ctx.builder.hostToCharSequenceFunction.apply(ctx.builder.address)));
        }
        FilterableStreamingHttpClient lbClient = closeOnException.prepend(new LoadBalancedStreamingHttpClient(executionContext, lb, reqRespFactory));
        if (ctx.builder.retryingHttpRequesterFilter == null) {
            ctx.builder.retryingHttpRequesterFilter = DEFAULT_AUTO_RETRIES;
            currClientFilterFactory = appendFilter(currClientFilterFactory, ctx.builder.retryingHttpRequesterFilter);
        }
        HttpExecutionStrategy computedStrategy = ctx.builder.strategyComputation.buildForClient(executionStrategy);
        LOGGER.debug("Client for {} created with base strategy {} → computed strategy {}", targetAddress(ctx), executionStrategy, computedStrategy);
        return new FilterableClientToClient(currClientFilterFactory != null ? currClientFilterFactory.create(lbClient, lb.eventStream(), ctx.sdStatus) : lbClient, computedStrategy);
    } catch (final Throwable t) {
        closeOnException.closeAsync().subscribe();
        throw t;
    }
}
Also used : CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) StreamingHttpRequestResponseFactory(io.servicetalk.http.api.StreamingHttpRequestResponseFactory) DefaultStreamingHttpRequestResponseFactory(io.servicetalk.http.api.DefaultStreamingHttpRequestResponseFactory) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) SslContext(io.netty.handler.ssl.SslContext) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext)

Example 4 with ExecutionStrategy

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

the class ClientStrategyInfluencerChainBuilder method add.

void add(ConnectionFactoryFilter<?, FilterableStreamingHttpConnection> connectionFactoryFilter) {
    ExecutionStrategy filterOffloads = connectionFactoryFilter.requiredOffloads();
    if (offloadNever() == filterOffloads) {
        LOGGER.warn("{}#requiredOffloads() returns offloadNever(), which is unexpected. " + "offloadNone() should be used instead. " + "Making automatic adjustment, consider updating the filter.", connectionFactoryFilter);
        filterOffloads = offloadNone();
    }
    if (defaultStrategy() == filterOffloads) {
        LOGGER.warn("{}#requiredOffloads() returns defaultStrategy(), which is unexpected. " + "offloadAll() (safe default) or more appropriate custom strategy should be used instead." + "Making automatic adjustment, consider updating the filter.", connectionFactoryFilter);
        filterOffloads = offloadAll();
    }
    connFactoryChain = null != connFactoryChain ? connFactoryChain.merge(filterOffloads) : ConnectAndHttpExecutionStrategy.from(filterOffloads);
}
Also used : ConnectAndHttpExecutionStrategy(io.servicetalk.http.api.ConnectAndHttpExecutionStrategy) ConnectExecutionStrategy(io.servicetalk.transport.api.ConnectExecutionStrategy) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy)

Aggregations

ExecutionStrategy (io.servicetalk.transport.api.ExecutionStrategy)4 HttpExecutionStrategy (io.servicetalk.http.api.HttpExecutionStrategy)3 AsyncCloseables.newCompositeCloseable (io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable)2 CompositeCloseable (io.servicetalk.concurrent.api.CompositeCloseable)2 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)2 HttpExecutionContext (io.servicetalk.http.api.HttpExecutionContext)2 HttpExecutionStrategies.defaultStrategy (io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy)2 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)2 HostAndPort (io.servicetalk.transport.api.HostAndPort)2 SslContext (io.netty.handler.ssl.SslContext)1 Buffer (io.servicetalk.buffer.api.Buffer)1 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)1 Matchers.contentEqualTo (io.servicetalk.buffer.api.Matchers.contentEqualTo)1 BufferAllocators (io.servicetalk.buffer.netty.BufferAllocators)1 ConnectionFactory (io.servicetalk.client.api.ConnectionFactory)1 ConnectionFactoryFilter (io.servicetalk.client.api.ConnectionFactoryFilter)1 DelegatingConnectionFactory (io.servicetalk.client.api.DelegatingConnectionFactory)1 ServiceDiscoverer (io.servicetalk.client.api.ServiceDiscoverer)1 ServiceDiscovererEvent (io.servicetalk.client.api.ServiceDiscovererEvent)1 BlockingIterator (io.servicetalk.concurrent.BlockingIterator)1