Search in sources :

Example 6 with HttpServiceContext

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

the class HttpTransportObserverTest method setUp.

private void setUp(HttpProtocol protocol) {
    this.protocol = protocol;
    protocol(protocol.config);
    connectionAcceptor(ctx -> {
        ctx.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
        return completed();
    });
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(HttpServiceContext ctx, StreamingHttpRequest request, StreamingHttpResponseFactory responseFactory) {
            requestReceived.countDown();
            try {
                processRequest.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throwException(e);
            }
            return delegate().handle(ctx, request, responseFactory);
        }
    });
    clientTransportObserver = mock(TransportObserver.class, "clientTransportObserver");
    clientConnectionObserver = mock(ConnectionObserver.class, "clientConnectionObserver");
    clientDataObserver = mock(DataObserver.class, "clientDataObserver");
    clientMultiplexedObserver = mock(MultiplexedObserver.class, "clientMultiplexedObserver");
    clientStreamObserver = mock(StreamObserver.class, "clientStreamObserver");
    clientReadObserver = mock(ReadObserver.class, "clientReadObserver");
    clientWriteObserver = mock(WriteObserver.class, "clientWriteObserver");
    when(clientTransportObserver.onNewConnection(any(), any())).thenReturn(clientConnectionObserver);
    lenient().when(clientConnectionObserver.connectionEstablished(any(ConnectionInfo.class))).thenReturn(clientDataObserver);
    lenient().when(clientConnectionObserver.multiplexedConnectionEstablished(any(ConnectionInfo.class))).thenReturn(clientMultiplexedObserver);
    lenient().when(clientMultiplexedObserver.onNewStream()).thenReturn(clientStreamObserver);
    lenient().when(clientStreamObserver.streamEstablished()).thenReturn(clientDataObserver);
    lenient().when(clientDataObserver.onNewRead()).thenReturn(clientReadObserver);
    lenient().when(clientDataObserver.onNewWrite()).thenReturn(clientWriteObserver);
    serverTransportObserver = mock(TransportObserver.class, "serverTransportObserver");
    serverConnectionObserver = mock(ConnectionObserver.class, "serverConnectionObserver");
    serverDataObserver = mock(DataObserver.class, "serverDataObserver");
    serverMultiplexedObserver = mock(MultiplexedObserver.class, "serverMultiplexedObserver");
    serverStreamObserver = mock(StreamObserver.class, "serverStreamObserver");
    serverReadObserver = mock(ReadObserver.class, "serverReadObserver");
    serverWriteObserver = mock(WriteObserver.class, "serverWriteObserver");
    when(serverTransportObserver.onNewConnection(any(), any())).thenReturn(serverConnectionObserver);
    lenient().when(serverConnectionObserver.connectionEstablished(any(ConnectionInfo.class))).thenReturn(serverDataObserver);
    lenient().when(serverConnectionObserver.multiplexedConnectionEstablished(any(ConnectionInfo.class))).thenReturn(serverMultiplexedObserver);
    lenient().when(serverMultiplexedObserver.onNewStream()).thenReturn(serverStreamObserver);
    lenient().when(serverStreamObserver.streamEstablished()).thenReturn(serverDataObserver);
    lenient().when(serverDataObserver.onNewRead()).thenReturn(serverReadObserver);
    lenient().when(serverDataObserver.onNewWrite()).thenReturn(serverWriteObserver);
    transportObserver(clientTransportObserver, serverTransportObserver);
    setUp(CACHED, CACHED_SERVER);
}
Also used : StreamObserver(io.servicetalk.transport.api.ConnectionObserver.StreamObserver) MultiplexedObserver(io.servicetalk.transport.api.ConnectionObserver.MultiplexedObserver) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) TransportObserver(io.servicetalk.transport.api.TransportObserver) WriteObserver(io.servicetalk.transport.api.ConnectionObserver.WriteObserver) DataObserver(io.servicetalk.transport.api.ConnectionObserver.DataObserver) ConnectionObserver(io.servicetalk.transport.api.ConnectionObserver) 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) ReadObserver(io.servicetalk.transport.api.ConnectionObserver.ReadObserver)

Example 7 with HttpServiceContext

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

the class TestServiceStreaming method handle.

@Override
public Single<StreamingHttpResponse> handle(final HttpServiceContext context, final StreamingHttpRequest req, final StreamingHttpResponseFactory factory) {
    LOGGER.debug("({}) Handling {}", counter, req.toString((a, b) -> b));
    final StreamingHttpResponse response;
    switch(req.path()) {
        case SVC_ECHO:
            response = newEchoResponse(req, factory);
            break;
        case SVC_COUNTER_NO_LAST_CHUNK:
            response = newTestCounterResponse(context, req, factory);
            break;
        case SVC_COUNTER:
            response = newTestCounterResponseWithLastPayloadChunk(context, req, factory);
            break;
        case SVC_LARGE_LAST:
            response = newLargeLastChunkResponse(context, req, factory);
            break;
        case SVC_TEST_PUBLISHER:
            response = newTestPublisherResponse(req, factory);
            break;
        case SVC_NO_CONTENT:
            response = newNoContentResponse(req, factory);
            break;
        case SVC_NO_CONTENT_AFTER_READ:
            return req.payloadBody().ignoreElements().concat(succeeded(newNoContentResponse(req, factory)));
        case SVC_ROT13:
            response = newRot13Response(req, factory);
            break;
        case SVC_NEVER:
            return req.payloadBody().ignoreElements().concat(never());
        case SVC_THROW_ERROR:
            response = throwErrorSynchronously();
            break;
        case SVC_SINGLE_ERROR:
            return Single.failed(DELIBERATE_EXCEPTION);
        case SVC_ERROR_BEFORE_READ:
            response = throwErrorBeforeRead(req, factory);
            break;
        case SVC_ERROR_DURING_READ:
            response = throwErrorDuringRead(req, factory);
            break;
        default:
            response = newNotFoundResponse(req, factory);
    }
    return succeeded(response);
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) LoggerFactory(org.slf4j.LoggerFactory) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) Publisher.empty(io.servicetalk.concurrent.api.Publisher.empty) Function(java.util.function.Function) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) Logger(org.slf4j.Logger) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) Single.never(io.servicetalk.concurrent.api.Single.never) Buffer(io.servicetalk.buffer.api.Buffer) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) NOT_FOUND(io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 8 with HttpServiceContext

use of io.servicetalk.http.api.HttpServiceContext 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 9 with HttpServiceContext

use of io.servicetalk.http.api.HttpServiceContext 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 10 with HttpServiceContext

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

the class AlpnClientAndServerTest method assertResponseAndServiceContext.

private void assertResponseAndServiceContext(HttpResponse response) throws Exception {
    assertThat(response.version(), is(expectedProtocol));
    assertThat(response.status(), is(OK));
    assertThat(response.payloadBody(textSerializerUtf8()), is(PAYLOAD_BODY));
    HttpServiceContext serviceCtx = serviceContext.take();
    assertThat(serviceCtx.protocol(), is(expectedProtocol));
    assertThat(serviceCtx.sslSession(), is(notNullValue()));
    assertThat(serviceCtx.sslSession(), is(notNullValue()));
    assertThat(requestVersion.take(), is(expectedProtocol));
    assertThat(serviceContext, is(empty()));
    assertThat(requestVersion, is(empty()));
}
Also used : HttpServiceContext(io.servicetalk.http.api.HttpServiceContext)

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