Search in sources :

Example 31 with ServerContext

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

the class NettyHttpServerConnectionDrainTest method requestTimesOutWithoutAutoDrainingOrUserConsuming.

@Disabled("https://github.com/apple/servicetalk/issues/981")
@Test
void requestTimesOutWithoutAutoDrainingOrUserConsuming() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    StreamingHttpClient client = null;
    try (ServerContext serverContext = server(false, respondOkWithoutReadingRequest(latch::countDown))) {
        client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).buildStreaming();
        client.request(client.post("/").payloadBody(from(LARGE_TEXT), appSerializerUtf8FixLen())).ignoreElement().subscribe();
        // Wait till the request is received
        assertThrows(TimeoutException.class, latch::await);
    // before initiating graceful close of the server
    } finally {
        closeClient(client);
    }
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ServerContext(io.servicetalk.transport.api.ServerContext) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 32 with ServerContext

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

the class NettyHttpServerConnectionDrainTest method requestIsAutoDrainedWhenUserFailsToConsume.

@Disabled("https://github.com/apple/servicetalk/issues/981")
@Test
void requestIsAutoDrainedWhenUserFailsToConsume() throws Exception {
    BlockingHttpClient client = null;
    try (ServerContext serverContext = server(true, respondOkWithoutReadingRequest())) {
        client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).buildBlocking();
        postLargePayloadAndAssertResponseOk(client);
    } finally {
        closeClient(client);
    }
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 33 with ServerContext

use of io.servicetalk.transport.api.ServerContext 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) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) 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) 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 34 with ServerContext

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

the class NettyHttpServerTest method testServiceThrowsReturnsErrorResponse.

@ParameterizedTest(name = "{displayName} [{index}] disableOffloading={0}")
@ValueSource(booleans = { true, false })
void testServiceThrowsReturnsErrorResponse(boolean disableOffloading) throws Exception {
    // the test suite state isn't used by this individual test, but cleanup code requires it is initialized.
    setUp(IMMEDIATE, IMMEDIATE);
    HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0));
    if (disableOffloading) {
        serverBuilder.executionStrategy(offloadNone());
    }
    try (ServerContext serverCtx = serverBuilder.listenStreamingAndAwait((ctx, request, responseFactory) -> {
        throw DELIBERATE_EXCEPTION;
    });
        BlockingHttpClient client = disableOffloading(HttpClients.forResolvedAddress(serverHostAndPort(serverCtx)), disableOffloading).buildBlocking()) {
        HttpResponse resp = client.request(client.get("/"));
        assertThat(resp.status(), is(INTERNAL_SERVER_ERROR));
    }
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 35 with ServerContext

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

the class PartitionedHttpClientTest method testClientGroupPartitioning.

@Test
void testClientGroupPartitioning() throws Exception {
    // user partition discovery service, userId=1 => srv1 | userId=2 => srv2
    try (ServerContext userDisco = HttpServers.forAddress(localAddress(0)).listenBlockingAndAwait((ctx, request, responseFactory) -> {
        if ("/partition".equals(request.path())) {
            String userIdParam = request.queryParameter("userId");
            if (userIdParam == null || userIdParam.isEmpty()) {
                return responseFactory.badRequest();
            }
            int userId = Integer.parseInt(userIdParam);
            if (userId != 1 && userId != 2) {
                return responseFactory.notFound();
            }
            ServerContext dSrv = userId == 1 ? srv1 : srv2;
            InetSocketAddress socketAddress = (InetSocketAddress) dSrv.listenAddress();
            return responseFactory.ok().payloadBody(socketAddress.getPort() + "", textSerializerUtf8());
        }
        return responseFactory.notFound();
    })) {
        try (PartitioningHttpClientWithOutOfBandDiscovery client = new PartitioningHttpClientWithOutOfBandDiscovery(userDisco)) {
            StreamingHttpResponse httpResponse1 = client.request(new User(1), client.get("/foo")).toFuture().get();
            StreamingHttpResponse httpResponse2 = client.request(new User(2), client.get("/foo")).toFuture().get();
            MatcherAssert.assertThat(httpResponse1.status(), is(OK));
            MatcherAssert.assertThat(httpResponse1.headers().get(X_SERVER), hasToString(SRV_1));
            MatcherAssert.assertThat(httpResponse2.status(), is(OK));
            MatcherAssert.assertThat(httpResponse2.headers().get(X_SERVER), hasToString(SRV_2));
        }
    }
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) InetSocketAddress(java.net.InetSocketAddress) Matchers.hasToString(org.hamcrest.Matchers.hasToString) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

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