Search in sources :

Example 36 with ServerContext

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

the class HttpSerializerErrorTest method streamingDeserializationHeaderMismatch.

@ParameterizedTest
@MethodSource("executors")
void streamingDeserializationHeaderMismatch(HttpTestExecutionStrategy serverStrategy) throws Exception {
    serverExecutionStrategy = serverStrategy.executorSupplier.get();
    HttpStreamingSerializerDeserializer<String> streamingSerializer = jsonStreamingSerializer(JACKSON.streamingSerializerDeserializer(String.class));
    try (ServerContext srv = HttpServers.forAddress(localAddress(0)).executionStrategy(serverExecutionStrategy).listenStreamingAndAwait((ctx, request, responseFactory) -> {
        try {
            return succeeded(responseFactory.ok().payloadBody(request.payloadBody(streamingSerializer), streamingSerializer));
        } catch (SerializationException e) {
            return succeeded(responseFactory.badRequest());
        }
    });
        BlockingHttpClient clt = HttpClients.forSingleAddress(serverHostAndPort(srv)).buildBlocking()) {
        HttpResponse resp = clt.request(clt.post("/foo").payloadBody(clt.executionContext().bufferAllocator().fromAscii("hello")));
        assertEquals(BAD_REQUEST, resp.status());
    }
}
Also used : SerializationException(io.servicetalk.serializer.api.SerializationException) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 37 with ServerContext

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

the class HttpSerializerErrorTest method blockingStreamingDeserializationHeaderMismatch.

@ParameterizedTest
@MethodSource("executors")
void blockingStreamingDeserializationHeaderMismatch(HttpTestExecutionStrategy serverStrategy) throws Exception {
    serverExecutionStrategy = serverStrategy.executorSupplier.get();
    HttpStreamingSerializerDeserializer<String> streamingSerializer = jsonStreamingSerializer(JACKSON.streamingSerializerDeserializer(String.class));
    try (ServerContext srv = HttpServers.forAddress(localAddress(0)).executionStrategy(serverExecutionStrategy).listenBlockingStreamingAndAwait((ctx, request, responseFactory) -> {
        try {
            BlockingIterable<String> reqIterable = request.payloadBody(streamingSerializer);
            try (HttpPayloadWriter<String> stream = responseFactory.sendMetaData(streamingSerializer)) {
                for (String reqChunk : reqIterable) {
                    stream.write(reqChunk);
                }
            }
        } catch (SerializationException e) {
            responseFactory.status(BAD_REQUEST);
            responseFactory.sendMetaData().close();
        }
    });
        BlockingHttpClient clt = HttpClients.forSingleAddress(serverHostAndPort(srv)).buildBlocking()) {
        HttpResponse resp = clt.request(clt.post("/foo").payloadBody(clt.executionContext().bufferAllocator().fromAscii("hello")));
        assertEquals(BAD_REQUEST, resp.status());
    }
}
Also used : SerializationException(io.servicetalk.serializer.api.SerializationException) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 38 with ServerContext

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

the class HttpSerializerErrorTest method serializationMapThrowsPropagatesToClient.

@ParameterizedTest
@MethodSource("executors")
void serializationMapThrowsPropagatesToClient(HttpTestExecutionStrategy serverStrategy) throws Exception {
    serverExecutionStrategy = serverStrategy.executorSupplier.get();
    TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() {
    };
    HttpStreamingSerializerDeserializer<Map<String, Object>> streamingSerializer = jsonStreamingSerializer(JACKSON.streamingSerializerDeserializer(mapType));
    HttpSerializerDeserializer<Map<String, Object>> serializer = HttpSerializers.jsonSerializer(JACKSON.serializerDeserializer(mapType));
    try (ServerContext srv = HttpServers.forAddress(localAddress(0)).executionStrategy(serverExecutionStrategy).listenAndAwait((ctx, request, responseFactory) -> responseFactory.ok().toStreamingResponse().payloadBody(request.toStreamingRequest().payloadBody(streamingSerializer).map(result -> {
        throw DELIBERATE_EXCEPTION;
    }), streamingSerializer).toResponse());
        BlockingHttpClient clt = HttpClients.forSingleAddress(serverHostAndPort(srv)).buildBlocking()) {
        HttpResponse resp = clt.request(clt.post("/foo").payloadBody(emptyMap(), serializer));
        assertEquals(INTERNAL_SERVER_ERROR, resp.status());
    }
}
Also used : HttpSerializers.jsonStreamingSerializer(io.servicetalk.http.api.HttpSerializers.jsonStreamingSerializer) SerializationException(io.servicetalk.serializer.api.SerializationException) BAD_REQUEST(io.servicetalk.http.api.HttpResponseStatus.BAD_REQUEST) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) TypeReference(com.fasterxml.jackson.core.type.TypeReference) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) Collections.emptyMap(java.util.Collections.emptyMap) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) JACKSON(io.servicetalk.data.jackson.JacksonSerializerFactory.JACKSON) DEFAULT(io.servicetalk.http.netty.HttpTestExecutionStrategy.DEFAULT) Collection(java.util.Collection) HttpResponse(io.servicetalk.http.api.HttpResponse) BlockingIterable(io.servicetalk.concurrent.BlockingIterable) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpStreamingSerializerDeserializer(io.servicetalk.http.api.HttpStreamingSerializerDeserializer) NO_OFFLOAD(io.servicetalk.http.netty.HttpTestExecutionStrategy.NO_OFFLOAD) HttpSerializers(io.servicetalk.http.api.HttpSerializers) HttpSerializerDeserializer(io.servicetalk.http.api.HttpSerializerDeserializer) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Map(java.util.Map) Collections.emptyMap(java.util.Collections.emptyMap) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 39 with ServerContext

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

the class HttpServerMultipleRequestsTest method consumeOfRequestBodyDoesNotCloseConnection.

@Disabled("https://github.com/apple/servicetalk/issues/981")
@Test
void consumeOfRequestBodyDoesNotCloseConnection() throws Exception {
    StreamingHttpService service = (ctx, request, responseFactory) -> {
        request.messageBody().ignoreElements().subscribe();
        CharSequence requestId = request.headers().get(REQUEST_ID_HEADER);
        if (requestId != null) {
            StreamingHttpResponse response = responseFactory.ok();
            response.headers().set(REQUEST_ID_HEADER, requestId);
            return succeeded(response);
        } else {
            return succeeded(responseFactory.newResponse(BAD_REQUEST));
        }
    };
    final int concurrency = 10;
    final int numRequests = 10;
    CompositeCloseable compositeCloseable = AsyncCloseables.newCompositeCloseable();
    ServerContext ctx = compositeCloseable.append(HttpServers.forAddress(localAddress(0)).ioExecutor(serverContext.ioExecutor()).executor(serverContext.executor()).executionStrategy(defaultStrategy()).listenStreamingAndAwait(service));
    ExecutorService executorService = Executors.newCachedThreadPool();
    try {
        AtomicReference<Throwable> causeRef = new AtomicReference<>();
        CyclicBarrier barrier = new CyclicBarrier(concurrency);
        CountDownLatch latch = new CountDownLatch(concurrency);
        for (int i = 0; i < concurrency; ++i) {
            final int finalI = i;
            executorService.execute(() -> {
                try {
                    StreamingHttpClient client = compositeCloseable.append(HttpClients.forResolvedAddress(serverHostAndPort(ctx)).protocols(h1().maxPipelinedRequests(numRequests).build()).ioExecutor(clientContext.ioExecutor()).executor(clientContext.executor()).executionStrategy(defaultStrategy()).buildStreaming());
                    ReservedStreamingHttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get();
                    compositeCloseable.append(connection);
                    barrier.await();
                    for (int x = 0; x < numRequests; ++x) {
                        makeClientRequestWithId(connection, "thread=" + finalI + " request=" + x);
                    }
                } catch (Throwable cause) {
                    causeRef.compareAndSet(null, cause);
                } finally {
                    latch.countDown();
                }
            });
        }
        latch.await();
        assertNull(causeRef.get());
    } finally {
        executorService.shutdown();
        compositeCloseable.close();
    }
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) ExecutionContextExtension.cached(io.servicetalk.transport.netty.internal.ExecutionContextExtension.cached) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) Disabled(org.junit.jupiter.api.Disabled) AtomicReference(java.util.concurrent.atomic.AtomicReference) BAD_REQUEST(io.servicetalk.http.api.HttpResponseStatus.BAD_REQUEST) 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) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ExecutorService(java.util.concurrent.ExecutorService) CyclicBarrier(java.util.concurrent.CyclicBarrier) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) NettyIoThreadFactory(io.servicetalk.transport.netty.internal.NettyIoThreadFactory) HttpProtocolConfigs.h1(io.servicetalk.http.netty.HttpProtocolConfigs.h1) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AsyncCloseables(io.servicetalk.concurrent.api.AsyncCloseables) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) CyclicBarrier(java.util.concurrent.CyclicBarrier) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) ServerContext(io.servicetalk.transport.api.ServerContext) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) ExecutorService(java.util.concurrent.ExecutorService) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 40 with ServerContext

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

the class MalformedDataAfterHttpMessageTest method afterRequest.

@Test
void afterRequest() throws Exception {
    try (ServerContext server = stServer();
        BlockingHttpClient client = stClient(server.listenAddress())) {
        Buffer malformedBody = client.executionContext().bufferAllocator().fromAscii(CONTENT).writeShort(// malformed data at the end of the request msg
        0);
        HttpRequest request = client.post("/").setHeader(CONTENT_LENGTH, valueOf(CONTENT.length())).setHeader(CONTENT_TYPE, TEXT_PLAIN).payloadBody(malformedBody);
        ReservedBlockingHttpConnection connection = client.reserveConnection(request);
        CountDownLatch connectionClosedLatch = new CountDownLatch(1);
        connection.connectionContext().onClose().whenFinally(connectionClosedLatch::countDown).subscribe();
        assertThrows(IOException.class, () -> connection.request(request));
        // Server should close the connection:
        connectionClosedLatch.await();
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpRequest(io.servicetalk.http.api.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) CountDownLatch(java.util.concurrent.CountDownLatch) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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