Search in sources :

Example 1 with StreamingHttpServiceFilterFactory

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

the class ErrorHandlingTest method setUp.

private void setUp(TestMode testMode, GrpcExecutionStrategy serverStrategy, GrpcExecutionStrategy clientStrategy) throws Exception {
    this.testMode = testMode;
    cannedResponse = TestResponse.newBuilder().setMessage("foo").build();
    ServiceFactory serviceFactory;
    StreamingHttpServiceFilterFactory serviceFilterFactory = IDENTITY_FILTER;
    StreamingHttpClientFilterFactory clientFilterFactory = IDENTITY_CLIENT_FILTER;
    Publisher<TestRequest> requestPublisher = from(TestRequest.newBuilder().build());
    switch(testMode) {
        case HttpClientFilterThrows:
            clientFilterFactory = new ErrorProducingClientFilter(true, DELIBERATE_EXCEPTION);
            serviceFactory = setupForSuccess();
            break;
        case HttpClientFilterThrowsGrpcException:
            clientFilterFactory = new ErrorProducingClientFilter(true, cannedException);
            serviceFactory = setupForSuccess();
            break;
        case HttpClientFilterEmitsError:
            clientFilterFactory = new ErrorProducingClientFilter(false, DELIBERATE_EXCEPTION);
            serviceFactory = setupForSuccess();
            break;
        case HttpClientFilterEmitsGrpcException:
            clientFilterFactory = new ErrorProducingClientFilter(false, cannedException);
            serviceFactory = setupForSuccess();
            break;
        case HttpFilterThrows:
            serviceFilterFactory = new ErrorProducingSvcFilter(true, DELIBERATE_EXCEPTION);
            serviceFactory = setupForSuccess();
            break;
        case HttpFilterThrowsGrpcException:
            serviceFilterFactory = new ErrorProducingSvcFilter(true, cannedException);
            serviceFactory = setupForSuccess();
            break;
        case HttpFilterEmitsError:
            serviceFilterFactory = new ErrorProducingSvcFilter(false, DELIBERATE_EXCEPTION);
            serviceFactory = setupForSuccess();
            break;
        case HttpFilterEmitsGrpcException:
            serviceFilterFactory = new ErrorProducingSvcFilter(false, cannedException);
            serviceFactory = setupForSuccess();
            break;
        case ServiceThrows:
            serviceFactory = setupForServiceThrows(DELIBERATE_EXCEPTION);
            break;
        case ServiceThrowsGrpcException:
            serviceFactory = setupForServiceThrows(cannedException);
            break;
        case ServiceOperatorThrows:
            serviceFactory = setupForServiceOperatorThrows(DELIBERATE_EXCEPTION);
            break;
        case ServiceOperatorThrowsGrpcException:
            serviceFactory = setupForServiceOperatorThrows(cannedException);
            break;
        case ServiceSecondOperatorThrowsGrpcException:
            serviceFactory = setupForServiceSecondOperatorThrows(cannedException);
            requestPublisher = from(TestRequest.newBuilder().build(), TestRequest.newBuilder().setName(REQ_THROW_NAME).build());
            break;
        case ServiceEmitsError:
            serviceFactory = setupForServiceEmitsError(DELIBERATE_EXCEPTION);
            break;
        case ServiceEmitsGrpcException:
            serviceFactory = setupForServiceEmitsError(cannedException);
            break;
        case ServiceEmitsDataThenError:
            serviceFactory = setupForServiceEmitsDataThenError(DELIBERATE_EXCEPTION);
            break;
        case ServiceEmitsDataThenGrpcException:
            serviceFactory = setupForServiceEmitsDataThenError(cannedException);
            break;
        case BlockingServiceThrows:
            serviceFactory = setupForBlockingServiceThrows(DELIBERATE_EXCEPTION);
            break;
        case BlockingServiceThrowsGrpcException:
            serviceFactory = setupForBlockingServiceThrows(cannedException);
            break;
        case BlockingServiceWritesThenThrows:
            serviceFactory = setupForBlockingServiceWritesThenThrows(DELIBERATE_EXCEPTION);
            break;
        case BlockingServiceWritesThenThrowsGrpcException:
            serviceFactory = setupForBlockingServiceWritesThenThrows(cannedException);
            break;
        default:
            throw new IllegalArgumentException("Unknown mode: " + testMode);
    }
    this.requestPublisher = requestPublisher;
    final StreamingHttpServiceFilterFactory filterFactory = serviceFilterFactory;
    serverContext = GrpcServers.forAddress(localAddress(0)).initializeHttp(builder -> builder.appendServiceFilter(filterFactory).executionStrategy(serverStrategy)).listenAndAwait(serviceFactory);
    final StreamingHttpClientFilterFactory pickedClientFilterFactory = clientFilterFactory;
    GrpcClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = GrpcClients.forAddress(serverHostAndPort(serverContext)).initializeHttp(builder -> builder.appendClientFilter(pickedClientFilterFactory).executionStrategy(clientStrategy));
    client = clientBuilder.build(new ClientFactory());
    blockingClient = clientBuilder.buildBlocking(new ClientFactory());
}
Also used : StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServiceFactory(io.servicetalk.grpc.netty.TesterProto.Tester.ServiceFactory) InetSocketAddress(java.net.InetSocketAddress) ClientFactory(io.servicetalk.grpc.netty.TesterProto.Tester.ClientFactory) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) TestRequest(io.servicetalk.grpc.netty.TesterProto.TestRequest)

Example 2 with StreamingHttpServiceFilterFactory

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

the class H2PriorKnowledgeFeatureParityTest method bindHttpEchoServer.

private InetSocketAddress bindHttpEchoServer(@Nullable StreamingHttpServiceFilterFactory filterFactory, @Nullable CountDownLatch connectionOnClosingLatch) throws Exception {
    HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0)).protocols(h2PriorKnowledge ? h2Default() : h1Default());
    if (filterFactory != null) {
        serverBuilder.appendServiceFilter(filterFactory);
    }
    if (connectionOnClosingLatch != null) {
        serverBuilder.appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

            @Override
            public Completable accept(final ConnectionContext context) {
                ((NettyConnectionContext) context).onClosing().whenFinally(connectionOnClosingLatch::countDown).subscribe();
                return completed();
            }
        });
    }
    h1ServerContext = serverBuilder.listenStreaming((ctx, request, responseFactory) -> {
        StreamingHttpResponse resp;
        if (request.headers().contains(EXPECT, CONTINUE)) {
            if (request.headers().contains(EXPECT_FAIL_HEADER)) {
                return succeeded(responseFactory.expectationFailed());
            } else {
                resp = responseFactory.continueResponse();
            }
        } else {
            resp = responseFactory.ok();
        }
        resp = resp.transformMessageBody(pub -> pub.ignoreElements().merge(request.messageBody())).transform(new StatelessTrailersTransformer<>());
        CharSequence contentType = request.headers().get(CONTENT_TYPE);
        if (contentType != null) {
            resp.setHeader(CONTENT_TYPE, contentType);
        }
        CharSequence contentLength = request.headers().get(CONTENT_LENGTH);
        if (contentLength != null) {
            resp.setHeader(CONTENT_LENGTH, contentLength);
        }
        CharSequence transferEncoding = request.headers().get(TRANSFER_ENCODING);
        if (transferEncoding != null) {
            resp.setHeader(TRANSFER_ENCODING, transferEncoding);
        }
        resp.headers().set(COOKIE, request.headers().valuesIterator(COOKIE));
        return succeeded(resp);
    }).toFuture().get();
    return (InetSocketAddress) h1ServerContext.listenAddress();
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) UnaryOperator.identity(java.util.function.UnaryOperator.identity) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) SingleSource(io.servicetalk.concurrent.SingleSource) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) UnaryOperator(java.util.function.UnaryOperator) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) Disabled(org.junit.jupiter.api.Disabled) Matchers.hasItems(org.hamcrest.Matchers.hasItems) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) H2StreamResetException(io.servicetalk.http.netty.NettyHttp2ExceptionUtils.H2StreamResetException) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) HttpRequest(io.servicetalk.http.api.HttpRequest) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Matchers.nullValue(org.hamcrest.Matchers.nullValue) HttpCookiePair(io.servicetalk.http.api.HttpCookiePair) EXPECT(io.servicetalk.http.api.HttpHeaderNames.EXPECT) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) PrintWriter(java.io.PrintWriter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) DefaultHttp2SettingsFrame(io.netty.handler.codec.http2.DefaultHttp2SettingsFrame) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) HttpResponse(io.servicetalk.http.api.HttpResponse) Http2SettingsAckFrame(io.netty.handler.codec.http2.Http2SettingsAckFrame) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) POST(io.servicetalk.http.api.HttpRequestMethod.POST) BlockingQueue(java.util.concurrent.BlockingQueue) ChannelPipeline(io.netty.channel.ChannelPipeline) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) Assertions.assertNotSame(org.junit.jupiter.api.Assertions.assertNotSame) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HttpSetCookie(io.servicetalk.http.api.HttpSetCookie) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) COOKIE(io.servicetalk.http.api.HttpHeaderNames.COOKIE) Matchers.is(org.hamcrest.Matchers.is) CONTENT_TYPE(io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Processor(io.servicetalk.concurrent.PublisherSource.Processor) BuilderUtils.serverChannel(io.servicetalk.transport.netty.internal.BuilderUtils.serverChannel) TRAILER(io.netty.handler.codec.http.HttpHeaderNames.TRAILER) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) HttpHeaders(io.servicetalk.http.api.HttpHeaders) ConsumableEvent(io.servicetalk.client.api.ConsumableEvent) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) MAX_CONCURRENCY(io.servicetalk.http.api.HttpEventKey.MAX_CONCURRENCY) HeaderUtils.isTransferEncodingChunked(io.servicetalk.http.api.HeaderUtils.isTransferEncodingChunked) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Processors(io.servicetalk.concurrent.api.Processors) BiConsumer(java.util.function.BiConsumer) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) SMALLEST_MAX_CONCURRENT_STREAMS(io.netty.handler.codec.http2.Http2CodecUtil.SMALLEST_MAX_CONCURRENT_STREAMS) DEFAULT(io.servicetalk.http.netty.HttpTestExecutionStrategy.DEFAULT) Single(io.servicetalk.concurrent.api.Single) StringWriter(java.io.StringWriter) Completable(io.servicetalk.concurrent.api.Completable) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) IOException(java.io.IOException) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) OK(io.servicetalk.http.api.HttpResponseStatus.OK) GET(io.servicetalk.http.api.HttpRequestMethod.GET) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) Matchers.emptyString(org.hamcrest.Matchers.emptyString) Http2FrameCodecBuilder(io.netty.handler.codec.http2.Http2FrameCodecBuilder) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2DataFrame(io.netty.handler.codec.http2.Http2DataFrame) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) PublisherSource(io.servicetalk.concurrent.PublisherSource) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpEventKey(io.servicetalk.http.api.HttpEventKey) List(java.util.List) ContextMap(io.servicetalk.context.api.ContextMap) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Writer(java.io.Writer) Queue(java.util.Queue) CONTINUE(io.servicetalk.http.api.HttpHeaderValues.CONTINUE) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) Http2Exception(io.servicetalk.http.api.Http2Exception) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpProtocolConfigs.h2Default(io.servicetalk.http.netty.HttpProtocolConfigs.h2Default) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) ServerContext(io.servicetalk.transport.api.ServerContext) Iterator(java.util.Iterator) EXPECTATION_FAILED(io.servicetalk.http.api.HttpResponseStatus.EXPECTATION_FAILED) NettyIoExecutors.createIoExecutor(io.servicetalk.transport.netty.internal.NettyIoExecutors.createIoExecutor) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Processors.newPublisherProcessor(io.servicetalk.concurrent.api.Processors.newPublisherProcessor) Consumer(java.util.function.Consumer) Matchers.emptyIterable(org.hamcrest.Matchers.emptyIterable) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) NO_OFFLOAD(io.servicetalk.http.netty.HttpTestExecutionStrategy.NO_OFFLOAD) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandler(io.netty.channel.ChannelHandler) SET_COOKIE(io.servicetalk.http.api.HttpHeaderNames.SET_COOKIE) DefaultHttpCookiePair(io.servicetalk.http.api.DefaultHttpCookiePair) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Completable(io.servicetalk.concurrent.api.Completable) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 3 with StreamingHttpServiceFilterFactory

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

the class AbstractHttpServiceAsyncContextTest method filterFactory.

private StreamingHttpServiceFilterFactory filterFactory(final boolean useImmediate, final boolean asyncFilter, final Queue<Throwable> errorQueue) {
    return service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory factory) {
            return asyncFilter ? defer(() -> doHandle(ctx, request, factory).shareContextOnSubscribe()) : doHandle(ctx, request, factory);
        }

        private Single<StreamingHttpResponse> doHandle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory factory) {
            if (useImmediate && !currentThread().getName().startsWith(IO_THREAD_PREFIX)) {
                // verify that if we expect to be offloaded, that we actually are
                return succeeded(factory.internalServerError());
            }
            CharSequence requestId = request.headers().getAndRemove(REQUEST_ID_HEADER);
            if (requestId != null) {
                AsyncContext.put(K1, requestId);
            }
            final StreamingHttpRequest filteredRequest = request.transformMessageBody(pub -> pub.afterSubscriber(assertAsyncContextSubscriber(requestId, errorQueue)));
            return delegate().handle(ctx, filteredRequest, factory).map(resp -> {
                assertAsyncContext(requestId, errorQueue);
                return resp.transformMessageBody(pub -> pub.afterSubscriber(assertAsyncContextSubscriber(requestId, errorQueue)));
            });
        }
    };
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) Thread.currentThread(java.lang.Thread.currentThread) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) CyclicBarrier(java.util.concurrent.CyclicBarrier) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Matchers.empty(org.hamcrest.Matchers.empty) ServerContext(io.servicetalk.transport.api.ServerContext) HttpProtocolConfigs.h1(io.servicetalk.http.netty.HttpProtocolConfigs.h1) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single.defer(io.servicetalk.concurrent.api.Single.defer) PublisherSource(io.servicetalk.concurrent.PublisherSource) Single(io.servicetalk.concurrent.api.Single) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) CountDownLatch(java.util.concurrent.CountDownLatch) ContextMap(io.servicetalk.context.api.ContextMap) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Queue(java.util.Queue) HostAndPort(io.servicetalk.transport.api.HostAndPort) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 4 with StreamingHttpServiceFilterFactory

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

the class DefaultHttpServerBuilder method listenForService.

/**
 * Starts this server and returns the {@link HttpServerContext} after the server has been successfully started.
 * <p>
 * If the underlying protocol (e.g. TCP) supports it this should result in a socket bind/listen on {@code address}.
 * <p>/p>
 * The execution path for a request will be offloaded from the IO thread as required to ensure safety. The
 * <dl>
 *     <dt>read side</dt>
 *     <dd>IO thread → request → non-offload filters → offload filters → raw service</dd>
 *     <dt>subscribe/request side</dt>
 *     <dd>IO thread → subscribe/request/cancel → non-offload filters → offload filters → raw service</dd>
 * </dl>
 *
 * @param rawService {@link StreamingHttpService} to use for the server.
 * @param strategy the {@link HttpExecutionStrategy} to use for the service.
 * @return A {@link Single} that completes when the server is successfully started or terminates with an error if
 * the server could not be started.
 */
private Single<HttpServerContext> listenForService(final StreamingHttpService rawService, final HttpExecutionStrategy strategy) {
    InfluencerConnectionAcceptor connectionAcceptor = connectionAcceptorFactory == null ? null : InfluencerConnectionAcceptor.withStrategy(connectionAcceptorFactory.create(ACCEPT_ALL), connectionAcceptorFactory.requiredOffloads());
    final StreamingHttpService filteredService;
    final HttpExecutionContext executionContext;
    if (noOffloadServiceFilters.isEmpty()) {
        filteredService = serviceFilters.isEmpty() ? rawService : buildService(serviceFilters.stream(), rawService);
        executionContext = buildExecutionContext(strategy);
    } else {
        Stream<StreamingHttpServiceFilterFactory> nonOffloadingFilters = noOffloadServiceFilters.stream();
        if (strategy.isRequestResponseOffloaded()) {
            executionContext = buildExecutionContext(REQRESP_OFFLOADS.missing(strategy));
            BooleanSupplier shouldOffload = executionContext.ioExecutor().shouldOffloadSupplier();
            // We are going to have to offload, even if just to the raw service
            OffloadingFilter offloadingFilter = new OffloadingFilter(strategy, buildFactory(serviceFilters), shouldOffload);
            nonOffloadingFilters = Stream.concat(nonOffloadingFilters, Stream.of(offloadingFilter));
        } else {
            // All the filters can be appended.
            nonOffloadingFilters = Stream.concat(nonOffloadingFilters, serviceFilters.stream());
            executionContext = buildExecutionContext(strategy);
        }
        filteredService = buildService(nonOffloadingFilters, rawService);
    }
    return doBind(executionContext, connectionAcceptor, filteredService).afterOnSuccess(serverContext -> LOGGER.debug("Server for address {} uses strategy {}", serverContext.listenAddress(), strategy));
}
Also used : HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) InfluencerConnectionAcceptor(io.servicetalk.transport.netty.internal.InfluencerConnectionAcceptor) BlockingStreamingHttpService(io.servicetalk.http.api.BlockingStreamingHttpService) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) BooleanSupplier(java.util.function.BooleanSupplier)

Example 5 with StreamingHttpServiceFilterFactory

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

the class ServiceTalkContentCodingTest method newServiceTalkServer.

private ServerContext newServiceTalkServer(final Scenario scenario, final Queue<Throwable> errors) throws Exception {
    HttpServerBuilder httpServerBuilder = HttpServers.forAddress(localAddress(0));
    StreamingHttpService service = (ctx, request, responseFactory) -> succeeded(buildResponse(responseFactory));
    StreamingHttpServiceFilterFactory filterFactory = REQ_FILTER.apply(scenario, errors);
    return httpServerBuilder.executionStrategy(defaultStrategy()).protocols(scenario.protocol.config).appendServiceFilter(new ContentCodingHttpServiceFilter(scenario.serverSupported, scenario.serverSupported)).appendServiceFilter(filterFactory).listenStreamingAndAwait(service);
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) ContentCodec(io.servicetalk.encoding.api.ContentCodec) BiFunction(java.util.function.BiFunction) Collections.disjoint(java.util.Collections.disjoint) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) Collections.singletonList(java.util.Collections.singletonList) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HeaderUtils.encodingFor(io.servicetalk.encoding.api.internal.HeaderUtils.encodingFor) ContentCodingHttpServiceFilter(io.servicetalk.http.api.ContentCodingHttpServiceFilter) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) List(java.util.List) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) HttpSerializationProviders.textDeserializer(io.servicetalk.http.api.HttpSerializationProviders.textDeserializer) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Queue(java.util.Queue) Arrays.stream(java.util.Arrays.stream) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Identity.identity(io.servicetalk.encoding.api.Identity.identity) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) CharSequences.contentEquals(io.servicetalk.buffer.api.CharSequences.contentEquals) HttpSerializationProviders.textSerializer(io.servicetalk.http.api.HttpSerializationProviders.textSerializer) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) UNSUPPORTED_MEDIA_TYPE(io.servicetalk.http.api.HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ContentCodingHttpRequesterFilter(io.servicetalk.http.api.ContentCodingHttpRequesterFilter) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) ACCEPT_ENCODING(io.servicetalk.http.api.HttpHeaderNames.ACCEPT_ENCODING) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Collectors.toList(java.util.stream.Collectors.toList) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Single.failed(io.servicetalk.concurrent.api.Single.failed) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) CONTENT_ENCODING(io.servicetalk.http.api.HttpHeaderNames.CONTENT_ENCODING) HostAndPort(io.servicetalk.transport.api.HostAndPort) ContentCodingHttpServiceFilter(io.servicetalk.http.api.ContentCodingHttpServiceFilter) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory)

Aggregations

StreamingHttpServiceFilterFactory (io.servicetalk.http.api.StreamingHttpServiceFilterFactory)5 HostAndPort (io.servicetalk.transport.api.HostAndPort)4 Single (io.servicetalk.concurrent.api.Single)3 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)3 HttpServerBuilder (io.servicetalk.http.api.HttpServerBuilder)3 HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)3 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)3 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)3 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)3 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)3 StreamingHttpServiceFilter (io.servicetalk.http.api.StreamingHttpServiceFilter)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 InetSocketAddress (java.net.InetSocketAddress)3 PublisherSource (io.servicetalk.concurrent.PublisherSource)2 AsyncContext (io.servicetalk.concurrent.api.AsyncContext)2 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)2 ContextMap (io.servicetalk.context.api.ContextMap)2 Key.newKey (io.servicetalk.context.api.ContextMap.Key.newKey)2