Search in sources :

Example 26 with StreamingHttpService

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

the class RequestResponseContextTest method service.

@Override
void service(final StreamingHttpService service) {
    final StreamingHttpService newService;
    assert api != null;
    switch(api) {
        case AsyncAggregated:
            newService = toStreamingHttpService((HttpService) (ctx, request, responseFactory) -> {
                HttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return succeeded(response);
            }, offloadNone()).adaptor();
            break;
        case AsyncStreaming:
            newService = (ctx, request, responseFactory) -> {
                StreamingHttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return succeeded(response);
            };
            break;
        case BlockingAggregated:
            newService = toStreamingHttpService((BlockingHttpService) (ctx, request, responseFactory) -> {
                HttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return response;
            }, offloadNone()).adaptor();
            break;
        case BlockingStreaming:
            newService = toStreamingHttpService((ctx, request, response) -> {
                transferContext(request, response);
                try (HttpPayloadWriter<Buffer> writer = response.sendMetaData()) {
                    for (Buffer chunk : request.payloadBody()) {
                        writer.write(chunk);
                    }
                }
            }, offloadNone()).adaptor();
            break;
        default:
            throw new IllegalStateException("Unknown api: " + api);
    }
    super.service(newService);
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Collections.singletonList(java.util.Collections.singletonList) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) HttpRequest(io.servicetalk.http.api.HttpRequest) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpClient(io.servicetalk.http.api.HttpClient) Matchers.hasSize(org.hamcrest.Matchers.hasSize) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Nullable(javax.annotation.Nullable) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpService(io.servicetalk.http.api.HttpService) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Single(io.servicetalk.concurrent.api.Single) HttpResponse(io.servicetalk.http.api.HttpResponse) SVC_ECHO(io.servicetalk.http.netty.TestServiceStreaming.SVC_ECHO) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) HttpRequestMetaData(io.servicetalk.http.api.HttpRequestMetaData) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) String.valueOf(java.lang.String.valueOf) ContextMap(io.servicetalk.context.api.ContextMap) BlockingHttpService(io.servicetalk.http.api.BlockingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.contains(org.hamcrest.Matchers.contains) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) Buffer(io.servicetalk.buffer.api.Buffer) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse)

Example 27 with StreamingHttpService

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

the class FlushStrategyOnServerTest method setUp.

private void setUp(final Param param) {
    this.interceptor = new OutboundWriteEventsInterceptor();
    this.headersFactory = DefaultHttpHeadersFactory.INSTANCE;
    final StreamingHttpService service = (ctx, request, responseFactory) -> {
        StreamingHttpResponse resp = responseFactory.ok();
        if (request.headers().get(USE_EMPTY_RESP_BODY) == null) {
            resp.payloadBody(from("Hello", "World"), appSerializerUtf8FixLen());
        }
        if (request.headers().get(USE_AGGREGATED_RESP) != null) {
            return resp.toResponse().map(HttpResponse::toStreamingResponse);
        }
        return succeeded(resp);
    };
    final DefaultHttpExecutionContext httpExecutionContext = new DefaultHttpExecutionContext(DEFAULT_ALLOCATOR, globalExecutionContext().ioExecutor(), EXECUTOR_RULE.executor(), param.executionStrategy);
    final ReadOnlyHttpServerConfig config = new HttpServerConfig().asReadOnly();
    final ReadOnlyTcpServerConfig tcpReadOnly = new TcpServerConfig().asReadOnly();
    try {
        serverContext = TcpServerBinder.bind(localAddress(0), tcpReadOnly, true, httpExecutionContext, null, (channel, observer) -> {
            final ConnectionObserver connectionObserver = config.tcpConfig().transportObserver().onNewConnection(channel.localAddress(), channel.remoteAddress());
            return initChannel(channel, httpExecutionContext, config, new TcpServerChannelInitializer(tcpReadOnly, connectionObserver).andThen(channel1 -> channel1.pipeline().addLast(interceptor)), service, true, connectionObserver);
        }, connection -> connection.process(true)).map(delegate -> new NettyHttpServerContext(delegate, service, httpExecutionContext)).toFuture().get();
    } catch (Exception e) {
        fail(e);
    }
    client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).protocols(h1Default()).buildBlocking();
}
Also used : DefaultHttpExecutionContext(io.servicetalk.http.api.DefaultHttpExecutionContext) TcpServerChannelInitializer(io.servicetalk.tcp.netty.internal.TcpServerChannelInitializer) TcpServerConfig(io.servicetalk.tcp.netty.internal.TcpServerConfig) ReadOnlyTcpServerConfig(io.servicetalk.tcp.netty.internal.ReadOnlyTcpServerConfig) ChannelPromise(io.netty.channel.ChannelPromise) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) Executor(io.servicetalk.concurrent.api.Executor) GlobalExecutionContext.globalExecutionContext(io.servicetalk.transport.netty.internal.GlobalExecutionContext.globalExecutionContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ExecutorExtension(io.servicetalk.concurrent.api.ExecutorExtension) HttpResponse(io.servicetalk.http.api.HttpResponse) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) BlockingQueue(java.util.concurrent.BlockingQueue) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) HttpExecutionStrategies.customStrategyBuilder(io.servicetalk.http.api.HttpExecutionStrategies.customStrategyBuilder) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Assertions.fail(org.junit.jupiter.api.Assertions.fail) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) StreamingHttpRequests.newTransportRequest(io.servicetalk.http.api.StreamingHttpRequests.newTransportRequest) HttpHeaders(io.servicetalk.http.api.HttpHeaders) EnumSource(org.junit.jupiter.params.provider.EnumSource) NettyHttpServer.initChannel(io.servicetalk.http.netty.NettyHttpServer.initChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) GET(io.servicetalk.http.api.HttpRequestMethod.GET) TcpServerBinder(io.servicetalk.tcp.netty.internal.TcpServerBinder) NettyHttpServerContext(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerContext) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) HttpHeadersFactory(io.servicetalk.http.api.HttpHeadersFactory) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) NettyHttpServerContext(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerContext) TcpServerChannelInitializer(io.servicetalk.tcp.netty.internal.TcpServerChannelInitializer) DefaultHttpExecutionContext(io.servicetalk.http.api.DefaultHttpExecutionContext) TcpServerConfig(io.servicetalk.tcp.netty.internal.TcpServerConfig) ReadOnlyTcpServerConfig(io.servicetalk.tcp.netty.internal.ReadOnlyTcpServerConfig) ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) ReadOnlyTcpServerConfig(io.servicetalk.tcp.netty.internal.ReadOnlyTcpServerConfig) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 28 with StreamingHttpService

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

the class GrpcRouter method populateRoutes.

private static void populateRoutes(final GrpcExecutionContext executionContext, final Map<String, StreamingHttpService> allRoutes, final Map<String, RouteProvider> routes, final CompositeCloseable closeable, final Map<String, GrpcExecutionStrategy> executionStrategies) {
    for (Map.Entry<String, RouteProvider> entry : routes.entrySet()) {
        final String path = entry.getKey();
        final ServiceAdapterHolder adapterHolder = entry.getValue().buildRoute(executionContext);
        final StreamingHttpService route = closeable.append(adapterHolder.adaptor());
        final GrpcExecutionStrategy routeStrategy = executionStrategies.getOrDefault(path, null);
        final HttpExecutionStrategy missing = null == routeStrategy ? HttpExecutionStrategies.offloadNever() : executionContext.executionStrategy().missing(routeStrategy);
        verifyNoOverrides(allRoutes.put(path, null != routeStrategy && missing.isRequestResponseOffloaded() ? StreamingHttpServiceToOffloadedStreamingHttpService.offloadService(adapterHolder.serviceInvocationStrategy(), executionContext.executor(), IoThreadFactory.IoThread::currentThreadIsIoThread, route) : route), path, emptyMap());
        LOGGER.debug("route strategy for path={} : ctx={} route={} → using={}", path, executionContext.executionStrategy(), routeStrategy, missing);
    }
}
Also used : ServiceAdapterHolder(io.servicetalk.http.api.HttpApiConversions.ServiceAdapterHolder) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) 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) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) Map(java.util.Map) HashMap(java.util.HashMap) Collections.emptyMap(java.util.Collections.emptyMap) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap)

Example 29 with StreamingHttpService

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

the class DefaultFallbackServiceTest method testDefaultFallbackService.

@Test
void testDefaultFallbackService() throws Exception {
    final StreamingHttpService fixture = DefaultFallbackServiceStreaming.instance();
    final Single<StreamingHttpResponse> responseSingle = fixture.handle(ctx, request, reqRespFactory);
    final StreamingHttpResponse response = responseSingle.toFuture().get();
    assert response != null;
    assertEquals(HTTP_1_1, response.version());
    assertEquals(NOT_FOUND, response.status());
    assertEquals(ZERO, response.headers().get(CONTENT_LENGTH));
    assertEquals(TEXT_PLAIN_UTF_8, response.headers().get(CONTENT_TYPE));
}
Also used : StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 30 with StreamingHttpService

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

the class HttpPredicateRouterBuilderHeaderTest method testWhenHeaderIsPresent.

@Test
void testWhenHeaderIsPresent() {
    final StreamingHttpService service = new HttpPredicateRouterBuilder().whenHeader("host").isPresent().thenRouteTo(serviceA).when((ctx, req) -> true).thenRouteTo(fallbackService).buildStreaming();
    when(headers.valuesIterator("host")).then(answerIteratorOf("localhost"));
    assertSame(responseA, service.handle(ctx, request, reqRespFactory));
    when(headers.valuesIterator("host")).thenReturn(emptyIterator());
    assertSame(fallbackResponse, service.handle(ctx, request, reqRespFactory));
}
Also used : StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) 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