Search in sources :

Example 16 with HttpServiceContext

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

the class RequestResponseContextTest method setUp.

void setUp(Api api) {
    this.api = api;
    connectionFilterFactory(connection -> new StreamingHttpConnectionFilter(connection) {

        @Override
        public Single<StreamingHttpResponse> request(StreamingHttpRequest request) {
            final List<String> requestCtxValue = request.context().get(CLIENT_REQUEST_KEY);
            try {
                assertThat(requestCtxValue, is(notNullValue()));
                assertThat(requestCtxValue, hasSize(1));
                request.addHeader(CONTEXT_HEADER, requestCtxValue.get(0));
            } catch (Throwable t) {
                asyncError.add(t);
            }
            return delegate().request(request).map(response -> {
                response.context().put(CLIENT_RESPONSE_KEY, valueOf(response.headers().get(CONTEXT_HEADER)));
                return response;
            });
        }
    });
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(HttpServiceContext ctx, StreamingHttpRequest request, StreamingHttpResponseFactory responseFactory) {
            CharSequence requestCtxValue = request.headers().get(CONTEXT_HEADER);
            try {
                assertThat(requestCtxValue, is(notNullValue()));
                request.context().put(SERVER_REQUEST_KEY, singletonList(requestCtxValue.toString()));
            } catch (Throwable t) {
                asyncError.add(t);
            }
            return delegate().handle(ctx, request, responseFactory).map(response -> {
                response.headers().add(CONTEXT_HEADER, valueOf(response.context().get(SERVER_RESPONSE_KEY)));
                return response;
            });
        }
    });
    setUp(CACHED, CACHED_SERVER);
}
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) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest)

Example 17 with HttpServiceContext

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

the class HttpLifecycleObserverTest method testClientCancelsRequestBeforeResponse.

@ParameterizedTest(name = "{displayName} [{index}] protocol={0}")
@EnumSource(HttpProtocol.class)
void testClientCancelsRequestBeforeResponse(HttpProtocol protocol) throws Exception {
    CountDownLatch requestReceived = new CountDownLatch(1);
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(HttpServiceContext ctx, StreamingHttpRequest request, StreamingHttpResponseFactory responseFactory) {
            return delegate().handle(ctx, request.transformMessageBody(mb -> mb.afterOnNext(__ -> requestReceived.countDown())), responseFactory);
        }
    });
    setUp(protocol);
    StreamingHttpClient client = streamingHttpClient();
    Future<StreamingHttpResponse> responseFuture = client.request(client.post(SVC_NEVER).payloadBody(Publisher.from(CONTENT.duplicate()).concat(Publisher.never()))).toFuture();
    requestReceived.await();
    responseFuture.cancel(true);
    bothTerminate.await();
    verify(serverExchangeObserver, await()).onExchangeFinally();
    clientInOrder.verify(clientLifecycleObserver).onNewExchange();
    clientInOrder.verify(clientExchangeObserver).onRequest(any(StreamingHttpRequest.class));
    clientInOrder.verify(clientExchangeObserver).onConnectionSelected(any(ConnectionInfo.class));
    clientInOrder.verify(clientExchangeObserver).onResponseCancel();
    clientRequestInOrder.verify(clientRequestObserver).onRequestDataRequested(anyLong());
    clientRequestInOrder.verify(clientRequestObserver).onRequestData(any(Buffer.class));
    clientRequestInOrder.verify(clientRequestObserver).onRequestCancel();
    clientInOrder.verify(clientExchangeObserver).onExchangeFinally();
    verifyNoMoreInteractions(clientLifecycleObserver, clientExchangeObserver, clientRequestObserver);
    verifyNoInteractions(clientResponseObserver);
    serverInOrder.verify(serverLifecycleObserver).onNewExchange();
    serverInOrder.verify(serverExchangeObserver).onConnectionSelected(any(ConnectionInfo.class));
    serverInOrder.verify(serverExchangeObserver).onRequest(any(StreamingHttpRequest.class));
    serverRequestInOrder.verify(serverRequestObserver, atLeastOnce()).onRequestDataRequested(anyLong());
    serverRequestInOrder.verify(serverRequestObserver).onRequestData(any(Buffer.class));
    serverRequestInOrder.verify(serverRequestObserver).onRequestError(any(IOException.class));
    // because of offloading, cancel from the IO-thread may race with an error propagated through request publisher:
    verify(serverExchangeObserver, atMostOnce()).onResponseCancel();
    verify(serverExchangeObserver, atMostOnce()).onResponse(any(StreamingHttpResponse.class));
    verify(serverResponseObserver, atMostOnce()).onResponseDataRequested(anyLong());
    verify(serverResponseObserver, atMostOnce()).onResponseComplete();
    serverInOrder.verify(serverExchangeObserver).onExchangeFinally();
    verifyNoMoreInteractions(serverLifecycleObserver, serverExchangeObserver, serverRequestObserver, serverResponseObserver);
}
Also used : HttpLifecycleObserver(io.servicetalk.http.api.HttpLifecycleObserver) HttpLifecycleObservers.logging(io.servicetalk.http.utils.HttpLifecycleObservers.logging) ConnectionInfo(io.servicetalk.transport.api.ConnectionInfo) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Future(java.util.concurrent.Future) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Mockito.doAnswer(org.mockito.Mockito.doAnswer) HttpRequestObserver(io.servicetalk.http.api.HttpLifecycleObserver.HttpRequestObserver) HttpTransportObserverTest.await(io.servicetalk.http.netty.HttpTransportObserverTest.await) Collection(java.util.Collection) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) SVC_ECHO(io.servicetalk.http.netty.TestServiceStreaming.SVC_ECHO) HttpExchangeObserver(io.servicetalk.http.api.HttpLifecycleObserver.HttpExchangeObserver) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Mockito.atMostOnce(org.mockito.Mockito.atMostOnce) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) SVC_THROW_ERROR(io.servicetalk.http.netty.TestServiceStreaming.SVC_THROW_ERROR) Buffer(io.servicetalk.buffer.api.Buffer) SVC_NEVER(io.servicetalk.http.netty.TestServiceStreaming.SVC_NEVER) Mockito.inOrder(org.mockito.Mockito.inOrder) DEFAULT_RO_ALLOCATOR(io.servicetalk.buffer.api.ReadOnlyBufferAllocators.DEFAULT_RO_ALLOCATOR) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) SVC_ERROR_DURING_READ(io.servicetalk.http.netty.TestServiceStreaming.SVC_ERROR_DURING_READ) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) Http2Exception(io.servicetalk.http.api.Http2Exception) HttpHeaders(io.servicetalk.http.api.HttpHeaders) EnumSource(org.junit.jupiter.params.provider.EnumSource) HttpResponseObserver(io.servicetalk.http.api.HttpLifecycleObserver.HttpResponseObserver) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) SVC_NO_CONTENT(io.servicetalk.http.netty.TestServiceStreaming.SVC_NO_CONTENT) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) InOrder(org.mockito.InOrder) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) ClosedChannelException(java.nio.channels.ClosedChannelException) Single(io.servicetalk.concurrent.api.Single) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) HttpLifecycleObservers.combine(io.servicetalk.http.utils.HttpLifecycleObservers.combine) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) OK(io.servicetalk.http.api.HttpResponseStatus.OK) SVC_SINGLE_ERROR(io.servicetalk.http.netty.TestServiceStreaming.SVC_SINGLE_ERROR) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Mockito.never(org.mockito.Mockito.never) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Single.failed(io.servicetalk.concurrent.api.Single.failed) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) ConnectionInfo(io.servicetalk.transport.api.ConnectionInfo) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 18 with HttpServiceContext

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

the class TrailersOnlyErrorTest method testServiceFilterThrows.

@Test
void testServiceFilterThrows() throws Exception {
    final BlockingQueue<Throwable> asyncErrors = new LinkedBlockingDeque<>();
    final TesterService service = mockTesterService();
    final GrpcServerBuilder serverBuilder = GrpcServers.forAddress(localAddress(0)).initializeHttp(builder -> builder.appendServiceFilter(svc -> new StreamingHttpServiceFilter(svc) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            throw DELIBERATE_EXCEPTION;
        }
    }));
    try (ServerContext serverContext = serverBuilder.listenAndAwait(new Tester.ServiceFactory(service))) {
        final GrpcClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = GrpcClients.forAddress(serverHostAndPort(serverContext)).initializeHttp(builder -> builder.appendClientFilter(__ -> true, setupResponseVerifierFilter(asyncErrors)));
        try (TesterClient client = clientBuilder.build(new Tester.ClientFactory())) {
            verifyException(client.test(TestRequest.newBuilder().build()).toFuture(), UNKNOWN);
            assertNoAsyncErrors(asyncErrors);
            verifyException(client.testRequestStream(Publisher.from(TestRequest.newBuilder().build())).toFuture(), UNKNOWN);
            assertNoAsyncErrors(asyncErrors);
            verifyException(client.testResponseStream(TestRequest.newBuilder().build()).toFuture(), UNKNOWN);
            assertNoAsyncErrors(asyncErrors);
            verifyException(client.testBiDiStream(from(TestRequest.newBuilder().build()).concat(never())).toFuture(), UNKNOWN);
            assertNoAsyncErrors(asyncErrors);
            verifyException(client.testBiDiStream(from(TestRequest.newBuilder().build())).toFuture(), UNKNOWN);
            assertNoAsyncErrors(asyncErrors);
        }
    }
}
Also used : GrpcServerBuilder(io.servicetalk.grpc.api.GrpcServerBuilder) TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) UNKNOWN(io.servicetalk.grpc.api.GrpcStatusCode.UNKNOWN) GrpcStatusCode(io.servicetalk.grpc.api.GrpcStatusCode) HelloRequest(io.grpc.examples.helloworld.HelloRequest) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) GreeterClient(io.grpc.examples.helloworld.Greeter.GreeterClient) GrpcStatusException(io.servicetalk.grpc.api.GrpcStatusException) Future(java.util.concurrent.Future) UNIMPLEMENTED(io.servicetalk.grpc.api.GrpcStatusCode.UNIMPLEMENTED) TesterClient(io.servicetalk.grpc.netty.TesterProto.Tester.TesterClient) Greeter(io.grpc.examples.helloworld.Greeter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) BlockingQueue(java.util.concurrent.BlockingQueue) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) Matchers.equalTo(org.hamcrest.Matchers.equalTo) GrpcClientBuilder(io.servicetalk.grpc.api.GrpcClientBuilder) Mockito.mock(org.mockito.Mockito.mock) Publisher.never(io.servicetalk.concurrent.api.Publisher.never) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) GrpcServerBuilder(io.servicetalk.grpc.api.GrpcServerBuilder) 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) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) TesterService(io.servicetalk.grpc.netty.TesterProto.Tester.TesterService) TestRequest(io.servicetalk.grpc.netty.TesterProto.TestRequest) Mockito.when(org.mockito.Mockito.when) ExecutionException(java.util.concurrent.ExecutionException) GRPC_STATUS(io.servicetalk.grpc.api.GrpcHeaderNames.GRPC_STATUS) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) Tester(io.servicetalk.grpc.netty.TesterProto.Tester) HostAndPort(io.servicetalk.transport.api.HostAndPort) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Tester(io.servicetalk.grpc.netty.TesterProto.Tester) InetSocketAddress(java.net.InetSocketAddress) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) TesterService(io.servicetalk.grpc.netty.TesterProto.Tester.TesterService) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) TesterClient(io.servicetalk.grpc.netty.TesterProto.Tester.TesterClient) ServerContext(io.servicetalk.transport.api.ServerContext) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 19 with HttpServiceContext

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

the class ServiceTalkContentEncodingTest method runTest.

@Override
protected void runTest(final HttpProtocol protocol, final Encoder clientEncoding, final Decoders clientDecoder, final Encoders serverEncoder, final Decoders serverDecoder, boolean valid) throws Throwable {
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).protocols(protocol.config).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            return delegate().handle(ctx, request, responseFactory).map(resp -> {
                // content encoding should be stripped by the time the decoding is done.
                assertThat(resp.headers().get(ACCEPT_ENCODING), nullValue());
                CharSequence contentEncoding = resp.headers().get(CONTENT_ENCODING);
                boolean found = contentEncoding == null && (serverEncoder.list.isEmpty() || !request.headers().contains(ACCEPT_ENCODING));
                for (BufferEncoder be : serverEncoder.list) {
                    if (contentEncoding == null && contentEqualsIgnoreCase(be.encodingName(), identityEncoder().encodingName()) || contentEncoding != null && contentEqualsIgnoreCase(be.encodingName(), contentEncoding)) {
                        found = true;
                        break;
                    }
                }
                return found || !valid ? resp : responseFactory.ok().payloadBody(Publisher.from("server error: invalid " + CONTENT_ENCODING + ": " + contentEncoding), appSerializerUtf8FixLen());
            }).onErrorReturn(AssertionError.class, cause -> responseFactory.ok().payloadBody(Publisher.from("server error: " + cause.toString()), appSerializerUtf8FixLen()));
        }
    }).appendServiceFilter(new ContentEncodingHttpServiceFilter(serverEncoder.list, serverDecoder.group)).listenBlockingAndAwait((ctx, request, responseFactory) -> {
        String requestPayload = request.payloadBody(textSerializerUtf8());
        if (payloadAsString((byte) 'a').equals(requestPayload)) {
            return responseFactory.ok().payloadBody(payloadAsString((byte) 'b'), textSerializerUtf8());
        } else {
            return responseFactory.badRequest().payloadBody(requestPayload, textSerializerUtf8());
        }
    });
        BlockingHttpClient client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).protocols(protocol.config).appendClientFilter(new ContentEncodingHttpRequesterFilter(clientDecoder.group)).appendClientFilter(c -> new StreamingHttpClientFilter(c) {

            @Override
            protected Single<StreamingHttpResponse> request(final StreamingHttpRequester delegate, final StreamingHttpRequest request) {
                return Single.defer(() -> {
                    assertHeader(() -> clientEncoding.encoder == null ? null : clientEncoding.encoder.encodingName(), request.headers().get(CONTENT_ENCODING), true);
                    assertHeader(clientDecoder.group::advertisedMessageEncoding, request.headers().get(ACCEPT_ENCODING), false);
                    return delegate.request(request).shareContextOnSubscribe();
                });
            }
        }).buildBlocking()) {
        HttpResponse response = client.request(client.get("/").contentEncoding(clientEncoding.encoder).payloadBody(payloadAsString((byte) 'a'), textSerializerUtf8()));
        if (valid) {
            assertThat(response.status(), is(OK));
            // content encoding should be stripped by the time the decoding is done.
            assertThat(response.headers().get(CONTENT_ENCODING), nullValue());
            assertEquals(payloadAsString((byte) 'b'), response.payloadBody(textSerializerUtf8()));
        } else {
            assertThat(response.status(), is(UNSUPPORTED_MEDIA_TYPE));
        }
    }
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) Supplier(java.util.function.Supplier) UNSUPPORTED_MEDIA_TYPE(io.servicetalk.http.api.HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) IsNull.nullValue(org.hamcrest.core.IsNull.nullValue) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) ContentEncodingHttpRequesterFilter(io.servicetalk.http.api.ContentEncodingHttpRequesterFilter) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) BufferEncoder(io.servicetalk.encoding.api.BufferEncoder) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) 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) HttpResponse(io.servicetalk.http.api.HttpResponse) Identity.identityEncoder(io.servicetalk.encoding.api.Identity.identityEncoder) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) CharSequences.contentEqualsIgnoreCase(io.servicetalk.buffer.api.CharSequences.contentEqualsIgnoreCase) ACCEPT_ENCODING(io.servicetalk.http.api.HttpHeaderNames.ACCEPT_ENCODING) ContentEncodingHttpServiceFilter(io.servicetalk.http.api.ContentEncodingHttpServiceFilter) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) CONTENT_ENCODING(io.servicetalk.http.api.HttpHeaderNames.CONTENT_ENCODING) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) ContentEncodingHttpRequesterFilter(io.servicetalk.http.api.ContentEncodingHttpRequesterFilter) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) ContentEncodingHttpServiceFilter(io.servicetalk.http.api.ContentEncodingHttpServiceFilter) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) BufferEncoder(io.servicetalk.encoding.api.BufferEncoder) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Aggregations

HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)19 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)18 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)18 Single (io.servicetalk.concurrent.api.Single)16 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)15 StreamingHttpServiceFilter (io.servicetalk.http.api.StreamingHttpServiceFilter)15 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)9 Buffer (io.servicetalk.buffer.api.Buffer)8 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)8 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)7 StreamingHttpService (io.servicetalk.http.api.StreamingHttpService)7 InetSocketAddress (java.net.InetSocketAddress)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 HttpResponse (io.servicetalk.http.api.HttpResponse)6 OK (io.servicetalk.http.api.HttpResponseStatus.OK)6 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)6 ServerContext (io.servicetalk.transport.api.ServerContext)6 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)6 Nullable (javax.annotation.Nullable)6 Publisher (io.servicetalk.concurrent.api.Publisher)5