Search in sources :

Example 1 with BlockingStreamingHttpRequest

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

the class RequestResponseContextTest method testBlockingStreaming.

@Test
void testBlockingStreaming() throws Exception {
    setUp(Api.BlockingStreaming);
    String requestContextValue = randomString(10);
    BlockingStreamingHttpClient client = streamingHttpClient().asBlockingStreamingClient();
    BlockingStreamingHttpRequest request = client.get(SVC_ECHO);
    request.context().put(CLIENT_REQUEST_KEY, singletonList(requestContextValue));
    BlockingStreamingHttpResponse response = client.request(request);
    assertResponse(response.toStreamingResponse(), HTTP_1_1, OK, 0);
    assertContext(requestContextValue, request, response);
}
Also used : BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 2 with BlockingStreamingHttpRequest

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

the class BlockingStreamingHttpServiceTest method setRequestMessageBody.

@Test
void setRequestMessageBody() throws Exception {
    BlockingStreamingHttpClient client = context((ctx, request, response) -> {
        response.status(OK);
        try {
            HttpMessageBodyIterator<Buffer> reqItr = request.messageBody().iterator();
            StringBuilder sb = new StringBuilder();
            while (reqItr.hasNext()) {
                sb.append(requireNonNull(reqItr.next()).toString(UTF_8));
            }
            assertThat(sb.toString(), is(HELLO_WORLD));
            HttpHeaders trailers = reqItr.trailers();
            assertThat(trailers, notNullValue());
            assertThat(trailers.get(X_TOTAL_LENGTH).toString(), is(HELLO_WORLD_LENGTH));
        } catch (Throwable cause) {
            HttpPayloadWriter<String> payloadWriter = response.sendMetaData(appSerializerUtf8FixLen());
            payloadWriter.write(cause.toString());
            payloadWriter.close();
            return;
        }
        response.sendMetaData(appSerializerUtf8FixLen()).close();
    });
    BufferAllocator alloc = client.executionContext().bufferAllocator();
    BlockingStreamingHttpRequest req = client.get("/");
    req.setHeader(TRAILER, X_TOTAL_LENGTH);
    int split = HELLO_WORLD.length() / 2;
    final BlockingIterable<Buffer> reqIterable = BlockingIterables.from(asList(alloc.fromAscii(HELLO_WORLD.substring(0, split)), alloc.fromAscii(HELLO_WORLD.substring(split))));
    req.messageBody(() -> new HttpMessageBodyIterator<Buffer>() {

        private final BlockingIterator<Buffer> iterator = reqIterable.iterator();

        @Nullable
        private HttpHeaders trailers;

        private int totalLength;

        @Nullable
        @Override
        public HttpHeaders trailers() {
            if (trailers == null) {
                trailers = DefaultHttpHeadersFactory.INSTANCE.newTrailers();
                trailers.set(X_TOTAL_LENGTH, String.valueOf(totalLength));
            }
            return trailers;
        }

        @Override
        public boolean hasNext(final long timeout, final TimeUnit unit) throws TimeoutException {
            return iterator.hasNext(timeout, unit);
        }

        @Nullable
        @Override
        public Buffer next(final long timeout, final TimeUnit unit) throws TimeoutException {
            return addTotalLength(iterator.next(timeout, unit));
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Nullable
        @Override
        public Buffer next() {
            return addTotalLength(iterator.next());
        }

        @Override
        public void close() throws Exception {
            iterator.close();
        }

        @Nullable
        private Buffer addTotalLength(@Nullable Buffer buffer) {
            if (buffer != null) {
                totalLength += buffer.readableBytes();
            }
            return buffer;
        }
    });
    BlockingStreamingHttpResponse response = client.request(req);
    assertThat(response.status(), is(OK));
    assertThat(stream(response.payloadBody(appSerializerUtf8FixLen()).spliterator(), false).collect(Collectors.toList()), emptyIterable());
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) Nullable(javax.annotation.Nullable) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 3 with BlockingStreamingHttpRequest

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

the class DefaultGrpcClientCallFactory method newBlockingStreamingCall.

@Override
public <Req, Resp> BlockingStreamingClientCall<Req, Resp> newBlockingStreamingCall(final MethodDescriptor<Req, Resp> methodDescriptor, final BufferDecoderGroup decompressors) {
    GrpcStreamingSerializer<Req> serializerIdentity = streamingSerializer(methodDescriptor);
    GrpcStreamingDeserializer<Resp> deserializerIdentity = streamingDeserializer(methodDescriptor);
    List<GrpcStreamingDeserializer<Resp>> deserializers = streamingDeserializers(methodDescriptor, decompressors.decoders());
    CharSequence acceptedEncoding = decompressors.advertisedMessageEncoding();
    CharSequence requestContentType = grpcContentType(methodDescriptor.requestDescriptor().serializerDescriptor().contentType());
    CharSequence responseContentType = grpcContentType(methodDescriptor.responseDescriptor().serializerDescriptor().contentType());
    final BlockingStreamingHttpClient client = streamingHttpClient.asBlockingStreamingClient();
    return (metadata, request) -> {
        Duration timeout = timeoutForRequest(metadata.timeout());
        GrpcStreamingSerializer<Req> serializer = streamingSerializer(methodDescriptor, serializerIdentity, metadata.requestCompressor());
        String mdPath = methodDescriptor.httpPath();
        BlockingStreamingHttpRequest httpRequest = client.post(UNKNOWN_PATH.equals(mdPath) ? metadata.path() : mdPath);
        initRequest(httpRequest, requestContentType, serializer.messageEncoding(), acceptedEncoding, timeout);
        httpRequest.payloadBody(serializer.serialize(request, streamingHttpClient.executionContext().bufferAllocator()));
        try {
            assignStrategy(httpRequest, metadata);
            final BlockingStreamingHttpResponse response = client.request(httpRequest);
            return validateResponseAndGetPayload(response.toStreamingResponse(), responseContentType, client.executionContext().bufferAllocator(), readGrpcMessageEncodingRaw(response.headers(), deserializerIdentity, deserializers, GrpcStreamingDeserializer::messageEncoding)).toIterable();
        } 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) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) Duration(java.time.Duration) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse)

Example 4 with BlockingStreamingHttpRequest

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

the class AsyncContextHttpFilterVerifier method verifyServerFilterAsyncContextVisibility.

/**
 * Verify that all interactions with the request/response and message-body from a request that goes through
 * the provided {@link StreamingHttpServiceFilterFactory} filter, have valid visibility of the {@link AsyncContext}.
 *
 * @param filter The {@link StreamingHttpServiceFilterFactory} filter to verify.
 */
public static void verifyServerFilterAsyncContextVisibility(final StreamingHttpServiceFilterFactory filter) throws Exception {
    final BlockingQueue<Throwable> errors = new LinkedBlockingDeque<>();
    final List<String> payload = singletonList("Hello World");
    final ServerContext serverContext = forAddress(localAddress(0)).appendServiceFilter(asyncContextAssertionFilter(errors)).appendServiceFilter(filter).listenStreamingAndAwait(asyncContextRequestHandler(errors));
    final BlockingStreamingHttpClient client = forSingleAddress(serverHostAndPort(serverContext)).buildBlockingStreaming();
    final BlockingStreamingHttpRequest request = client.post("/test").payloadBody(payload, appSerializerUtf8FixLen());
    final BlockingStreamingHttpResponse resp = client.request(request);
    assertThat(resp.status(), is(OK));
    Iterator<String> itr = resp.payloadBody(appSerializerUtf8FixLen()).iterator();
    assertThat(itr.hasNext(), is(true));
    assertThat(itr.next(), is(payload.get(0)));
    assertThat(itr.hasNext(), is(false));
    assertNoAsyncErrors(errors);
}
Also used : BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ServerContext(io.servicetalk.transport.api.ServerContext) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse)

Aggregations

BlockingStreamingHttpClient (io.servicetalk.http.api.BlockingStreamingHttpClient)4 BlockingStreamingHttpRequest (io.servicetalk.http.api.BlockingStreamingHttpRequest)4 BlockingStreamingHttpResponse (io.servicetalk.http.api.BlockingStreamingHttpResponse)4 TimeUnit (java.util.concurrent.TimeUnit)2 Nullable (javax.annotation.Nullable)2 Buffer (io.servicetalk.buffer.api.Buffer)1 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)1 BlockingIterator (io.servicetalk.concurrent.BlockingIterator)1 AsyncContext (io.servicetalk.concurrent.api.AsyncContext)1 Completable (io.servicetalk.concurrent.api.Completable)1 Publisher (io.servicetalk.concurrent.api.Publisher)1 BlockingIterables.singletonBlockingIterable (io.servicetalk.concurrent.internal.BlockingIterables.singletonBlockingIterable)1 BufferDecoder (io.servicetalk.encoding.api.BufferDecoder)1 BufferDecoderGroup (io.servicetalk.encoding.api.BufferDecoderGroup)1 BufferEncoder (io.servicetalk.encoding.api.BufferEncoder)1 Identity.identityEncoder (io.servicetalk.encoding.api.Identity.identityEncoder)1 GRPC_CONTENT_TYPE_PROTO_SUFFIX (io.servicetalk.grpc.api.GrpcHeaderValues.GRPC_CONTENT_TYPE_PROTO_SUFFIX)1 DefaultMethodDescriptor (io.servicetalk.grpc.api.GrpcUtils.DefaultMethodDescriptor)1 GrpcUtils.decompressors (io.servicetalk.grpc.api.GrpcUtils.decompressors)1 GrpcUtils.defaultToInt (io.servicetalk.grpc.api.GrpcUtils.defaultToInt)1