Search in sources :

Example 1 with CompositeBuffer

use of io.servicetalk.buffer.api.CompositeBuffer in project servicetalk by apple.

the class ClientEffectiveStrategyTest method getResponse.

private String getResponse(ClientType clientType, StreamingHttpClient client) throws Exception {
    switch(clientType) {
        case Blocking:
            BlockingHttpClient blockingClient = client.asBlockingClient();
            return blockingClient.request(blockingClient.get("/")).payloadBody().toString(StandardCharsets.US_ASCII);
        case BlockingStreaming:
            BlockingStreamingHttpClient blockingStreamingClient = client.asBlockingStreamingClient();
            Supplier<CompositeBuffer> supplier = client.executionContext().bufferAllocator()::newCompositeBuffer;
            return StreamSupport.stream(blockingStreamingClient.request(blockingStreamingClient.get("/")).payloadBody().spliterator(), false).reduce((Buffer base, Buffer buffer) -> (base instanceof CompositeBuffer ? ((CompositeBuffer) base) : supplier.get().addBuffer(base)).addBuffer(buffer)).map(buffer -> buffer.toString(StandardCharsets.US_ASCII)).orElse("");
        case AsyncStreaming:
            return client.request(client.get("/")).flatMap(resp -> resp.payloadBody().collect(() -> client.executionContext().bufferAllocator().newCompositeBuffer(), CompositeBuffer::addBuffer)).toFuture().get().toString(StandardCharsets.US_ASCII);
        case Async:
            HttpClient httpClient = client.asClient();
            return httpClient.request(httpClient.get("/")).toFuture().get().payloadBody().toString(StandardCharsets.US_ASCII);
        default:
            fail("Unexpected client type " + clientType);
            /* NOTREACHED */
            return "failed";
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) ResponseData(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.ResponseData) StreamingHttpConnectionFilterFactory(io.servicetalk.http.api.StreamingHttpConnectionFilterFactory) LoadBalancer(io.servicetalk.client.api.LoadBalancer) ServiceDiscovererEvent(io.servicetalk.client.api.ServiceDiscovererEvent) AfterAll(org.junit.jupiter.api.AfterAll) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) EnumSet(java.util.EnumSet) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) ExecutionMode(org.junit.jupiter.api.parallel.ExecutionMode) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) FilterableStreamingHttpLoadBalancedConnection(io.servicetalk.http.api.FilterableStreamingHttpLoadBalancedConnection) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) HttpExecutionStrategies.offloadAll(io.servicetalk.http.api.HttpExecutionStrategies.offloadAll) ResponseMeta(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.ResponseMeta) RoundRobinLoadBalancerFactory(io.servicetalk.loadbalancer.RoundRobinLoadBalancerFactory) Queue(java.util.Queue) Assertions.fail(org.junit.jupiter.api.Assertions.fail) RequestPayloadSubscription(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.RequestPayloadSubscription) LoadBalancerFactory(io.servicetalk.client.api.LoadBalancerFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) HttpLoadBalancerFactory(io.servicetalk.http.api.HttpLoadBalancerFactory) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) HttpExecutionStrategies(io.servicetalk.http.api.HttpExecutionStrategies) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) HttpClient(io.servicetalk.http.api.HttpClient) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamSupport(java.util.stream.StreamSupport) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) Matchers(org.hamcrest.Matchers) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) Execution(org.junit.jupiter.api.parallel.Execution) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpClient(io.servicetalk.http.api.HttpClient) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient)

Example 2 with CompositeBuffer

use of io.servicetalk.buffer.api.CompositeBuffer in project servicetalk by apple.

the class HttpDataSourceTransformations method aggregatePayloadAndTrailers.

static Single<PayloadAndTrailers> aggregatePayloadAndTrailers(final DefaultPayloadInfo payloadInfo, final Publisher<?> payloadAndTrailers, final BufferAllocator allocator) {
    if (payloadAndTrailers == empty()) {
        payloadInfo.setEmpty(true).setMayHaveTrailersAndGenericTypeBuffer(false);
        return succeeded(EMPTY_PAYLOAD_AND_TRAILERS);
    }
    return payloadAndTrailers.collect(PayloadAndTrailers::new, (pair, nextItem) -> {
        if (nextItem instanceof Buffer) {
            try {
                Buffer buffer = (Buffer) nextItem;
                if (isAlwaysEmpty(pair.payload)) {
                    pair.payload = buffer;
                } else if (pair.payload instanceof CompositeBuffer) {
                    ((CompositeBuffer) pair.payload).addBuffer(buffer);
                } else {
                    Buffer oldBuffer = pair.payload;
                    pair.payload = allocator.newCompositeBuffer(MAX_VALUE).addBuffer(oldBuffer).addBuffer(buffer);
                }
            } catch (IllegalArgumentException cause) {
                BufferOverflowException ex = new BufferOverflowException();
                ex.initCause(cause);
                throw ex;
            }
        } else if (nextItem instanceof HttpHeaders) {
            pair.trailers = (HttpHeaders) nextItem;
        } else {
            throw new UnsupportedHttpChunkException(nextItem);
        }
        return pair;
    }).map(pair -> {
        if (isAlwaysEmpty(pair.payload)) {
            payloadInfo.setEmpty(true);
        }
        if (pair.trailers == null) {
            payloadInfo.setMayHaveTrailersAndGenericTypeBuffer(false);
        }
        return pair;
    });
}
Also used : AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) Publisher(io.servicetalk.concurrent.api.Publisher) BufferOverflowException(java.nio.BufferOverflowException) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) MAX_VALUE(java.lang.Integer.MAX_VALUE) TimeoutException(java.util.concurrent.TimeoutException) ConcurrentSubscription(io.servicetalk.concurrent.internal.ConcurrentSubscription) Publisher.empty(io.servicetalk.concurrent.api.Publisher.empty) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) SubscriberUtils.checkDuplicateSubscription(io.servicetalk.concurrent.internal.SubscriberUtils.checkDuplicateSubscription) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Objects.requireNonNull(java.util.Objects.requireNonNull) DelayedSubscription(io.servicetalk.concurrent.internal.DelayedSubscription) NoSuchElementException(java.util.NoSuchElementException) AtomicIntegerFieldUpdater.newUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater) Nullable(javax.annotation.Nullable) Single(io.servicetalk.concurrent.api.Single) PublisherOperator(io.servicetalk.concurrent.api.PublisherOperator) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) System.nanoTime(java.lang.System.nanoTime) BlockingIterable(io.servicetalk.concurrent.BlockingIterable) TimeUnit(java.util.concurrent.TimeUnit) Buffer(io.servicetalk.buffer.api.Buffer) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) Buffer(io.servicetalk.buffer.api.Buffer) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) BufferOverflowException(java.nio.BufferOverflowException)

Example 3 with CompositeBuffer

use of io.servicetalk.buffer.api.CompositeBuffer in project servicetalk by apple.

the class CancellableResources method postRsStreams.

@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
@Path("/rs-streams")
@POST
public Publisher<Buffer> postRsStreams(@QueryParam("subscribe") final boolean subscribe, final Publisher<Buffer> requestContent, @Context final ConnectionContext ctx) {
    final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
    final CompositeBuffer responseBuffer = allocator.newCompositeBuffer(2).addBuffer(allocator.fromAscii("GOT: "));
    // subscribe when it gets the response back from the router
    if (subscribe) {
        return from(responseBuffer.writeAscii(getContentAsString(requestContent)));
    } else {
        final AtomicBoolean first = new AtomicBoolean(true);
        return requestContent.map(c -> first.compareAndSet(true, false) ? responseBuffer.addBuffer(c) : c);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) POST(javax.ws.rs.POST)

Example 4 with CompositeBuffer

use of io.servicetalk.buffer.api.CompositeBuffer in project servicetalk by apple.

the class NettyChannelContentCodec method drainChannelQueueToSingleBuffer.

@Nullable
private static Buffer drainChannelQueueToSingleBuffer(final Queue<Object> queue, final BufferAllocator allocator) {
    if (queue.isEmpty()) {
        return null;
    }
    if (queue.size() == 1) {
        return newBufferFrom((ByteBuf) queue.poll());
    } else {
        int accumulateSize = 0;
        int components = 0;
        for (Object buffer : queue) {
            accumulateSize += ((ByteBuf) buffer).readableBytes();
            components++;
        }
        ByteBuf part;
        if (accumulateSize <= MAX_SIZE_FOR_MERGED_BUFFER) {
            // Try to merge everything together if total size is less than 1KiB (small chunks, ie. footer).
            // CompositeBuffer can require some additional work to write and may limit how much data we can
            // pass to writev (max of 1024 pointers), so if there are small chunks it may be better to combine them.
            Buffer merged = allocator.newBuffer();
            while ((part = (ByteBuf) queue.poll()) != null) {
                merged.writeBytes(newBufferFrom(part));
            }
            return merged;
        }
        CompositeBuffer composite = allocator.newCompositeBuffer(components);
        while ((part = (ByteBuf) queue.poll()) != null) {
            composite.addBuffer(newBufferFrom(part));
        }
        return composite;
    }
}
Also used : CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) Buffer(io.servicetalk.buffer.api.Buffer) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) ByteBuf(io.netty.buffer.ByteBuf) Nullable(javax.annotation.Nullable)

Example 5 with CompositeBuffer

use of io.servicetalk.buffer.api.CompositeBuffer in project servicetalk by apple.

the class ProtoDeserializerTest method multipleMessagesInCompositeBuffer.

@Test
void multipleMessagesInCompositeBuffer() throws IOException {
    final CompositeBuffer composite = DEFAULT_ALLOCATOR.newCompositeBuffer();
    Buffer msg = grpcBufferFor("Hello");
    while (msg.readableBytes() > 0) {
        composite.addBuffer(msg.readSlice(1));
    }
    composite.addBuffer(grpcBufferFor("Hello1"));
    List<String> deserialized = deserialize(composite);
    assertThat("Unexpected messages deserialized.", deserialized, contains("Hello", "Hello1"));
}
Also used : CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) Buffer(io.servicetalk.buffer.api.Buffer) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) Test(org.junit.jupiter.api.Test)

Aggregations

CompositeBuffer (io.servicetalk.buffer.api.CompositeBuffer)8 Buffer (io.servicetalk.buffer.api.Buffer)5 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)4 Nullable (javax.annotation.Nullable)3 Publisher (io.servicetalk.concurrent.api.Publisher)2 Single (io.servicetalk.concurrent.api.Single)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 ByteBuf (io.netty.buffer.ByteBuf)1 EMPTY_BUFFER (io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER)1 DEFAULT_ALLOCATOR (io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR)1 ConnectionFactory (io.servicetalk.client.api.ConnectionFactory)1 LoadBalancer (io.servicetalk.client.api.LoadBalancer)1 LoadBalancerFactory (io.servicetalk.client.api.LoadBalancerFactory)1 ServiceDiscovererEvent (io.servicetalk.client.api.ServiceDiscovererEvent)1 BlockingIterable (io.servicetalk.concurrent.BlockingIterable)1 BlockingIterator (io.servicetalk.concurrent.BlockingIterator)1 Subscriber (io.servicetalk.concurrent.PublisherSource.Subscriber)1