Search in sources :

Example 51 with BlockingHttpClient

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

the class ConnectionAcceptorOffloadingTest method testAcceptorOffloading.

@ParameterizedTest
@ValueSource(booleans = { false, true })
void testAcceptorOffloading(boolean offload) throws Exception {
    AtomicReference<Boolean> offloaded = new AtomicReference<>();
    ConnectionAcceptorFactory factory = ConnectionAcceptorFactory.withStrategy(original -> context -> {
        boolean isIoThread = IoThreadFactory.IoThread.currentThreadIsIoThread();
        offloaded.set(!isIoThread);
        return original.accept(context);
    }, offload ? ConnectExecutionStrategy.offloadAll() : ConnectExecutionStrategy.offloadNone());
    try (ServerContext server = HttpServers.forPort(0).appendConnectionAcceptorFilter(factory).listenAndAwait(this::helloWorld)) {
        SocketAddress serverAddress = server.listenAddress();
        try (BlockingHttpClient client = HttpClients.forResolvedAddress(serverAddress).buildBlocking()) {
            HttpResponse response = client.request(client.get("/sayHello"));
            assertThat("unexpected status", response.status(), is(HttpResponseStatus.OK));
        }
    }
    assertThat("factory was not invoked", offloaded.get(), is(notNullValue()));
    assertThat("incorrect offloading", offloaded.get(), is(offload));
}
Also used : ServerContext(io.servicetalk.transport.api.ServerContext) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) SocketAddress(java.net.SocketAddress) ConnectionAcceptorFactory(io.servicetalk.transport.api.ConnectionAcceptorFactory) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 52 with BlockingHttpClient

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

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

the class BasicAuthStrategyInfluencerTest method noOffloadsInfluence.

@Test
void noOffloadsInfluence() throws Exception {
    BlockingHttpClient client = setup(true);
    assert service != null;
    HttpResponse response = makeRequest(client);
    assertThat("Unexpected response.", response.status().code(), is(200));
    service.assertHandleOffload(startsWith(IO_EXECUTOR_NAME_PREFIX));
    service.assertRequestOffload(startsWith(IO_EXECUTOR_NAME_PREFIX));
    service.assertResponseOffload(startsWith(IO_EXECUTOR_NAME_PREFIX));
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) Test(org.junit.jupiter.api.Test)

Example 54 with BlockingHttpClient

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

the class BlockingHelloWorldClient method main.

public static void main(String[] args) throws Exception {
    try (BlockingHttpClient client = HttpClients.forSingleAddress("localhost", 8080).buildBlocking()) {
        HttpResponse response = client.request(client.get("/sayHello"));
        System.out.println(response.toString((name, value) -> value));
        System.out.println(response.payloadBody(textSerializerUtf8()));
    }
}
Also used : BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpResponse(io.servicetalk.http.api.HttpResponse) HttpClients(io.servicetalk.http.netty.HttpClients) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpResponse(io.servicetalk.http.api.HttpResponse)

Example 55 with BlockingHttpClient

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

the class DefaultGrpcClientCallFactory method newBlockingCall.

@Override
public <Req, Resp> BlockingClientCall<Req, Resp> newBlockingCall(final MethodDescriptor<Req, Resp> methodDescriptor, final BufferDecoderGroup decompressors) {
    final BlockingHttpClient client = streamingHttpClient.asBlockingClient();
    GrpcSerializer<Req> serializerIdentity = serializer(methodDescriptor);
    GrpcDeserializer<Resp> deserializerIdentity = deserializer(methodDescriptor);
    List<GrpcDeserializer<Resp>> deserializers = deserializers(methodDescriptor, decompressors.decoders());
    CharSequence acceptedEncoding = decompressors.advertisedMessageEncoding();
    CharSequence requestContentType = grpcContentType(methodDescriptor.requestDescriptor().serializerDescriptor().contentType());
    CharSequence responseContentType = grpcContentType(methodDescriptor.responseDescriptor().serializerDescriptor().contentType());
    return (metadata, request) -> {
        Duration timeout = timeoutForRequest(metadata.timeout());
        GrpcSerializer<Req> serializer = serializer(methodDescriptor, serializerIdentity, metadata.requestCompressor());
        String mdPath = methodDescriptor.httpPath();
        HttpRequest httpRequest = client.post(UNKNOWN_PATH.equals(mdPath) ? metadata.path() : mdPath);
        initRequest(httpRequest, requestContentType, serializer.messageEncoding(), acceptedEncoding, timeout);
        httpRequest.payloadBody(serializer.serialize(request, client.executionContext().bufferAllocator()));
        try {
            assignStrategy(httpRequest, metadata);
            final HttpResponse response = client.request(httpRequest);
            return validateResponseAndGetPayload(response, responseContentType, client.executionContext().bufferAllocator(), readGrpcMessageEncodingRaw(response.headers(), deserializerIdentity, deserializers, GrpcDeserializer::messageEncoding));
        } catch (Throwable cause) {
            throw toGrpcException(cause);
        }
    };
}
Also used : GrpcUtils.serializerDeserializer(io.servicetalk.grpc.api.GrpcUtils.serializerDeserializer) Publisher(io.servicetalk.concurrent.api.Publisher) DefaultMethodDescriptor(io.servicetalk.grpc.api.GrpcUtils.DefaultMethodDescriptor) GrpcUtils.decompressors(io.servicetalk.grpc.api.GrpcUtils.decompressors) GrpcUtils.readGrpcMessageEncodingRaw(io.servicetalk.grpc.api.GrpcUtils.readGrpcMessageEncodingRaw) GrpcUtils.defaultToInt(io.servicetalk.grpc.api.GrpcUtils.defaultToInt) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) HttpRequest(io.servicetalk.http.api.HttpRequest) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Duration(java.time.Duration) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) BufferDecoderGroup(io.servicetalk.encoding.api.BufferDecoderGroup) GRPC_CONTENT_TYPE_PROTO_SUFFIX(io.servicetalk.grpc.api.GrpcHeaderValues.GRPC_CONTENT_TYPE_PROTO_SUFFIX) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpClient(io.servicetalk.http.api.HttpClient) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) GrpcUtils.toGrpcException(io.servicetalk.grpc.api.GrpcUtils.toGrpcException) BufferEncoder(io.servicetalk.encoding.api.BufferEncoder) Nullable(javax.annotation.Nullable) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) Completable(io.servicetalk.concurrent.api.Completable) HttpResponse(io.servicetalk.http.api.HttpResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Identity.identityEncoder(io.servicetalk.encoding.api.Identity.identityEncoder) GrpcUtils.grpcContentType(io.servicetalk.grpc.api.GrpcUtils.grpcContentType) GrpcUtils.validateResponseAndGetPayload(io.servicetalk.grpc.api.GrpcUtils.validateResponseAndGetPayload) HTTP_EXECUTION_STRATEGY_KEY(io.servicetalk.http.api.HttpContextKeys.HTTP_EXECUTION_STRATEGY_KEY) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) HttpRequestMetaData(io.servicetalk.http.api.HttpRequestMetaData) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) GrpcUtils.initRequest(io.servicetalk.grpc.api.GrpcUtils.initRequest) BlockingIterables.singletonBlockingIterable(io.servicetalk.concurrent.internal.BlockingIterables.singletonBlockingIterable) GRPC_DEADLINE_KEY(io.servicetalk.grpc.internal.DeadlineUtils.GRPC_DEADLINE_KEY) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) BufferDecoder(io.servicetalk.encoding.api.BufferDecoder) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) HttpRequest(io.servicetalk.http.api.HttpRequest) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) Duration(java.time.Duration)

Aggregations

BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)100 HttpResponse (io.servicetalk.http.api.HttpResponse)69 ServerContext (io.servicetalk.transport.api.ServerContext)54 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)49 Test (org.junit.jupiter.api.Test)41 InetSocketAddress (java.net.InetSocketAddress)32 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)30 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)28 MethodSource (org.junit.jupiter.params.provider.MethodSource)28 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)26 HttpRequest (io.servicetalk.http.api.HttpRequest)25 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)25 Single (io.servicetalk.concurrent.api.Single)21 OK (io.servicetalk.http.api.HttpResponseStatus.OK)21 HttpSerializers.textSerializerUtf8 (io.servicetalk.http.api.HttpSerializers.textSerializerUtf8)21 HostAndPort (io.servicetalk.transport.api.HostAndPort)21 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)21 Matchers.is (org.hamcrest.Matchers.is)20 Nullable (javax.annotation.Nullable)16 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)15