Search in sources :

Example 6 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient in project servicetalk by apple.

the class ExpectContinueTest method expectationFailedAggregated.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void expectationFailedAggregated(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol);
        StreamingHttpClient client = createClient(serverContext, protocol);
        HttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get().asConnection()) {
        BufferAllocator allocator = connection.executionContext().bufferAllocator();
        Future<HttpResponse> responseFuture = connection.request(newRequest(connection, withCL, true, PAYLOAD + PAYLOAD, allocator)).toFuture();
        requestReceived.await();
        sendContinue.countDown();
        returnResponse.countDown();
        HttpResponse response = responseFuture.get();
        assertThat(response.status(), is(EXPECTATION_FAILED));
        assertThat(response.payloadBody().toString(US_ASCII), equalTo(""));
        sendFollowUpRequest(connection.asStreamingConnection(), withCL, allocator, OK);
    }
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) HttpConnection(io.servicetalk.http.api.HttpConnection) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) HttpServerContext(io.servicetalk.http.api.HttpServerContext) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 7 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient in project servicetalk by apple.

the class ExpectContinueTest method serverRespondsWithRedirect.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void serverRespondsWithRedirect(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol, (ctx, request, response) -> {
        if ("/redirect".equals(request.requestTarget())) {
            response.status(PERMANENT_REDIRECT);
            response.setHeader(LOCATION, "/");
            response.sendMetaData().close();
            return;
        }
        requestReceived.countDown();
        sendContinue.await();
        StringBuilder sb = new StringBuilder();
        request.payloadBody().forEach(chunk -> sb.append(chunk.toString(US_ASCII)));
        returnResponse.await();
        try (HttpPayloadWriter<Buffer> writer = response.sendMetaData()) {
            writer.write(ctx.executionContext().bufferAllocator().fromAscii(sb));
        }
    });
        StreamingHttpClient client = createClient(serverContext, protocol, new RedirectingHttpRequesterFilter(new RedirectConfigBuilder().allowedMethods(POST).headersToRedirect(CONTENT_LENGTH, TRANSFER_ENCODING, EXPECT).redirectPayloadBody(true).build()));
        StreamingHttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get()) {
        BufferAllocator allocator = connection.executionContext().bufferAllocator();
        TestPublisher<Buffer> payload = new TestPublisher.Builder<Buffer>().singleSubscriber().build();
        connection.request(newRequest(connection, withCL, false, payload).requestTarget("/redirect")).subscribe(responses::add);
        requestReceived.await();
        assertThat("Unexpected subscribe to payload body before 100 (Continue)", payload.isSubscribed(), is(false));
        sendContinue.countDown();
        sendRequestPayload(payload, allocator);
        returnResponse.countDown();
        assertResponse(OK, PAYLOAD + PAYLOAD);
        sendFollowUpRequest(connection, withCL, allocator, OK);
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) HttpServerContext(io.servicetalk.http.api.HttpServerContext) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) RedirectingHttpRequesterFilter(io.servicetalk.http.utils.RedirectingHttpRequesterFilter) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 8 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient in project servicetalk by apple.

the class ExpectContinueTest method serverError.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void serverError(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol, (ctx, request, response) -> {
        requestReceived.countDown();
        returnResponse.await();
        if (request.headers().contains(EXPECT, CONTINUE)) {
            response.status(INTERNAL_SERVER_ERROR);
        }
        response.sendMetaData().close();
    });
        StreamingHttpClient client = createClient(serverContext, protocol);
        StreamingHttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get()) {
        TestPublisher<Buffer> payload = new TestPublisher.Builder<Buffer>().singleSubscriber().build();
        connection.request(newRequest(connection, withCL, true, payload)).subscribe(responses::add);
        requestReceived.await();
        assertThat("Unexpected subscribe to payload body before 100 (Continue)", payload.isSubscribed(), is(false));
        returnResponse.countDown();
        assertResponse(INTERNAL_SERVER_ERROR, "");
        // send a follow-up request on the same connection:
        connection.request(connection.get("/")).subscribe(responses::add);
        assertResponse(OK, "");
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) HttpServerContext(io.servicetalk.http.api.HttpServerContext) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 9 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient in project servicetalk by apple.

the class ExpectContinueTest method expectContinueAggregated.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void expectContinueAggregated(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol);
        StreamingHttpClient client = createClient(serverContext, protocol);
        HttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get().asConnection()) {
        BufferAllocator allocator = connection.executionContext().bufferAllocator();
        Future<HttpResponse> responseFuture = connection.request(newRequest(connection, withCL, false, PAYLOAD + PAYLOAD, allocator)).toFuture();
        requestReceived.await();
        sendContinue.countDown();
        returnResponse.countDown();
        HttpResponse response = responseFuture.get();
        assertThat(response.status(), is(OK));
        assertThat(response.payloadBody().toString(US_ASCII), equalTo(PAYLOAD + PAYLOAD));
        sendFollowUpRequest(connection.asStreamingConnection(), withCL, allocator, OK);
    }
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) HttpConnection(io.servicetalk.http.api.HttpConnection) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) HttpServerContext(io.servicetalk.http.api.HttpServerContext) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 10 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient in project servicetalk by apple.

the class HttpConnectionEmptyPayloadTest method headRequestContentEmpty.

@Test
void headRequestContentEmpty() throws Exception {
    try (CompositeCloseable closeable = AsyncCloseables.newCompositeCloseable()) {
        final int expectedContentLength = 128;
        byte[] expectedPayload = new byte[expectedContentLength];
        ThreadLocalRandom.current().nextBytes(expectedPayload);
        ServerContext serverContext = closeable.merge(HttpServers.forAddress(localAddress(0)).ioExecutor(executionContextRule.ioExecutor()).executionStrategy(offloadNone()).listenStreamingAndAwait((ctx, req, factory) -> {
            StreamingHttpResponse resp = factory.ok().payloadBody(from(HEAD.equals(req.method()) ? EMPTY_BUFFER : ctx.executionContext().bufferAllocator().newBuffer(expectedContentLength).writeBytes(expectedPayload)));
            resp.addHeader(CONTENT_LENGTH, String.valueOf(expectedContentLength));
            return succeeded(resp);
        }));
        StreamingHttpClient client = closeable.merge(forResolvedAddress(serverHostAndPort(serverContext)).ioExecutor(executionContextRule.ioExecutor()).protocols(h1().maxPipelinedRequests(3).build()).executor(executionContextRule.executor()).executionStrategy(defaultStrategy()).buildStreaming());
        StreamingHttpConnection connection = closeable.merge(client.reserveConnection(client.get("/")).toFuture().get());
        // Request HEAD, GET, HEAD to verify that we can keep reading data despite a HEAD request providing a hint
        // about content-length (and not actually providing the content).
        Single<StreamingHttpResponse> response1Single = connection.request(connection.newRequest(HEAD, "/"));
        Single<StreamingHttpResponse> response2Single = connection.request(connection.get("/"));
        Single<StreamingHttpResponse> response3Single = connection.request(connection.newRequest(HEAD, "/"));
        StreamingHttpResponse response = awaitIndefinitelyNonNull(response1Single);
        assertEquals(OK, response.status());
        CharSequence contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        // Drain the current response content so we will be able to read the next response.
        response.messageBody().ignoreElements().toFuture().get();
        response = awaitIndefinitelyNonNull(response2Single);
        assertEquals(OK, response.status());
        contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        Buffer buffer = awaitIndefinitelyNonNull(response.payloadBody().collect(() -> connection.connectionContext().executionContext().bufferAllocator().newBuffer(), Buffer::writeBytes));
        byte[] actualBytes = new byte[buffer.readableBytes()];
        buffer.readBytes(actualBytes);
        assertArrayEquals(expectedPayload, actualBytes);
        response = awaitIndefinitelyNonNull(response3Single);
        assertEquals(OK, response.status());
        contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        response.messageBody().ignoreElements().toFuture().get();
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) HEAD(io.servicetalk.http.api.HttpRequestMethod.HEAD) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) HttpProtocolConfigs.h1(io.servicetalk.http.netty.HttpProtocolConfigs.h1) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single(io.servicetalk.concurrent.api.Single) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Integer.parseInt(java.lang.Integer.parseInt) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) Test(org.junit.jupiter.api.Test) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) Buffer(io.servicetalk.buffer.api.Buffer) AsyncCloseables(io.servicetalk.concurrent.api.AsyncCloseables) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ServerContext(io.servicetalk.transport.api.ServerContext) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)76 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)48 RedirectConfigBuilder (io.servicetalk.http.api.RedirectConfigBuilder)33 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)31 Test (org.junit.jupiter.api.Test)31 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)27 Buffer (io.servicetalk.buffer.api.Buffer)24 MethodSource (org.junit.jupiter.params.provider.MethodSource)22 StreamingHttpConnection (io.servicetalk.http.api.StreamingHttpConnection)19 SingleAddressHttpClientBuilder (io.servicetalk.http.api.SingleAddressHttpClientBuilder)16 HttpServerContext (io.servicetalk.http.api.HttpServerContext)15 InetSocketAddress (java.net.InetSocketAddress)15 ServerContext (io.servicetalk.transport.api.ServerContext)13 Single (io.servicetalk.concurrent.api.Single)12 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)11 CountDownLatch (java.util.concurrent.CountDownLatch)11 ExecutionException (java.util.concurrent.ExecutionException)11 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)10 HostAndPort (io.servicetalk.transport.api.HostAndPort)10 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)9