Search in sources :

Example 1 with StreamingHttpService

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

the class GrpcRouter method bind.

Single<GrpcServerContext> bind(final ServerBinder binder, final GrpcExecutionContext executionContext) {
    final CompositeCloseable closeable = AsyncCloseables.newCompositeCloseable();
    final Map<String, StreamingHttpService> allRoutes = new HashMap<>();
    populateRoutes(executionContext, allRoutes, routes, closeable, executionStrategies);
    populateRoutes(executionContext, allRoutes, streamingRoutes, closeable, executionStrategies);
    populateRoutes(executionContext, allRoutes, blockingRoutes, closeable, executionStrategies);
    populateRoutes(executionContext, allRoutes, blockingStreamingRoutes, closeable, executionStrategies);
    // TODO: Optimize to bind a specific programming model service based on routes
    return binder.bindStreaming(new StreamingHttpService() {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            final StreamingHttpService service;
            if (!POST.equals(request.method()) || (service = allRoutes.get(request.path())) == null) {
                return NOT_FOUND_SERVICE.handle(ctx, request, responseFactory);
            } else {
                return service.handle(ctx, request, responseFactory);
            }
        }

        @Override
        public Completable closeAsync() {
            return closeable.closeAsync();
        }

        @Override
        public Completable closeAsyncGracefully() {
            return closeable.closeAsyncGracefully();
        }
    }).map(httpServerContext -> new DefaultGrpcServerContext(httpServerContext, executionContext));
}
Also used : HashMap(java.util.HashMap) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) BlockingStreamingHttpService(io.servicetalk.http.api.BlockingStreamingHttpService) StreamingHttpServiceToOffloadedStreamingHttpService(io.servicetalk.http.api.StreamingHttpServiceToOffloadedStreamingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 2 with StreamingHttpService

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

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

the class HttpPredicateRouterBuilderTest method testDefaultFallback.

@Test
void testDefaultFallback() throws Exception {
    final StreamingHttpService service = new HttpPredicateRouterBuilder().buildStreaming();
    final Single<StreamingHttpResponse> responseSingle = service.handle(ctx, request, reqRespFactory);
    final StreamingHttpResponse response = responseSingle.toFuture().get();
    assert response != null;
    assertEquals(404, response.status().code());
}
Also used : StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 4 with StreamingHttpService

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

the class HttpPredicateRouterBuilderTest method testWhenMethod.

@Test
void testWhenMethod() {
    final StreamingHttpService service = new HttpPredicateRouterBuilder().whenMethod(POST).thenRouteTo(serviceA).when((ctx, req) -> true).thenRouteTo(fallbackService).buildStreaming();
    when(request.method()).thenReturn(POST);
    assertSame(responseA, service.handle(ctx, request, reqRespFactory));
    when(request.method()).thenReturn(GET);
    assertSame(fallbackResponse, service.handle(ctx, request, reqRespFactory));
}
Also used : StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Test(org.junit.jupiter.api.Test)

Example 5 with StreamingHttpService

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

the class HttpPredicateRouterBuilderTest method testCloseAsyncClosesAllServicesWhenFirstOneIsError.

@Test
void testCloseAsyncClosesAllServicesWhenFirstOneIsError() throws Exception {
    when(serviceA.closeAsync()).thenReturn(failCompletable);
    when(serviceB.closeAsync()).thenReturn(completableB);
    when(serviceC.closeAsync()).thenReturn(completableC);
    final StreamingHttpService service = new HttpPredicateRouterBuilder().whenMethod(GET).thenRouteTo(serviceA).whenMethod(POST).thenRouteTo(serviceB).when((ctx, req) -> true).thenRouteTo(serviceC).buildStreaming();
    try {
        final Completable completable = service.closeAsync();
        completable.toFuture().get();
        Assertions.fail("Expected an exception from `await`");
    } catch (final ExecutionException e) {
        assertSame(DELIBERATE_EXCEPTION, e.getCause());
    }
    verify(serviceA).closeAsync();
    verify(serviceB).closeAsync();
    verify(serviceC).closeAsync();
    failCompletable.verifyNotCancelled();
    completableB.verifyNotCancelled();
    completableC.verifyNotCancelled();
    failCompletable.verifyListenCalled();
    completableB.verifyListenCalled();
    completableC.verifyListenCalled();
}
Also used : Completable(io.servicetalk.concurrent.api.Completable) LegacyTestCompletable(io.servicetalk.concurrent.api.LegacyTestCompletable) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Aggregations

StreamingHttpService (io.servicetalk.http.api.StreamingHttpService)50 Test (org.junit.jupiter.api.Test)38 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)8 ServerContext (io.servicetalk.transport.api.ServerContext)8 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)7 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)7 HttpResponse (io.servicetalk.http.api.HttpResponse)6 HttpApiConversions.toStreamingHttpService (io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService)5 HttpExecutionStrategy (io.servicetalk.http.api.HttpExecutionStrategy)5 HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)5 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)5 StreamingHttpServiceFilter (io.servicetalk.http.api.StreamingHttpServiceFilter)5 InOrder (org.mockito.InOrder)5 Single (io.servicetalk.concurrent.api.Single)4 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)4 BlockingStreamingHttpService (io.servicetalk.http.api.BlockingStreamingHttpService)4 OK (io.servicetalk.http.api.HttpResponseStatus.OK)4 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)4 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)4 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)4