Search in sources :

Example 6 with StreamingHttpRequester

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

the class H2PriorKnowledgeFeatureParityTest method clientSendsInvalidContentLength.

private void clientSendsInvalidContentLength(boolean addTrailers, BiConsumer<HttpHeaders, Integer> headersModifier) throws Exception {
    assumeFalse(!h2PriorKnowledge && addTrailers, "HTTP/1.1 does not support Content-Length with trailers");
    InetSocketAddress serverAddress = bindHttpEchoServer();
    try (BlockingHttpClient client = forSingleAddress(HostAndPort.of(serverAddress)).protocols(h2PriorKnowledge ? h2Default() : h1Default()).executionStrategy(clientExecutionStrategy).appendClientFilter(client1 -> new StreamingHttpClientFilter(client1) {

        @Override
        protected Single<StreamingHttpResponse> request(final StreamingHttpRequester delegate, final StreamingHttpRequest request) {
            return request.toRequest().map(req -> {
                req.headers().remove(TRANSFER_ENCODING);
                headersModifier.accept(req.headers(), req.payloadBody().readableBytes());
                return req.toStreamingRequest();
            }).flatMap(delegate::request);
        }
    }).buildBlocking()) {
        HttpRequest request = client.get("/").payloadBody("a", textSerializerUtf8());
        if (addTrailers) {
            request.trailers().set("mytrailer", "myvalue");
        }
        if (h2PriorKnowledge) {
            assertThrows(H2StreamResetException.class, () -> client.request(request));
        } else {
            try (ReservedBlockingHttpConnection reservedConn = client.reserveConnection(request)) {
                assertThrows(IOException.class, () -> {
                    // Either the current request or the next one should fail
                    reservedConn.request(request);
                    reservedConn.request(client.get("/"));
                });
            }
        }
    }
}
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) LogLevel(io.servicetalk.logging.api.LogLevel) 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) PROTOCOL_ERROR(io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR) HttpCookiePair(io.servicetalk.http.api.HttpCookiePair) DefaultHttp2ResetFrame(io.netty.handler.codec.http2.DefaultHttp2ResetFrame) 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) UPGRADE(io.servicetalk.http.api.HttpHeaderNames.UPGRADE) 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) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) 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) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) 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) CONNECTION(io.servicetalk.http.api.HttpHeaderNames.CONNECTION) 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) Test(org.junit.jupiter.api.Test) 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) HttpMetaData(io.servicetalk.http.api.HttpMetaData) 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) KEEP_ALIVE(io.servicetalk.http.api.HttpHeaderValues.KEEP_ALIVE) 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) PROXY_CONNECTION(io.servicetalk.http.netty.H2ToStH1Utils.PROXY_CONNECTION) 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) HttpRequest(io.servicetalk.http.api.HttpRequest) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) InetSocketAddress(java.net.InetSocketAddress) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection)

Example 7 with StreamingHttpRequester

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

the class ResponseTimeoutTest method setUp.

private void setUp(Duration clientTimeout, Duration serverTimeout) throws Exception {
    ctx = forAddress(localAddress(0)).appendServiceFilter(new TimeoutHttpServiceFilter((req, ts) -> serverTimeout, true)).listenAndAwait((__, ___, factory) -> {
        Single<HttpResponse> resp = Single.never();
        serverResponses.add(resp);
        return resp;
    });
    client = forSingleAddress(serverHostAndPort(ctx)).appendClientFilter(client -> new StreamingHttpClientFilter(client) {

        @Override
        protected Single<StreamingHttpResponse> request(final StreamingHttpRequester delegate, final StreamingHttpRequest request) {
            return Single.succeeded(null).afterOnSubscribe(delayedClientCancels::add).concat(delegate().request(request).liftSync(target -> new Subscriber<StreamingHttpResponse>() {

                @Override
                public void onSubscribe(final Cancellable cancellable) {
                    target.onSubscribe(() -> {
                        delayedClientCancels.add(cancellable);
                        cancellable.cancel();
                    });
                }

                @Override
                public void onSuccess(final StreamingHttpResponse result) {
                    ClientTerminationSignal signal = OK.equals(result.status()) ? new ClientTerminationSignal(target, result) : new ClientTerminationSignal(target, new HttpResponseStatusException(result.status()));
                    delayedClientTermination.add(signal);
                    target.onSuccess(result);
                }

                @Override
                public void onError(final Throwable t) {
                    delayedClientTermination.add(new ClientTerminationSignal(target, t));
                    target.onError(t);
                }
            })).filter(Objects::nonNull).firstOrError().map(thing -> (StreamingHttpResponse) thing);
        }
    }).appendConnectionFactoryFilter(original -> new CountingConnectionFactory(original, connectionCount)).appendClientFilter(new TimeoutHttpRequesterFilter((req, ts) -> clientTimeout, true)).build();
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Arrays(java.util.Arrays) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Subscriber(io.servicetalk.concurrent.SingleSource.Subscriber) TimeoutException(java.util.concurrent.TimeoutException) Cancellable(io.servicetalk.concurrent.Cancellable) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Duration(java.time.Duration) HttpClient(io.servicetalk.http.api.HttpClient) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Nullable(javax.annotation.Nullable) MethodSource(org.junit.jupiter.params.provider.MethodSource) PrintWriter(java.io.PrintWriter) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single.defer(io.servicetalk.concurrent.api.Single.defer) Single(io.servicetalk.concurrent.api.Single) StringWriter(java.io.StringWriter) Collection(java.util.Collection) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) HttpResponse(io.servicetalk.http.api.HttpResponse) TimeoutHttpRequesterFilter(io.servicetalk.http.utils.TimeoutHttpRequesterFilter) BlockingQueue(java.util.concurrent.BlockingQueue) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) TimeoutHttpServiceFilter(io.servicetalk.http.utils.TimeoutHttpServiceFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ContextMap(io.servicetalk.context.api.ContextMap) Matcher(org.hamcrest.Matcher) TransportObserver(io.servicetalk.transport.api.TransportObserver) Single.failed(io.servicetalk.concurrent.api.Single.failed) Matchers.is(org.hamcrest.Matchers.is) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) Cancellable(io.servicetalk.concurrent.Cancellable) TimeoutHttpServiceFilter(io.servicetalk.http.utils.TimeoutHttpServiceFilter) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) Single(io.servicetalk.concurrent.api.Single) Subscriber(io.servicetalk.concurrent.SingleSource.Subscriber) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) TimeoutHttpRequesterFilter(io.servicetalk.http.utils.TimeoutHttpRequesterFilter) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 8 with StreamingHttpRequester

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

the class DefaultMultiAddressUrlHttpClientBuilderTest method buildWithProvidedServiceDiscoverer.

@Test
@SuppressWarnings("unchecked")
void buildWithProvidedServiceDiscoverer() throws Exception {
    ServiceDiscoverer<HostAndPort, InetSocketAddress, ServiceDiscovererEvent<InetSocketAddress>> mockedServiceDiscoverer = mock(ServiceDiscoverer.class);
    StreamingHttpRequester newRequester = HttpClients.forMultiAddressUrl(mockedServiceDiscoverer).ioExecutor(CTX.ioExecutor()).buildStreaming();
    newRequester.closeAsync().toFuture().get();
    verify(mockedServiceDiscoverer, never()).closeAsync();
}
Also used : AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) BlockingStreamingHttpRequester(io.servicetalk.http.api.BlockingStreamingHttpRequester) ServiceDiscovererEvent(io.servicetalk.client.api.ServiceDiscovererEvent) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test)

Example 9 with StreamingHttpRequester

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

the class AbstractEchoServerBasedHttpRequesterTest method makeRequestValidateResponseAndClose.

static void makeRequestValidateResponseAndClose(StreamingHttpRequester requester) throws ExecutionException, InterruptedException {
    try {
        StreamingHttpRequest request = requester.get("/request?foo=bar&foo=baz").payloadBody(from(DEFAULT_ALLOCATOR.fromAscii("Testing123")));
        request.headers().set(HOST, "mock.servicetalk.io");
        StreamingHttpResponse resp = awaitIndefinitelyNonNull(requester.request(request).retryWhen(retryWithExponentialBackoffFullJitter(10, t -> true, ofMillis(100), ofDays(10), CTX.executor())));
        assertThat(resp.status(), equalTo(OK));
        Single<String> respBody = resp.payloadBody().collect(StringBuilder::new, (sb, buf) -> {
            sb.append(buf.toString(UTF_8));
            return sb;
        }).map(StringBuilder::toString);
        HttpHeaders headers = resp.headers();
        assertThat(headers.get("test-req-method"), hasToString(GET.toString()));
        assertThat(headers.get("test-req-target"), hasToString("/request?foo=bar&foo=baz"));
        assertThat(headers.get("test-req-header-host"), hasToString("mock.servicetalk.io"));
        assertThat(headers.get("test-req-header-transfer-encoding"), equalTo(CHUNKED));
        assertThat(respBody.toFuture().get(), equalTo("Testing123"));
    } finally {
        requester.closeAsync().toFuture().get();
    }
}
Also used : Matchers.hasToString(org.hamcrest.Matchers.hasToString) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) IsEqual.equalTo(org.hamcrest.core.IsEqual.equalTo) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) AfterAll(org.junit.jupiter.api.AfterAll) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) TestInstance(org.junit.jupiter.api.TestInstance) BeforeAll(org.junit.jupiter.api.BeforeAll) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HOST(io.servicetalk.http.api.HttpHeaderNames.HOST) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) Duration.ofDays(java.time.Duration.ofDays) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) RetryStrategies.retryWithExponentialBackoffFullJitter(io.servicetalk.concurrent.api.RetryStrategies.retryWithExponentialBackoffFullJitter) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) OK(io.servicetalk.http.api.HttpResponseStatus.OK) GET(io.servicetalk.http.api.HttpRequestMethod.GET) ExecutionException(java.util.concurrent.ExecutionException) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Duration.ofMillis(java.time.Duration.ofMillis) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.hasToString(org.hamcrest.Matchers.hasToString) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 10 with StreamingHttpRequester

use of io.servicetalk.http.api.StreamingHttpRequester 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

StreamingHttpRequester (io.servicetalk.http.api.StreamingHttpRequester)10 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)8 Single (io.servicetalk.concurrent.api.Single)7 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)7 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)7 OK (io.servicetalk.http.api.HttpResponseStatus.OK)6 StreamingHttpClientFilter (io.servicetalk.http.api.StreamingHttpClientFilter)6 ServerContext (io.servicetalk.transport.api.ServerContext)6 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)6 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)6 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)5 Nullable (javax.annotation.Nullable)5 Matchers.is (org.hamcrest.Matchers.is)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 Publisher (io.servicetalk.concurrent.api.Publisher)4 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)4 CHUNKED (io.servicetalk.http.api.HttpHeaderValues.CHUNKED)4 HttpHeaders (io.servicetalk.http.api.HttpHeaders)4 GET (io.servicetalk.http.api.HttpRequestMethod.GET)4 HttpResponse (io.servicetalk.http.api.HttpResponse)4