Search in sources :

Example 11 with StreamingHttpClient

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

the class HttpLifecycleObserverTest method makeRequestAndAssertResponse.

private void makeRequestAndAssertResponse(String path, HttpProtocol protocol, HttpResponseStatus status, int contentLength) throws Exception {
    StreamingHttpClient client = streamingHttpClient();
    StreamingHttpRequest request = contentLength == 0 ? client.get(path) : client.post(path).payloadBody(Publisher.from(CONTENT.duplicate())).transform(// adds empty trailers
    new StatelessTrailersTransformer<>());
    StreamingHttpResponse response = client.request(request).toFuture().get();
    assertResponse(response, protocol.version, status, contentLength);
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 12 with StreamingHttpClient

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

the class ExecutionStrategyInContextTest method testStreaming.

@ParameterizedTest(name = "customStrategy={0}")
@ValueSource(booleans = { false, true })
void testStreaming(boolean customStrategy) throws Exception {
    StreamingHttpClient client = initClientAndServer(builder -> builder.listenStreaming((ctx, request, responseFactory) -> {
        serviceStrategyRef.set(ctx.executionContext().executionStrategy());
        return succeeded(responseFactory.ok());
    }), customStrategy).buildStreaming();
    clientAsCloseable = client;
    if (!customStrategy) {
        assert expectedClientStrategy == null;
        expectedClientStrategy = defaultStrategy();
        assert expectedServerStrategy == null;
        expectedServerStrategy = defaultStrategy();
    }
    HttpExecutionStrategy clientStrat = client.executionContext().executionStrategy();
    assertThat("Unexpected client strategy.", clientStrat, equalStrategies(expectedClientStrategy));
    client.request(client.get("/")).toFuture().get();
    assertThat("Unexpected service strategy", serviceStrategyRef.get(), equalStrategies(expectedServerStrategy));
    ReservedStreamingHttpConnection conn = client.reserveConnection(client.get("/")).toFuture().get();
    assertThat("Unexpected connection strategy (from execution context).", conn.executionContext().executionStrategy(), equalStrategies(expectedClientStrategy));
    assertThat("Unexpected connection strategy (from execution context).", conn.connectionContext().executionContext().executionStrategy(), equalStrategies(expectedClientStrategy));
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies(io.servicetalk.http.api.HttpExecutionStrategies) HttpServerContext(io.servicetalk.http.api.HttpServerContext) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) HttpClient(io.servicetalk.http.api.HttpClient) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ReservedHttpConnection(io.servicetalk.http.api.ReservedHttpConnection) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) ReservedBlockingStreamingHttpConnection(io.servicetalk.http.api.ReservedBlockingStreamingHttpConnection) ValueSource(org.junit.jupiter.params.provider.ValueSource) Description(org.hamcrest.Description) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) InetSocketAddress(java.net.InetSocketAddress) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) Objects(java.util.Objects) HttpExecutionStrategies.customStrategyBuilder(io.servicetalk.http.api.HttpExecutionStrategies.customStrategyBuilder) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Matcher(org.hamcrest.Matcher) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) HostAndPort(io.servicetalk.transport.api.HostAndPort) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 13 with StreamingHttpClient

use of io.servicetalk.http.api.StreamingHttpClient 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 14 with StreamingHttpClient

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

the class HttpTransportObserverAsyncContextTest method clientErrorWrite.

@ParameterizedTest(name = "protocol={0}")
@EnumSource(HttpProtocol.class)
void clientErrorWrite(HttpProtocol httpProtocol) {
    setUp(httpProtocol);
    StreamingHttpClient client = streamingHttpClient();
    assertThrows(ExecutionException.class, () -> client.request(client.post(SVC_NO_CONTENT_AFTER_READ).payloadBody(Publisher.failed(DELIBERATE_EXCEPTION))).toFuture().get());
    assertMap(clientObserver.storageMap(), CLIENT_VALUE);
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 15 with StreamingHttpClient

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

the class LoadBalancerReadyHttpClientTest method verifyFailsAction0.

private Throwable verifyFailsAction0(Function<StreamingHttpClient, Single<?>> action, Consumer<Throwable> errorConsumer, Throwable error) throws InterruptedException {
    StreamingHttpClient client = TestStreamingHttpClient.from(reqRespFactory, mockExecutionCtx, appendClientFilterFactory(newAutomaticRetryFilterFactory(loadBalancerPublisher, sdStatusCompletable), testHandler));
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<Throwable> causeRef = new AtomicReference<>();
    action.apply(client).whenOnError(causeRef::set).afterFinally(latch::countDown).toCompletable().subscribe();
    // We don't expect the request to complete until onInitialized completes.
    assertThat(latch.await(100, MILLISECONDS), is(false));
    // When a failure occurs that should also fail the action!
    errorConsumer.accept(error);
    latch.await();
    return causeRef.get();
}
Also used : TestStreamingHttpClient(io.servicetalk.http.api.TestStreamingHttpClient) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)77 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)48 RedirectConfigBuilder (io.servicetalk.http.api.RedirectConfigBuilder)33 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)30 Test (org.junit.jupiter.api.Test)30 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)26 Buffer (io.servicetalk.buffer.api.Buffer)24 MethodSource (org.junit.jupiter.params.provider.MethodSource)22 StreamingHttpConnection (io.servicetalk.http.api.StreamingHttpConnection)19 InetSocketAddress (java.net.InetSocketAddress)16 HttpServerContext (io.servicetalk.http.api.HttpServerContext)15 SingleAddressHttpClientBuilder (io.servicetalk.http.api.SingleAddressHttpClientBuilder)15 ServerContext (io.servicetalk.transport.api.ServerContext)14 Single (io.servicetalk.concurrent.api.Single)12 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)11 HostAndPort (io.servicetalk.transport.api.HostAndPort)11 CountDownLatch (java.util.concurrent.CountDownLatch)11 ExecutionException (java.util.concurrent.ExecutionException)11 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)10 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)10