Search in sources :

Example 1 with NettyConnectionContext

use of io.servicetalk.transport.netty.internal.NettyConnectionContext 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 NettyConnectionContext

use of io.servicetalk.transport.netty.internal.NettyConnectionContext in project servicetalk by apple.

the class H2PriorKnowledgeFeatureParityTest method bindHttpEchoServer.

private InetSocketAddress bindHttpEchoServer(@Nullable StreamingHttpServiceFilterFactory filterFactory, @Nullable CountDownLatch connectionOnClosingLatch) throws Exception {
    HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0)).protocols(h2PriorKnowledge ? h2Default() : h1Default());
    if (filterFactory != null) {
        serverBuilder.appendServiceFilter(filterFactory);
    }
    if (connectionOnClosingLatch != null) {
        serverBuilder.appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

            @Override
            public Completable accept(final ConnectionContext context) {
                ((NettyConnectionContext) context).onClosing().whenFinally(connectionOnClosingLatch::countDown).subscribe();
                return completed();
            }
        });
    }
    h1ServerContext = serverBuilder.listenStreaming((ctx, request, responseFactory) -> {
        StreamingHttpResponse resp;
        if (request.headers().contains(EXPECT, CONTINUE)) {
            if (request.headers().contains(EXPECT_FAIL_HEADER)) {
                return succeeded(responseFactory.expectationFailed());
            } else {
                resp = responseFactory.continueResponse();
            }
        } else {
            resp = responseFactory.ok();
        }
        resp = resp.transformMessageBody(pub -> pub.ignoreElements().merge(request.messageBody())).transform(new StatelessTrailersTransformer<>());
        CharSequence contentType = request.headers().get(CONTENT_TYPE);
        if (contentType != null) {
            resp.setHeader(CONTENT_TYPE, contentType);
        }
        CharSequence contentLength = request.headers().get(CONTENT_LENGTH);
        if (contentLength != null) {
            resp.setHeader(CONTENT_LENGTH, contentLength);
        }
        CharSequence transferEncoding = request.headers().get(TRANSFER_ENCODING);
        if (transferEncoding != null) {
            resp.setHeader(TRANSFER_ENCODING, transferEncoding);
        }
        resp.headers().set(COOKIE, request.headers().valuesIterator(COOKIE));
        return succeeded(resp);
    }).toFuture().get();
    return (InetSocketAddress) h1ServerContext.listenAddress();
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) UnaryOperator.identity(java.util.function.UnaryOperator.identity) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) SingleSource(io.servicetalk.concurrent.SingleSource) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) UnaryOperator(java.util.function.UnaryOperator) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) Disabled(org.junit.jupiter.api.Disabled) Matchers.hasItems(org.hamcrest.Matchers.hasItems) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) H2StreamResetException(io.servicetalk.http.netty.NettyHttp2ExceptionUtils.H2StreamResetException) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) HttpRequest(io.servicetalk.http.api.HttpRequest) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Matchers.nullValue(org.hamcrest.Matchers.nullValue) HttpCookiePair(io.servicetalk.http.api.HttpCookiePair) EXPECT(io.servicetalk.http.api.HttpHeaderNames.EXPECT) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) PrintWriter(java.io.PrintWriter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) DefaultHttp2SettingsFrame(io.netty.handler.codec.http2.DefaultHttp2SettingsFrame) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) HttpResponse(io.servicetalk.http.api.HttpResponse) Http2SettingsAckFrame(io.netty.handler.codec.http2.Http2SettingsAckFrame) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) POST(io.servicetalk.http.api.HttpRequestMethod.POST) BlockingQueue(java.util.concurrent.BlockingQueue) ChannelPipeline(io.netty.channel.ChannelPipeline) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) Assertions.assertNotSame(org.junit.jupiter.api.Assertions.assertNotSame) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HttpSetCookie(io.servicetalk.http.api.HttpSetCookie) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) COOKIE(io.servicetalk.http.api.HttpHeaderNames.COOKIE) Matchers.is(org.hamcrest.Matchers.is) CONTENT_TYPE(io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Processor(io.servicetalk.concurrent.PublisherSource.Processor) BuilderUtils.serverChannel(io.servicetalk.transport.netty.internal.BuilderUtils.serverChannel) TRAILER(io.netty.handler.codec.http.HttpHeaderNames.TRAILER) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) HttpHeaders(io.servicetalk.http.api.HttpHeaders) ConsumableEvent(io.servicetalk.client.api.ConsumableEvent) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) MAX_CONCURRENCY(io.servicetalk.http.api.HttpEventKey.MAX_CONCURRENCY) HeaderUtils.isTransferEncodingChunked(io.servicetalk.http.api.HeaderUtils.isTransferEncodingChunked) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Processors(io.servicetalk.concurrent.api.Processors) BiConsumer(java.util.function.BiConsumer) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) SMALLEST_MAX_CONCURRENT_STREAMS(io.netty.handler.codec.http2.Http2CodecUtil.SMALLEST_MAX_CONCURRENT_STREAMS) DEFAULT(io.servicetalk.http.netty.HttpTestExecutionStrategy.DEFAULT) Single(io.servicetalk.concurrent.api.Single) StringWriter(java.io.StringWriter) Completable(io.servicetalk.concurrent.api.Completable) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) IOException(java.io.IOException) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) OK(io.servicetalk.http.api.HttpResponseStatus.OK) GET(io.servicetalk.http.api.HttpRequestMethod.GET) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) Matchers.emptyString(org.hamcrest.Matchers.emptyString) Http2FrameCodecBuilder(io.netty.handler.codec.http2.Http2FrameCodecBuilder) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2DataFrame(io.netty.handler.codec.http2.Http2DataFrame) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) PublisherSource(io.servicetalk.concurrent.PublisherSource) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpEventKey(io.servicetalk.http.api.HttpEventKey) List(java.util.List) ContextMap(io.servicetalk.context.api.ContextMap) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Writer(java.io.Writer) Queue(java.util.Queue) CONTINUE(io.servicetalk.http.api.HttpHeaderValues.CONTINUE) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) Http2Exception(io.servicetalk.http.api.Http2Exception) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpProtocolConfigs.h2Default(io.servicetalk.http.netty.HttpProtocolConfigs.h2Default) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) ServerContext(io.servicetalk.transport.api.ServerContext) Iterator(java.util.Iterator) EXPECTATION_FAILED(io.servicetalk.http.api.HttpResponseStatus.EXPECTATION_FAILED) NettyIoExecutors.createIoExecutor(io.servicetalk.transport.netty.internal.NettyIoExecutors.createIoExecutor) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Processors.newPublisherProcessor(io.servicetalk.concurrent.api.Processors.newPublisherProcessor) Consumer(java.util.function.Consumer) Matchers.emptyIterable(org.hamcrest.Matchers.emptyIterable) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) NO_OFFLOAD(io.servicetalk.http.netty.HttpTestExecutionStrategy.NO_OFFLOAD) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandler(io.netty.channel.ChannelHandler) SET_COOKIE(io.servicetalk.http.api.HttpHeaderNames.SET_COOKIE) DefaultHttpCookiePair(io.servicetalk.http.api.DefaultHttpCookiePair) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Completable(io.servicetalk.concurrent.api.Completable) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 3 with NettyConnectionContext

use of io.servicetalk.transport.netty.internal.NettyConnectionContext in project servicetalk by apple.

the class NettyHttpServerConnectionTest method updateFlushStrategy.

@ParameterizedTest(name = "server={0} client={1}")
@MethodSource("executionStrategies")
void updateFlushStrategy(HttpExecutionStrategy serverExecutionStrategy, HttpExecutionStrategy clientExecutionStrategy) throws Exception {
    customStrategy = new MockFlushStrategy();
    AtomicReference<Cancellable> customCancellableRef = new AtomicReference<>();
    AtomicBoolean handledFirstRequest = new AtomicBoolean();
    serverContext = HttpServers.forAddress(localAddress(0)).ioExecutor(contextRule.ioExecutor()).appendConnectionAcceptorFilter(original -> original.append(ctx -> {
        customCancellableRef.set(((NettyConnectionContext) ctx).updateFlushStrategy((__, ___) -> customStrategy));
        return completed();
    })).executionStrategy(serverExecutionStrategy).listenStreaming((ctx, request, responseFactory) -> {
        if (handledFirstRequest.compareAndSet(false, true)) {
            customStrategy.afterFirstWrite(FlushStrategy.FlushSender::flush);
            return succeeded(responseFactory.ok().payloadBody(responsePublisher));
        }
        return succeeded(responseFactory.ok().payloadBody(responsePublisher2));
    }).toFuture().get();
    client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).executionStrategy(clientExecutionStrategy).buildStreaming();
    StreamingHttpResponse response = client.request(client.newRequest(GET, "/1")).toFuture().get();
    FlushStrategy.FlushSender customFlushSender = customStrategy.verifyApplied();
    Cancellable customCancellable = customCancellableRef.get();
    assertNotNull(customCancellable);
    // Verify that the custom strategy is applied and used for flushing.
    customStrategy.verifyWriteStarted();
    customStrategy.verifyItemWritten(1);
    customStrategy.verifyNoMoreInteractions();
    String payloadBodyString = "foo";
    TestSubscription testSubscription1 = new TestSubscription();
    responsePublisher.onSubscribe(testSubscription1);
    testSubscription1.awaitRequestN(1);
    responsePublisher.onNext(DEFAULT_ALLOCATOR.fromAscii(payloadBodyString));
    responsePublisher.onComplete();
    customFlushSender.flush();
    Buffer responsePayload = response.payloadBody().collect(DEFAULT_ALLOCATOR::newBuffer, (results, current) -> {
        results.writeBytes(current);
        return results;
    }).toFuture().get();
    assertEquals(payloadBodyString, responsePayload.toString(US_ASCII));
    customStrategy.verifyItemWritten(2);
    customStrategy.verifyWriteTerminated();
    // Restore the default flush strategy, which should flush on each
    customCancellable.cancel();
    StreamingHttpResponse response2 = client.request(client.newRequest(GET, "/2")).toFuture().get();
    TestSubscription testSubscription2 = new TestSubscription();
    responsePublisher2.onSubscribe(testSubscription2);
    responsePublisher2.onNext(DEFAULT_ALLOCATOR.fromAscii(payloadBodyString));
    responsePublisher2.onComplete();
    responsePayload = response2.payloadBody().collect(DEFAULT_ALLOCATOR::newBuffer, (results, current) -> {
        results.writeBytes(current);
        return results;
    }).toFuture().get();
    assertEquals(payloadBodyString, responsePayload.toString(US_ASCII));
}
Also used : FlushStrategy(io.servicetalk.transport.netty.internal.FlushStrategy) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(io.servicetalk.concurrent.Cancellable) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) MethodSource(org.junit.jupiter.params.provider.MethodSource) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) Arguments(org.junit.jupiter.params.provider.Arguments) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) GET(io.servicetalk.http.api.HttpRequestMethod.GET) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) MockFlushStrategy(io.servicetalk.transport.netty.internal.MockFlushStrategy) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Buffer(io.servicetalk.buffer.api.Buffer) Cancellable(io.servicetalk.concurrent.Cancellable) MockFlushStrategy(io.servicetalk.transport.netty.internal.MockFlushStrategy) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) FlushStrategy(io.servicetalk.transport.netty.internal.FlushStrategy) MockFlushStrategy(io.servicetalk.transport.netty.internal.MockFlushStrategy) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 4 with NettyConnectionContext

use of io.servicetalk.transport.netty.internal.NettyConnectionContext in project servicetalk by apple.

the class DeferredServerChannelBinder method bind.

static Single<HttpServerContext> bind(final HttpExecutionContext executionContext, final ReadOnlyHttpServerConfig config, final SocketAddress listenAddress, @Nullable final InfluencerConnectionAcceptor connectionAcceptor, final StreamingHttpService service, final boolean drainRequestPayloadBody, final boolean sniOnly) {
    final ReadOnlyTcpServerConfig tcpConfig = config.tcpConfig();
    assert tcpConfig.sslContext() != null;
    final BiFunction<Channel, ConnectionObserver, Single<NettyConnectionContext>> channelInit = sniOnly ? (channel, connectionObserver) -> sniInitChannel(listenAddress, channel, config, executionContext, service, drainRequestPayloadBody, connectionObserver) : (channel, connectionObserver) -> alpnInitChannel(listenAddress, channel, config, executionContext, service, drainRequestPayloadBody, connectionObserver);
    // In case ALPN negotiates h2, h2 connection MUST enable auto read for its Channel.
    return TcpServerBinder.bind(listenAddress, tcpConfig, false, executionContext, connectionAcceptor, channelInit, serverConnection -> {
        // Start processing requests on http/1.1 connection:
        if (serverConnection instanceof NettyHttpServerConnection) {
            ((NettyHttpServerConnection) serverConnection).process(true);
        }
    // Nothing to do otherwise as h2 uses auto read on the parent channel
    }).map(delegate -> {
        LOGGER.debug("Started HTTP server with ALPN for address {}", delegate.listenAddress());
        // The ServerContext returned by TcpServerBinder takes care of closing the connectionAcceptor.
        return new NettyHttpServer.NettyHttpServerContext(delegate, service, executionContext);
    });
}
Also used : ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) NettyHttpServerConnection(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerConnection) Logger(org.slf4j.Logger) SocketAddress(java.net.SocketAddress) HTTP_2(io.servicetalk.http.netty.AlpnIds.HTTP_2) Single(io.servicetalk.concurrent.api.Single) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) TcpServerChannelInitializer(io.servicetalk.tcp.netty.internal.TcpServerChannelInitializer) InfluencerConnectionAcceptor(io.servicetalk.transport.netty.internal.InfluencerConnectionAcceptor) TcpServerBinder(io.servicetalk.tcp.netty.internal.TcpServerBinder) ReadOnlyTcpServerConfig(io.servicetalk.tcp.netty.internal.ReadOnlyTcpServerConfig) Channel(io.netty.channel.Channel) ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) HTTP_1_1(io.servicetalk.http.netty.AlpnIds.HTTP_1_1) HttpServerContext(io.servicetalk.http.api.HttpServerContext) NoopChannelInitializer(io.servicetalk.http.netty.AlpnChannelSingle.NoopChannelInitializer) Single.failed(io.servicetalk.concurrent.api.Single.failed) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Nullable(javax.annotation.Nullable) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) NettyHttpServerConnection(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerConnection) Single(io.servicetalk.concurrent.api.Single) Channel(io.netty.channel.Channel) ReadOnlyTcpServerConfig(io.servicetalk.tcp.netty.internal.ReadOnlyTcpServerConfig)

Example 5 with NettyConnectionContext

use of io.servicetalk.transport.netty.internal.NettyConnectionContext in project servicetalk by apple.

the class FlushStrategyOverrideTest method overrideFlush.

@Test
void overrideFlush() throws Throwable {
    NettyConnectionContext nctx = (NettyConnectionContext) conn.connectionContext();
    MockFlushStrategy clientStrategy = new MockFlushStrategy();
    Cancellable c = nctx.updateFlushStrategy((old, isOriginal) -> isOriginal ? clientStrategy : old);
    CountDownLatch reqWritten = new CountDownLatch(1);
    StreamingHttpRequest req = client.get("/flush").payloadBody(from(1, 2, 3).map(count -> ctx.bufferAllocator().fromAscii("" + count)).afterFinally(reqWritten::countDown));
    Future<? extends Collection<Object>> clientResp = conn.request(req).flatMapPublisher(StreamingHttpResponse::messageBody).toFuture();
    // Wait for request to be written.
    reqWritten.await();
    FlushSender clientFlush = clientStrategy.verifyApplied();
    clientStrategy.verifyWriteStarted();
    clientStrategy.verifyItemWritten(5);
    clientStrategy.verifyWriteTerminated();
    clientFlush.flush();
    MockFlushStrategy serverStrategy = service.getLastUsedStrategy();
    FlushSender serverFlush = serverStrategy.verifyApplied();
    serverStrategy.verifyWriteStarted();
    serverStrategy.verifyItemWritten(5);
    serverStrategy.verifyWriteTerminated();
    serverFlush.flush();
    Collection<Object> chunks = clientResp.get();
    assertThat("Unexpected items received.", chunks, hasSize(3));
    // revert to flush on each.
    c.cancel();
    // No more custom strategies.
    Collection<Object> secondReqChunks = conn.request(conn.get("")).flatMapPublisher(StreamingHttpResponse::messageBody).toFuture().get();
    clientStrategy.verifyNoMoreInteractions();
    service.getLastUsedStrategy();
    serverStrategy.verifyNoMoreInteractions();
    assertThat("Unexpected payload for regular flush.", secondReqChunks, empty());
}
Also used : NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Cancellable(io.servicetalk.concurrent.Cancellable) FlushSender(io.servicetalk.transport.netty.internal.FlushStrategy.FlushSender) MockFlushStrategy(io.servicetalk.transport.netty.internal.MockFlushStrategy) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) CountDownLatch(java.util.concurrent.CountDownLatch) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

NettyConnectionContext (io.servicetalk.transport.netty.internal.NettyConnectionContext)10 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)8 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)6 Buffer (io.servicetalk.buffer.api.Buffer)5 Single (io.servicetalk.concurrent.api.Single)5 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)5 Nullable (javax.annotation.Nullable)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 MethodSource (org.junit.jupiter.params.provider.MethodSource)5 Channel (io.netty.channel.Channel)4 Completable (io.servicetalk.concurrent.api.Completable)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)3 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)3 ServerContext (io.servicetalk.transport.api.ServerContext)3 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)3 AfterEach (org.junit.jupiter.api.AfterEach)3 Test (org.junit.jupiter.api.Test)3 Arguments (org.junit.jupiter.params.provider.Arguments)3 Matchers.contentEqualTo (io.servicetalk.buffer.api.Matchers.contentEqualTo)2