Search in sources :

Example 41 with ServerContext

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

the class DefaultMultiAddressUrlHttpClientBuilderTest method internalClientsUseDifferentExecutionContextWhenConfigured.

@Test
void internalClientsUseDifferentExecutionContextWhenConfigured() throws Exception {
    HttpExecutionContext externalCtx = new HttpExecutionContextBuilder().ioExecutor(CTX.ioExecutor()).executor(CTX.executor()).bufferAllocator(PREFER_HEAP_ALLOCATOR).executionStrategy(offloadAll()).build();
    HttpExecutionContext internalCtx = new HttpExecutionContextBuilder().ioExecutor(INTERNAL_CLIENT_CTX.ioExecutor()).executor(INTERNAL_CLIENT_CTX.executor()).bufferAllocator(PREFER_DIRECT_ALLOCATOR).executionStrategy(offloadNone()).build();
    AtomicReference<HttpExecutionContext> actualInternalCtx = new AtomicReference<>();
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNone()).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok()));
        BlockingHttpClient blockingHttpClient = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> builder.executionStrategy(internalCtx.executionStrategy()).executor(internalCtx.executor()).ioExecutor(internalCtx.ioExecutor()).bufferAllocator(internalCtx.bufferAllocator()).appendClientFilter(client -> {
            actualInternalCtx.set(client.executionContext());
            return new StreamingHttpClientFilter(client) {
            };
        })).executor(externalCtx.executor()).ioExecutor(externalCtx.ioExecutor()).executionStrategy(externalCtx.executionStrategy()).bufferAllocator(externalCtx.bufferAllocator()).buildBlocking()) {
        // Check external client
        assertExecutionContext(externalCtx, blockingHttpClient.executionContext());
        // Make a request to trigger the filter execution that extracts the execution context.
        HttpResponse response = blockingHttpClient.request(blockingHttpClient.get("http://" + serverHostAndPort(serverContext)));
        assertThat(response.status(), is(OK));
        // Check internal client
        assertExecutionContext(internalCtx, actualInternalCtx.get());
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) HttpHeaders(io.servicetalk.http.api.HttpHeaders) 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) HttpRequest(io.servicetalk.http.api.HttpRequest) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) PREFER_HEAP_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.PREFER_HEAP_ALLOCATOR) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) HttpResponse(io.servicetalk.http.api.HttpResponse) 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) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) Mockito.verify(org.mockito.Mockito.verify) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) Test(org.junit.jupiter.api.Test) PREFER_DIRECT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.PREFER_DIRECT_ALLOCATOR) Mockito.never(org.mockito.Mockito.never) HttpExecutionStrategies.offloadAll(io.servicetalk.http.api.HttpExecutionStrategies.offloadAll) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) Matchers.is(org.hamcrest.Matchers.is) HttpHeadersFactory(io.servicetalk.http.api.HttpHeadersFactory) HostAndPort(io.servicetalk.transport.api.HostAndPort) Mockito.mock(org.mockito.Mockito.mock) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) HttpResponse(io.servicetalk.http.api.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.jupiter.api.Test)

Example 42 with ServerContext

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

the class DefaultSingleAddressHttpClientBuilderTest method hostToCharSequenceFunction.

private static void hostToCharSequenceFunction(String hostNamePrefix, String hostName, String hostNameSuffix, @Nullable Integer port) throws Exception {
    try (ServerContext serverCtx = HttpServers.forAddress(localAddress(0)).sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build()).listenBlockingAndAwait((ctx, request, responseFactory) -> responseFactory.ok());
        BlockingHttpClient client = new DefaultSingleAddressHttpClientBuilder<>(hostNamePrefix + hostName + hostNameSuffix + (port == null ? "" : port), GlobalDnsServiceDiscoverer.mappingServiceDiscoverer(u -> serverCtx.listenAddress())).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).hostnameVerificationAlgorithm("").build()).buildBlocking()) {
        ReservedBlockingHttpConnection conn = client.reserveConnection(client.get("/"));
        try {
            SSLSession sslSession = conn.connectionContext().sslSession();
            assertNotNull(sslSession);
            assertThat(sslSession.getPeerHost(), startsWith(hostName));
            InetSocketAddress socketAddress = (InetSocketAddress) conn.connectionContext().remoteAddress();
            assertEquals(socketAddress.getPort(), sslSession.getPeerPort());
        } finally {
            conn.release();
        }
    }
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) InetSocketAddress(java.net.InetSocketAddress) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Test(org.junit.jupiter.api.Test) SSLSession(javax.net.ssl.SSLSession) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) InetSocketAddress(java.net.InetSocketAddress) SSLSession(javax.net.ssl.SSLSession) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 43 with ServerContext

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

the class ConnectionAcceptorOffloadingTest method testAcceptorOffloading.

@ParameterizedTest
@ValueSource(booleans = { false, true })
void testAcceptorOffloading(boolean offload) throws Exception {
    AtomicReference<Boolean> offloaded = new AtomicReference<>();
    ConnectionAcceptorFactory factory = ConnectionAcceptorFactory.withStrategy(original -> context -> {
        boolean isIoThread = IoThreadFactory.IoThread.currentThreadIsIoThread();
        offloaded.set(!isIoThread);
        return original.accept(context);
    }, offload ? ConnectExecutionStrategy.offloadAll() : ConnectExecutionStrategy.offloadNone());
    try (ServerContext server = HttpServers.forPort(0).appendConnectionAcceptorFilter(factory).listenAndAwait(this::helloWorld)) {
        SocketAddress serverAddress = server.listenAddress();
        try (BlockingHttpClient client = HttpClients.forResolvedAddress(serverAddress).buildBlocking()) {
            HttpResponse response = client.request(client.get("/sayHello"));
            assertThat("unexpected status", response.status(), is(HttpResponseStatus.OK));
        }
    }
    assertThat("factory was not invoked", offloaded.get(), is(notNullValue()));
    assertThat("incorrect offloading", offloaded.get(), is(offload));
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) SocketAddress(java.net.SocketAddress) ConnectionAcceptorFactory(io.servicetalk.transport.api.ConnectionAcceptorFactory) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 44 with ServerContext

use of io.servicetalk.transport.api.ServerContext 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 ContextMap context, @Nullable final TransportObserver observer) {
                factoryThread.set(Thread.currentThread());
                return original.newConnection(socketAddress, context, 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) ContextMap(io.servicetalk.context.api.ContextMap) 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)

Example 45 with ServerContext

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

the class ConsumeRequestPayloadOnResponsePathTest method test.

private void test(final BiFunction<Single<StreamingHttpResponse>, StreamingHttpRequest, Single<StreamingHttpResponse>> consumeRequestPayload) throws Exception {
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            return consumeRequestPayload.apply(delegate().handle(ctx, request, responseFactory), request);
        }
    }).listenStreamingAndAwait((ctx, request, responseFactory) -> {
        final StreamingHttpResponse response = responseFactory.ok().addHeader(TRAILER, X_TOTAL_LENGTH).payloadBody(from("Response\n", "Payload\n", "Body\n"), appSerializerUtf8FixLen()).transform(new TrailersTransformer<AtomicInteger, Buffer>() {

            @Override
            public AtomicInteger newState() {
                return new AtomicInteger();
            }

            @Override
            public Buffer accept(final AtomicInteger total, final Buffer chunk) {
                total.addAndGet(chunk.readableBytes());
                return chunk;
            }

            @Override
            public HttpHeaders payloadComplete(final AtomicInteger total, final HttpHeaders trailers) {
                trailers.add(X_TOTAL_LENGTH, String.valueOf(total.get()));
                return trailers;
            }

            @Override
            public HttpHeaders catchPayloadFailure(final AtomicInteger __, final Throwable ___, final HttpHeaders trailers) {
                return trailers;
            }
        });
        return succeeded(response);
    })) {
        HttpResponse response;
        try (BlockingHttpClient client = HttpClients.forSingleAddress(AddressUtils.serverHostAndPort(serverContext)).buildBlocking()) {
            response = client.request(client.post("/").payloadBody(EXPECTED_REQUEST_PAYLOAD, textSerializerUtf8()));
            serverLatch.await();
        }
        assertThat(response.status(), is(OK));
        assertThat("Request payload body might be consumed by someone else", errorRef.get(), is(nullValue()));
        assertThat(receivedPayload.toString(), is(EXPECTED_REQUEST_PAYLOAD));
        assertThat(response.headers().contains(TRAILER, X_TOTAL_LENGTH), is(true));
        assertThat(response.trailers().contains(X_TOTAL_LENGTH), is(true));
        CharSequence trailerLength = response.trailers().get(X_TOTAL_LENGTH);
        assertNotNull(trailerLength);
        assertThat("Unexpected response payload: '" + response.payloadBody().toString(UTF_8) + "'", trailerLength.toString(), is(Integer.toString(response.payloadBody().readableBytes())));
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) BiFunction(java.util.function.BiFunction) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpResponses.newTransportResponse(io.servicetalk.http.api.StreamingHttpResponses.newTransportResponse) PlatformDependent(io.servicetalk.utils.internal.PlatformDependent) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) TRAILER(io.servicetalk.http.api.HttpHeaderNames.TRAILER) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) HttpResponse(io.servicetalk.http.api.HttpResponse) OK(io.servicetalk.http.api.HttpResponseStatus.OK) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) AddressUtils(io.servicetalk.transport.netty.internal.AddressUtils) Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ServerContext(io.servicetalk.transport.api.ServerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Aggregations

ServerContext (io.servicetalk.transport.api.ServerContext)106 Test (org.junit.jupiter.api.Test)57 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)42 HttpResponse (io.servicetalk.http.api.HttpResponse)39 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)34 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)34 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)33 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)28 InetSocketAddress (java.net.InetSocketAddress)27 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)26 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)24 MethodSource (org.junit.jupiter.params.provider.MethodSource)22 HostAndPort (io.servicetalk.transport.api.HostAndPort)20 Single (io.servicetalk.concurrent.api.Single)19 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)19 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)16 ClientSslConfigBuilder (io.servicetalk.transport.api.ClientSslConfigBuilder)15 OK (io.servicetalk.http.api.HttpResponseStatus.OK)14 DefaultTestCerts (io.servicetalk.test.resources.DefaultTestCerts)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)14