Search in sources :

Example 6 with StreamingHttpServiceFilter

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

the class ContentLengthAndTrailersTest method setUp.

private void setUp(HttpProtocol protocol, String content) {
    this.protocol = protocol;
    this.content = content;
    protocol(protocol.config);
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            // Use transform to simulate access to request trailers
            return delegate().handle(ctx, request.transform(new StatelessTrailersTransformer<>()), responseFactory).map(response -> {
                final HttpHeaders headers = request.headers();
                if (headers.contains(CONTENT_LENGTH)) {
                    response.setHeader(CLIENT_CONTENT_LENGTH, mergeValues(headers.values(CONTENT_LENGTH)));
                }
                if (headers.contains(TRANSFER_ENCODING)) {
                    response.setHeader(CLIENT_TRANSFER_ENCODING, mergeValues(headers.values(TRANSFER_ENCODING)));
                }
                return response;
            });
        }
    });
    setUp(CACHED, CACHED_SERVER);
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) ArrayList(java.util.ArrayList) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpMetaData(io.servicetalk.http.api.HttpMetaData) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) Nullable(javax.annotation.Nullable) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) MethodSource(org.junit.jupiter.params.provider.MethodSource) Single(io.servicetalk.concurrent.api.Single) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.equalTo(org.hamcrest.Matchers.equalTo) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) HTTP_1(io.servicetalk.http.netty.HttpProtocol.HTTP_1) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest)

Example 7 with StreamingHttpServiceFilter

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

the class ConsumeRequestPayloadOnResponsePathTest method test.

private void test(final BiFunction<Single<StreamingHttpResponse>, StreamingHttpRequest, Single<StreamingHttpResponse>> consumeRequestPayload) throws Exception {
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            return consumeRequestPayload.apply(delegate().handle(ctx, request, responseFactory), request);
        }
    }).listenStreamingAndAwait((ctx, request, responseFactory) -> {
        final StreamingHttpResponse response = responseFactory.ok().addHeader(TRAILER, X_TOTAL_LENGTH).payloadBody(from("Response\n", "Payload\n", "Body\n"), appSerializerUtf8FixLen()).transform(new TrailersTransformer<AtomicInteger, Buffer>() {

            @Override
            public AtomicInteger newState() {
                return new AtomicInteger();
            }

            @Override
            public Buffer accept(final AtomicInteger total, final Buffer chunk) {
                total.addAndGet(chunk.readableBytes());
                return chunk;
            }

            @Override
            public HttpHeaders payloadComplete(final AtomicInteger total, final HttpHeaders trailers) {
                trailers.add(X_TOTAL_LENGTH, String.valueOf(total.get()));
                return trailers;
            }

            @Override
            public HttpHeaders catchPayloadFailure(final AtomicInteger __, final Throwable ___, final HttpHeaders trailers) {
                return trailers;
            }
        });
        return succeeded(response);
    })) {
        HttpResponse response;
        try (BlockingHttpClient client = HttpClients.forSingleAddress(AddressUtils.serverHostAndPort(serverContext)).buildBlocking()) {
            response = client.request(client.post("/").payloadBody(EXPECTED_REQUEST_PAYLOAD, textSerializerUtf8()));
            serverLatch.await();
        }
        assertThat(response.status(), is(OK));
        assertThat("Request payload body might be consumed by someone else", errorRef.get(), is(nullValue()));
        assertThat(receivedPayload.toString(), is(EXPECTED_REQUEST_PAYLOAD));
        assertThat(response.headers().contains(TRAILER, X_TOTAL_LENGTH), is(true));
        assertThat(response.trailers().contains(X_TOTAL_LENGTH), is(true));
        CharSequence trailerLength = response.trailers().get(X_TOTAL_LENGTH);
        assertNotNull(trailerLength);
        assertThat("Unexpected response payload: '" + response.payloadBody().toString(UTF_8) + "'", trailerLength.toString(), is(Integer.toString(response.payloadBody().readableBytes())));
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) BiFunction(java.util.function.BiFunction) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpResponses.newTransportResponse(io.servicetalk.http.api.StreamingHttpResponses.newTransportResponse) PlatformDependent(io.servicetalk.utils.internal.PlatformDependent) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) TRAILER(io.servicetalk.http.api.HttpHeaderNames.TRAILER) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) HttpResponse(io.servicetalk.http.api.HttpResponse) OK(io.servicetalk.http.api.HttpResponseStatus.OK) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) AddressUtils(io.servicetalk.transport.netty.internal.AddressUtils) Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ServerContext(io.servicetalk.transport.api.ServerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 8 with StreamingHttpServiceFilter

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

the class TimeoutHttpServiceFilterTest method applyFilter.

private static Single<StreamingHttpResponse> applyFilter(TimeoutHttpServiceFilter filterFactory, final HttpExecutionStrategy strategy, final Single<StreamingHttpResponse> responseSingle) {
    HttpExecutionContext executionContext = new DefaultHttpExecutionContext(DEFAULT_ALLOCATOR, IO_EXECUTOR, EXECUTOR, strategy);
    HttpServiceContext serviceContext = mock(HttpServiceContext.class);
    when(serviceContext.executionContext()).thenReturn(executionContext);
    StreamingHttpService service = mock(StreamingHttpService.class);
    when(service.handle(any(), any(), any())).thenReturn(responseSingle);
    StreamingHttpServiceFilter filter = filterFactory.create(service);
    return filter.handle(serviceContext, mock(StreamingHttpRequest.class), mock(StreamingHttpResponseFactory.class));
}
Also used : StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) DefaultHttpExecutionContext(io.servicetalk.http.api.DefaultHttpExecutionContext) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) DefaultHttpExecutionContext(io.servicetalk.http.api.DefaultHttpExecutionContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest)

Example 9 with StreamingHttpServiceFilter

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

the class BasicAuthHttpServiceFilterTest method closeAsync.

@Test
void closeAsync() throws Exception {
    AtomicBoolean credentialsVerifierClosed = new AtomicBoolean();
    AtomicBoolean nextServiceClosed = new AtomicBoolean();
    StreamingHttpServiceFilter service = new BasicAuthHttpServiceFilter.Builder<>(new CredentialsVerifier<BasicUserInfo>() {

        @Override
        public Single<BasicUserInfo> apply(final String userId, final String password) {
            return never();
        }

        @Override
        public Completable closeAsync() {
            return completed().beforeOnComplete(() -> credentialsVerifierClosed.set(true));
        }
    }, REALM_VALUE).buildServer().create(new StreamingHttpService() {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory factory) {
            return never();
        }

        @Override
        public Completable closeAsync() {
            return completed().beforeOnComplete(() -> nextServiceClosed.set(true));
        }
    });
    assertFalse(credentialsVerifierClosed.get());
    assertFalse(nextServiceClosed.get());
    service.closeAsync().toFuture().get();
    assertTrue(credentialsVerifierClosed.get());
    assertTrue(nextServiceClosed.get());
}
Also used : Completable(io.servicetalk.concurrent.api.Completable) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Test(org.junit.jupiter.api.Test)

Example 10 with StreamingHttpServiceFilter

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

the class BasicAuthHttpServiceFilterTest method testAuthenticatedForProxy.

private static void testAuthenticatedForProxy(StreamingHttpRequest request) throws Exception {
    StreamingHttpServiceFilter service = new BasicAuthHttpServiceFilter.Builder<>(CREDENTIALS_VERIFIER, REALM_VALUE).userInfoAsyncContextKey(USER_INFO_AC_KEY).userInfoRequestContextKey(USER_INFO_RC_KEY).buildProxy().create(HELLO_WORLD_SERVICE);
    StreamingHttpResponse response = awaitIndefinitelyNonNull(service.handle(CONN_CTX, request, reqRespFactory));
    assertEquals(OK, response.status());
    assertTrue(response.headers().contains(USER_ID_AC_HEADER_NAME, "userId"));
    assertTrue(response.headers().contains(USER_ID_RC_HEADER_NAME, "userId"));
}
Also used : StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Aggregations

StreamingHttpServiceFilter (io.servicetalk.http.api.StreamingHttpServiceFilter)21 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)17 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)17 HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)15 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)15 Single (io.servicetalk.concurrent.api.Single)14 Buffer (io.servicetalk.buffer.api.Buffer)7 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)7 HttpResponse (io.servicetalk.http.api.HttpResponse)7 OK (io.servicetalk.http.api.HttpResponseStatus.OK)7 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)7 Test (org.junit.jupiter.api.Test)7 InetSocketAddress (java.net.InetSocketAddress)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)5 HttpHeaders (io.servicetalk.http.api.HttpHeaders)5 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)5 ServerContext (io.servicetalk.transport.api.ServerContext)5 CharSequences.newAsciiString (io.servicetalk.buffer.api.CharSequences.newAsciiString)4 Publisher (io.servicetalk.concurrent.api.Publisher)4