Search in sources :

Example 1 with ReservedStreamingHttpConnection

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

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

the class GracefulCloseTest method useConnection.

@ParameterizedTest
@EnumSource(TrailerAddType.class)
void useConnection(TrailerAddType trailerAddType) throws Exception {
    setUp(trailerAddType);
    ReservedStreamingHttpConnection conn = client.reserveConnection(client.get("/")).toFuture().get();
    StreamingHttpResponse resp = conn.request(client.get("/").payloadBody(from("Hello"), appSerializerUtf8FixLen())).toFuture().get();
    assertThat("Unexpected response.", resp.status().code(), equalTo(HttpResponseStatus.OK.code()));
    // Drain response.
    resp.payloadBody().toFuture().get();
    conn.close();
}
Also used : ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with ReservedStreamingHttpConnection

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

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

the class ConnectionFactoryFilterTest method onClosingIsDelegated.

@Test
void onClosingIsDelegated() throws Exception {
    CompletableSource.Processor onClosing = newCompletableProcessor();
    client = clientBuilder.appendConnectionFactoryFilter(newConnectionFactoryFilter(delegate -> new NettyConnectionContextReturningConnection(delegate, onClosing))).buildBlocking();
    ReservedStreamingHttpConnection con = client.asStreamingClient().reserveConnection(client.get("/")).toFuture().get();
    NettyConnectionContext ctx = (NettyConnectionContext) con.connectionContext();
    onClosing.onComplete();
    ctx.onClosing().toFuture().get();
}
Also used : FlushStrategy(io.servicetalk.transport.netty.internal.FlushStrategy) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) UnaryOperator(java.util.function.UnaryOperator) Cancellable(io.servicetalk.concurrent.Cancellable) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Nonnull(javax.annotation.Nonnull) HttpConnectionContext(io.servicetalk.http.api.HttpConnectionContext) Nullable(javax.annotation.Nullable) Processors.newCompletableProcessor(io.servicetalk.concurrent.api.Processors.newCompletableProcessor) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) Completable(io.servicetalk.concurrent.api.Completable) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) HttpResponse(io.servicetalk.http.api.HttpResponse) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) InetSocketAddress(java.net.InetSocketAddress) CompletableSource(io.servicetalk.concurrent.CompletableSource) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) Channel(io.netty.channel.Channel) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportObserver(io.servicetalk.transport.api.TransportObserver) Matchers.is(org.hamcrest.Matchers.is) AsyncCloseables(io.servicetalk.concurrent.api.AsyncCloseables) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) DelegatingHttpConnectionContext(io.servicetalk.http.api.DelegatingHttpConnectionContext) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) HostAndPort(io.servicetalk.transport.api.HostAndPort) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) CompletableSource(io.servicetalk.concurrent.CompletableSource) Test(org.junit.jupiter.api.Test)

Example 5 with ReservedStreamingHttpConnection

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

the class LoadBalancedStreamingHttpClient method reserveConnection.

@Override
public Single<ReservedStreamingHttpConnection> reserveConnection(final HttpRequestMetaData metaData) {
    return Single.defer(() -> {
        Single<ReservedStreamingHttpConnection> connection = loadBalancer.selectConnection(SELECTOR_FOR_RESERVE).map(identity());
        final HttpExecutionStrategy strategy = requestExecutionStrategy(metaData, executionContext().executionStrategy());
        return (strategy.isMetadataReceiveOffloaded() || strategy.isDataReceiveOffloaded() ? connection.publishOn(executionContext.executor(), IoThread::currentThreadIsIoThread) : connection).shareContextOnSubscribe();
    });
}
Also used : ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy)

Aggregations

ReservedStreamingHttpConnection (io.servicetalk.http.api.ReservedStreamingHttpConnection)5 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)3 ServerContext (io.servicetalk.transport.api.ServerContext)3 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)3 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)3 AsyncCloseables (io.servicetalk.concurrent.api.AsyncCloseables)2 CompositeCloseable (io.servicetalk.concurrent.api.CompositeCloseable)2 Single (io.servicetalk.concurrent.api.Single)2 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)2 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)2 HttpExecutionStrategies.defaultStrategy (io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy)2 HttpExecutionStrategy (io.servicetalk.http.api.HttpExecutionStrategy)2 ReservedBlockingHttpConnection (io.servicetalk.http.api.ReservedBlockingHttpConnection)2 SingleAddressHttpClientBuilder (io.servicetalk.http.api.SingleAddressHttpClientBuilder)2 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)2 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)2 HostAndPort (io.servicetalk.transport.api.HostAndPort)2 InetSocketAddress (java.net.InetSocketAddress)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2