Search in sources :

Example 16 with Publisher

use of io.servicetalk.concurrent.api.Publisher in project servicetalk by apple.

the class DefaultContainerResponseWriter method sendResponse.

private void sendResponse(final long contentLength, @Nullable final Publisher<Buffer> content, final ContainerResponse containerResponse) {
    final HttpResponseStatus status = getStatus(containerResponse);
    final StreamingHttpResponse response;
    if (content != null && !isHeadRequest()) {
        final HttpExecutionStrategy executionStrategy = getResponseExecutionStrategy(request);
        // TODO(scott): use request factory methods that accept a payload body to avoid overhead of payloadBody.
        final Publisher<Buffer> payloadBody = (executionStrategy != null && executionStrategy.isSendOffloaded() ? content.subscribeOn(serviceCtx.executionContext().executor(), IoThreadFactory.IoThread::currentThreadIsIoThread) : content).beforeCancel(// Cleanup internal state if server cancels response body
        this::cancelResponse);
        response = responseFactory.newResponse(status).version(protocolVersion).payloadBody(payloadBody);
    } else {
        response = responseFactory.newResponse(status).version(protocolVersion);
    }
    final HttpHeaders headers = response.headers();
    // If we use HTTP/2 protocol all headers MUST be in lower case
    final boolean isH2 = response.version().major() == 2;
    containerResponse.getHeaders().forEach((k, vs) -> vs.forEach(v -> {
        headers.add(isH2 ? k.toLowerCase() : k, v == null ? emptyAsciiString() : asCharSequence(v));
    }));
    if (!headers.contains(CONTENT_LENGTH)) {
        if (contentLength == UNKNOWN_RESPONSE_LENGTH) {
            // We can omit Transfer-Encoding for HEAD per https://tools.ietf.org/html/rfc7231#section-4.3.2
            if (!isHeadRequest() && !HTTP_1_0.equals(protocolVersion)) {
                headers.set(TRANSFER_ENCODING, CHUNKED);
            }
        } else {
            headers.set(CONTENT_LENGTH, contentLength == 0 ? ZERO : Long.toString(contentLength));
            headers.removeIgnoreCase(TRANSFER_ENCODING, CHUNKED);
        }
    }
    responseSubscriber.onSuccess(response);
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) Subscriber(io.servicetalk.concurrent.SingleSource.Subscriber) LoggerFactory(org.slf4j.LoggerFactory) HttpHeaders(io.servicetalk.http.api.HttpHeaders) Cancellable(io.servicetalk.concurrent.Cancellable) RequestProperties.getResponseExecutionStrategy(io.servicetalk.http.router.jersey.internal.RequestProperties.getResponseExecutionStrategy) ConnectableBufferOutputStream(io.servicetalk.concurrent.api.internal.ConnectableBufferOutputStream) RequestProperties.getResponseBufferPublisher(io.servicetalk.http.router.jersey.internal.RequestProperties.getResponseBufferPublisher) ContainerException(org.glassfish.jersey.server.ContainerException) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) RequestProperties.getRequestCancellable(io.servicetalk.http.router.jersey.internal.RequestProperties.getRequestCancellable) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) HttpProtocolVersion(io.servicetalk.http.api.HttpProtocolVersion) CharSequences.emptyAsciiString(io.servicetalk.buffer.api.CharSequences.emptyAsciiString) AtomicIntegerFieldUpdater.newUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater) Status(javax.ws.rs.core.Response.Status) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) Nullable(javax.annotation.Nullable) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) IOException(java.io.IOException) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) TimeUnit(java.util.concurrent.TimeUnit) StatusType(javax.ws.rs.core.Response.StatusType) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) HEAD(javax.ws.rs.HttpMethod.HEAD) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Function.identity(java.util.function.Function.identity) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) Arrays.stream(java.util.Arrays.stream) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) System.arraycopy(java.lang.System.arraycopy) HTTP_1_0(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_0) HttpHeaders(io.servicetalk.http.api.HttpHeaders) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 17 with Publisher

use of io.servicetalk.concurrent.api.Publisher in project servicetalk by apple.

the class H2PriorKnowledgeFeatureParityTest method clientRespectsSettingsFrame.

@ParameterizedTest(name = "{displayName} [{index}] client={0}, h2PriorKnowledge={1}")
@MethodSource("clientExecutors")
void clientRespectsSettingsFrame(HttpTestExecutionStrategy strategy, boolean h2PriorKnowledge) throws Exception {
    setUp(strategy, h2PriorKnowledge);
    assumeTrue(h2PriorKnowledge, "Only HTTP/2 supports SETTINGS frames");
    int expectedMaxConcurrent = 1;
    BlockingQueue<FilterableStreamingHttpConnection> connectionQueue = new LinkedBlockingQueue<>();
    BlockingQueue<Publisher<? extends ConsumableEvent<Integer>>> maxConcurrentPubQueue = new LinkedBlockingQueue<>();
    AtomicReference<Channel> serverParentChannelRef = new AtomicReference<>();
    CountDownLatch serverChannelLatch = new CountDownLatch(1);
    CountDownLatch serverSettingsAckLatch = new CountDownLatch(2);
    serverAcceptorChannel = bindH2Server(serverEventLoopGroup, new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(final Channel ch) {
            ch.pipeline().addLast(new EchoHttp2Handler());
        }
    }, parentPipeline -> parentPipeline.addLast(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (serverParentChannelRef.compareAndSet(null, ctx.channel())) {
                serverChannelLatch.countDown();
            }
            super.channelActive(ctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof Http2SettingsAckFrame) {
                serverSettingsAckLatch.countDown();
            }
            super.channelRead(ctx, msg);
        }
    }), identity());
    InetSocketAddress serverAddress = (InetSocketAddress) serverAcceptorChannel.localAddress();
    try (StreamingHttpClient client = forSingleAddress(HostAndPort.of(serverAddress)).protocols(h2PriorKnowledge ? h2Default() : h1Default()).executionStrategy(clientExecutionStrategy).appendConnectionFilter(conn -> new TestConnectionFilter(conn, connectionQueue, maxConcurrentPubQueue)).buildStreaming()) {
        Processor<Buffer, Buffer> requestPayload = newProcessor();
        client.request(client.post("/0").payloadBody(fromSource(requestPayload))).toFuture().get();
        serverChannelLatch.await();
        Channel serverParentChannel = serverParentChannelRef.get();
        serverParentChannel.writeAndFlush(new DefaultHttp2SettingsFrame(new Http2Settings().maxConcurrentStreams(expectedMaxConcurrent))).sync();
        Iterator<? extends ConsumableEvent<Integer>> maxItr = maxConcurrentPubQueue.take().toIterable().iterator();
        // Verify that the initial maxConcurrency value is the default number
        assertThat("No initial maxConcurrency value", maxItr.hasNext(), is(true));
        ConsumableEvent<Integer> next = maxItr.next();
        assertThat(next, is(notNullValue()));
        assertThat("First event is not the default", next.event(), is(SMALLEST_MAX_CONCURRENT_STREAMS));
        // We previously made a request, and intentionally didn't complete the request body. We want to verify
        // that we have received the SETTINGS frame reducing the total number of streams to 1.
        assertThat("No maxConcurrency value received", maxItr.hasNext(), is(true));
        next = maxItr.next();
        assertThat(next, is(notNullValue()));
        assertThat("maxConcurrency did not change to the expected value", next.event(), is(expectedMaxConcurrent));
        // Wait for a server to receive a settings ack
        serverSettingsAckLatch.await();
        // After this point we want to issue a new request and verify that client selects a new connection.
        Processor<Buffer, Buffer> requestPayload2 = newProcessor();
        client.request(client.post("/1").payloadBody(fromSource(requestPayload2))).toFuture().get();
        // We expect 2 connections to be created.
        assertNotSame(connectionQueue.take(), connectionQueue.take());
        requestPayload.onComplete();
        requestPayload2.onComplete();
    }
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) UnaryOperator.identity(java.util.function.UnaryOperator.identity) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) SingleSource(io.servicetalk.concurrent.SingleSource) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) UnaryOperator(java.util.function.UnaryOperator) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) Disabled(org.junit.jupiter.api.Disabled) Matchers.hasItems(org.hamcrest.Matchers.hasItems) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) H2StreamResetException(io.servicetalk.http.netty.NettyHttp2ExceptionUtils.H2StreamResetException) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) HttpRequest(io.servicetalk.http.api.HttpRequest) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Matchers.nullValue(org.hamcrest.Matchers.nullValue) HttpCookiePair(io.servicetalk.http.api.HttpCookiePair) EXPECT(io.servicetalk.http.api.HttpHeaderNames.EXPECT) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) PrintWriter(java.io.PrintWriter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) DefaultHttp2SettingsFrame(io.netty.handler.codec.http2.DefaultHttp2SettingsFrame) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) HttpResponse(io.servicetalk.http.api.HttpResponse) Http2SettingsAckFrame(io.netty.handler.codec.http2.Http2SettingsAckFrame) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) POST(io.servicetalk.http.api.HttpRequestMethod.POST) BlockingQueue(java.util.concurrent.BlockingQueue) ChannelPipeline(io.netty.channel.ChannelPipeline) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) Assertions.assertNotSame(org.junit.jupiter.api.Assertions.assertNotSame) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HttpSetCookie(io.servicetalk.http.api.HttpSetCookie) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) COOKIE(io.servicetalk.http.api.HttpHeaderNames.COOKIE) Matchers.is(org.hamcrest.Matchers.is) CONTENT_TYPE(io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Processor(io.servicetalk.concurrent.PublisherSource.Processor) BuilderUtils.serverChannel(io.servicetalk.transport.netty.internal.BuilderUtils.serverChannel) TRAILER(io.netty.handler.codec.http.HttpHeaderNames.TRAILER) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) HttpHeaders(io.servicetalk.http.api.HttpHeaders) ConsumableEvent(io.servicetalk.client.api.ConsumableEvent) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) MAX_CONCURRENCY(io.servicetalk.http.api.HttpEventKey.MAX_CONCURRENCY) HeaderUtils.isTransferEncodingChunked(io.servicetalk.http.api.HeaderUtils.isTransferEncodingChunked) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) Processors(io.servicetalk.concurrent.api.Processors) BiConsumer(java.util.function.BiConsumer) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nullable(javax.annotation.Nullable) SMALLEST_MAX_CONCURRENT_STREAMS(io.netty.handler.codec.http2.Http2CodecUtil.SMALLEST_MAX_CONCURRENT_STREAMS) DEFAULT(io.servicetalk.http.netty.HttpTestExecutionStrategy.DEFAULT) Single(io.servicetalk.concurrent.api.Single) StringWriter(java.io.StringWriter) Completable(io.servicetalk.concurrent.api.Completable) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) IOException(java.io.IOException) ReservedBlockingHttpConnection(io.servicetalk.http.api.ReservedBlockingHttpConnection) OK(io.servicetalk.http.api.HttpResponseStatus.OK) GET(io.servicetalk.http.api.HttpRequestMethod.GET) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) Matchers.emptyString(org.hamcrest.Matchers.emptyString) Http2FrameCodecBuilder(io.netty.handler.codec.http2.Http2FrameCodecBuilder) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2DataFrame(io.netty.handler.codec.http2.Http2DataFrame) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) PublisherSource(io.servicetalk.concurrent.PublisherSource) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpEventKey(io.servicetalk.http.api.HttpEventKey) List(java.util.List) ContextMap(io.servicetalk.context.api.ContextMap) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Writer(java.io.Writer) Queue(java.util.Queue) CONTINUE(io.servicetalk.http.api.HttpHeaderValues.CONTINUE) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) Http2Exception(io.servicetalk.http.api.Http2Exception) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpProtocolConfigs.h2Default(io.servicetalk.http.netty.HttpProtocolConfigs.h2Default) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) ServerContext(io.servicetalk.transport.api.ServerContext) Iterator(java.util.Iterator) EXPECTATION_FAILED(io.servicetalk.http.api.HttpResponseStatus.EXPECTATION_FAILED) NettyIoExecutors.createIoExecutor(io.servicetalk.transport.netty.internal.NettyIoExecutors.createIoExecutor) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Processors.newPublisherProcessor(io.servicetalk.concurrent.api.Processors.newPublisherProcessor) Consumer(java.util.function.Consumer) Matchers.emptyIterable(org.hamcrest.Matchers.emptyIterable) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) NO_OFFLOAD(io.servicetalk.http.netty.HttpTestExecutionStrategy.NO_OFFLOAD) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandler(io.netty.channel.ChannelHandler) SET_COOKIE(io.servicetalk.http.api.HttpHeaderNames.SET_COOKIE) DefaultHttpCookiePair(io.servicetalk.http.api.DefaultHttpCookiePair) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2SettingsAckFrame(io.netty.handler.codec.http2.Http2SettingsAckFrame) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ConsumableEvent(io.servicetalk.client.api.ConsumableEvent) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Settings(io.netty.handler.codec.http2.Http2Settings) Buffer(io.servicetalk.buffer.api.Buffer) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) DefaultHttp2SettingsFrame(io.netty.handler.codec.http2.DefaultHttp2SettingsFrame) BuilderUtils.serverChannel(io.servicetalk.transport.netty.internal.BuilderUtils.serverChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(io.servicetalk.concurrent.api.Publisher) CountDownLatch(java.util.concurrent.CountDownLatch) H2StreamResetException(io.servicetalk.http.netty.NettyHttp2ExceptionUtils.H2StreamResetException) IOException(java.io.IOException) Http2Exception(io.servicetalk.http.api.Http2Exception) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 18 with Publisher

use of io.servicetalk.concurrent.api.Publisher in project servicetalk by apple.

the class DefaultPartitionedHttpClientBuilder method buildStreaming.

@Override
public StreamingHttpClient buildStreaming() {
    final HttpClientBuildContext<U, R> buildContext = builderTemplate.copyBuildCtx();
    final HttpExecutionContext executionContext = buildContext.builder.build().executionContext();
    BiIntFunction<Throwable, ? extends Completable> sdRetryStrategy = serviceDiscovererRetryStrategy;
    if (sdRetryStrategy == null) {
        sdRetryStrategy = retryWithConstantBackoffDeltaJitter(__ -> true, SD_RETRY_STRATEGY_INIT_DURATION, SD_RETRY_STRATEGY_JITTER, executionContext.executor());
    }
    ServiceDiscoverer<U, R, PartitionedServiceDiscovererEvent<R>> psd = new DefaultSingleAddressHttpClientBuilder.RetryingServiceDiscoverer<>(serviceDiscoverer, sdRetryStrategy);
    final PartitionedClientFactory<U, R, FilterableStreamingHttpClient> clientFactory = (pa, sd) -> {
        // build new context, user may have changed anything on the builder from the filter
        DefaultSingleAddressHttpClientBuilder<U, R> builder = buildContext.builder.copyBuildCtx().builder;
        builder.serviceDiscoverer(sd);
        clientFilterFunction.configureForPartition(pa, builder);
        if (clientInitializer != null) {
            clientInitializer.initialize(pa, builder);
        }
        return builder.buildStreaming();
    };
    final Publisher<PartitionedServiceDiscovererEvent<R>> psdEvents = psd.discover(buildContext.address()).flatMapConcatIterable(identity());
    DefaultPartitionedStreamingHttpClientFilter<U, R> partitionedClient = new DefaultPartitionedStreamingHttpClientFilter<>(psdEvents, serviceDiscoveryMaxQueueSize, clientFactory, partitionAttributesBuilderFactory, defaultReqRespFactory(buildContext.httpConfig().asReadOnly(), executionContext.bufferAllocator()), executionContext, partitionMapFactory);
    HttpExecutionStrategy computedStrategy = buildContext.builder.computeChainStrategy(executionContext.executionStrategy());
    LOGGER.debug("Client created with base strategy {} → computed strategy {}", executionContext.executionStrategy(), computedStrategy);
    return new FilterableClientToClient(partitionedClient, computedStrategy);
}
Also used : FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) Publisher(io.servicetalk.concurrent.api.Publisher) PartitionMapFactory(io.servicetalk.client.api.partition.PartitionMapFactory) LoggerFactory(org.slf4j.LoggerFactory) ClientGroup(io.servicetalk.client.api.ClientGroup) Function(java.util.function.Function) SD_RETRY_STRATEGY_JITTER(io.servicetalk.http.netty.DefaultSingleAddressHttpClientBuilder.SD_RETRY_STRATEGY_JITTER) FilterableReservedStreamingHttpConnection(io.servicetalk.http.api.FilterableReservedStreamingHttpConnection) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) SD_RETRY_STRATEGY_INIT_DURATION(io.servicetalk.http.netty.DefaultSingleAddressHttpClientBuilder.SD_RETRY_STRATEGY_INIT_DURATION) DefaultSingleAddressHttpClientBuilder.defaultReqRespFactory(io.servicetalk.http.netty.DefaultSingleAddressHttpClientBuilder.defaultReqRespFactory) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) Executor(io.servicetalk.concurrent.api.Executor) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Nullable(javax.annotation.Nullable) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) RetryStrategies.retryWithConstantBackoffDeltaJitter(io.servicetalk.concurrent.api.RetryStrategies.retryWithConstantBackoffDeltaJitter) PartitionedClientFactory(io.servicetalk.client.api.internal.DefaultPartitionedClientGroup.PartitionedClientFactory) HttpClientBuildContext(io.servicetalk.http.netty.DefaultSingleAddressHttpClientBuilder.HttpClientBuildContext) Logger(org.slf4j.Logger) UnknownPartitionException(io.servicetalk.client.api.partition.UnknownPartitionException) PartitionAttributesBuilder(io.servicetalk.client.api.partition.PartitionAttributesBuilder) ListenableAsyncCloseable(io.servicetalk.concurrent.api.ListenableAsyncCloseable) PartitionedHttpClientBuilder(io.servicetalk.http.api.PartitionedHttpClientBuilder) StreamingHttpRequestResponseFactory(io.servicetalk.http.api.StreamingHttpRequestResponseFactory) Single.defer(io.servicetalk.concurrent.api.Single.defer) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) ServiceDiscoverer(io.servicetalk.client.api.ServiceDiscoverer) PartitionedServiceDiscovererEvent(io.servicetalk.client.api.partition.PartitionedServiceDiscovererEvent) HttpRequestMetaData(io.servicetalk.http.api.HttpRequestMetaData) IoExecutor(io.servicetalk.transport.api.IoExecutor) PartitionAttributes(io.servicetalk.client.api.partition.PartitionAttributes) ClosedPartitionException(io.servicetalk.client.api.partition.ClosedPartitionException) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) DefaultPartitionedClientGroup(io.servicetalk.client.api.internal.DefaultPartitionedClientGroup) PowerSetPartitionMapFactory(io.servicetalk.client.api.internal.partition.PowerSetPartitionMapFactory) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Single.failed(io.servicetalk.concurrent.api.Single.failed) Function.identity(java.util.function.Function.identity) AsyncCloseables.emptyAsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseables.emptyAsyncCloseable) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) BiIntFunction(io.servicetalk.concurrent.api.BiIntFunction) PartitionHttpClientBuilderConfigurator(io.servicetalk.http.api.PartitionHttpClientBuilderConfigurator) SD_RETRY_STRATEGY_JITTER(io.servicetalk.http.netty.DefaultSingleAddressHttpClientBuilder.SD_RETRY_STRATEGY_JITTER) PartitionedServiceDiscovererEvent(io.servicetalk.client.api.partition.PartitionedServiceDiscovererEvent) HttpExecutionContext(io.servicetalk.http.api.HttpExecutionContext) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy)

Example 19 with Publisher

use of io.servicetalk.concurrent.api.Publisher in project servicetalk by apple.

the class HttpReporter method initReporter.

private PublisherSource.Processor<Span, Span> initReporter(final Builder builder, final HttpClient client) {
    final PublisherSource.Processor<Span, Span> buffer;
    SpanBytesEncoder spanEncoder = builder.codec.spanBytesEncoder();
    final BufferAllocator allocator = client.executionContext().bufferAllocator();
    final Publisher<Buffer> spans;
    if (!builder.batchingEnabled) {
        buffer = newPublisherProcessorDropHeadOnOverflow(builder.maxConcurrentReports);
        spans = fromSource(buffer).map(span -> allocator.wrap(spanEncoder.encodeList(Collections.singletonList(span))));
    } else {
        // As we send maxConcurrentReports number of parallel requests, each with roughly batchSizeHint number of
        // spans, we hold a maximum of that many Spans in-memory that we can send in parallel to the collector.
        buffer = newPublisherProcessorDropHeadOnOverflow(builder.batchSizeHint * builder.maxConcurrentReports);
        spans = fromSource(buffer).buffer(forCountOrTime(builder.batchSizeHint, builder.maxBatchDuration, () -> new ListAccumulator(builder.batchSizeHint), client.executionContext().executor())).filter(accumulate -> !accumulate.isEmpty()).map(bufferedSpans -> allocator.wrap(spanEncoder.encodeList(bufferedSpans)));
    }
    final CompletableSource.Processor spansTerminated = newCompletableProcessor();
    toSource(spans.flatMapCompletable(encodedSpansReporter(client, builder.codec), builder.maxConcurrentReports)).subscribe(spansTerminated);
    closeable.prepend(toAsyncCloseable(graceful -> {
        closeInitiated = true;
        try {
            buffer.onComplete();
        } catch (Throwable t) {
            LOGGER.error("Failed to dispose request buffer. Ignoring.", t);
        }
        return graceful ? fromSource(spansTerminated) : completed();
    }));
    return buffer;
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) APPLICATION_JSON(io.servicetalk.http.api.HttpHeaderValues.APPLICATION_JSON) Publisher(io.servicetalk.concurrent.api.Publisher) LoggerFactory(org.slf4j.LoggerFactory) Span(zipkin2.Span) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) Duration.ofSeconds(java.time.Duration.ofSeconds) Function(java.util.function.Function) ArrayList(java.util.ArrayList) SourceAdapters.fromSource(io.servicetalk.concurrent.api.SourceAdapters.fromSource) Duration(java.time.Duration) Objects.requireNonNull(java.util.Objects.requireNonNull) Component(zipkin2.Component) SpanBytesEncoder(zipkin2.codec.SpanBytesEncoder) HttpClient(io.servicetalk.http.api.HttpClient) AsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseable) Reporter(zipkin2.reporter.Reporter) Nonnull(javax.annotation.Nonnull) Processors.newCompletableProcessor(io.servicetalk.concurrent.api.Processors.newCompletableProcessor) Accumulator(io.servicetalk.concurrent.api.BufferStrategy.Accumulator) Processors.newPublisherProcessorDropHeadOnOverflow(io.servicetalk.concurrent.api.Processors.newPublisherProcessorDropHeadOnOverflow) Logger(org.slf4j.Logger) FutureUtils.awaitTermination(io.servicetalk.concurrent.internal.FutureUtils.awaitTermination) PublisherSource(io.servicetalk.concurrent.PublisherSource) OK(zipkin2.CheckResult.OK) Completable(io.servicetalk.concurrent.api.Completable) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) CheckResult.failed(zipkin2.CheckResult.failed) BufferStrategies.forCountOrTime(io.servicetalk.concurrent.api.BufferStrategies.forCountOrTime) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) CheckResult(zipkin2.CheckResult) AsyncCloseables.toAsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseables.toAsyncCloseable) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) CompletableSource(io.servicetalk.concurrent.CompletableSource) SUCCESSFUL_2XX(io.servicetalk.http.api.HttpResponseStatus.StatusClass.SUCCESSFUL_2XX) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Collections(java.util.Collections) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) PublisherSource(io.servicetalk.concurrent.PublisherSource) SpanBytesEncoder(zipkin2.codec.SpanBytesEncoder) CompletableSource(io.servicetalk.concurrent.CompletableSource) Span(zipkin2.Span) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator)

Example 20 with Publisher

use of io.servicetalk.concurrent.api.Publisher in project servicetalk by apple.

the class AfterErrorTest method testCallbackThrowsError.

@Override
@Test
void testCallbackThrowsError() {
    DeliberateException srcEx = new DeliberateException();
    doError(Publisher.<String>failed(srcEx), t -> {
        throw DELIBERATE_EXCEPTION;
    }).subscribe(subscriber);
    assertThat(subscriber.awaitOnError(), sameInstance(srcEx));
}
Also used : Test(org.junit.jupiter.api.Test) Consumer(java.util.function.Consumer) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) Publisher(io.servicetalk.concurrent.api.Publisher) PublisherSource(io.servicetalk.concurrent.PublisherSource) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) Test(org.junit.jupiter.api.Test)

Aggregations

Publisher (io.servicetalk.concurrent.api.Publisher)29 Buffer (io.servicetalk.buffer.api.Buffer)14 Single (io.servicetalk.concurrent.api.Single)14 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)13 Test (org.junit.jupiter.api.Test)13 Completable (io.servicetalk.concurrent.api.Completable)12 PublisherSource (io.servicetalk.concurrent.PublisherSource)11 Collection (java.util.Collection)11 SourceAdapters.toSource (io.servicetalk.concurrent.api.SourceAdapters.toSource)10 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)10 Matchers.is (org.hamcrest.Matchers.is)10 Subscription (io.servicetalk.concurrent.PublisherSource.Subscription)9 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)9 DEFAULT_ALLOCATOR (io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR)8 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)8 Executor (io.servicetalk.concurrent.api.Executor)8 HttpHeaders (io.servicetalk.http.api.HttpHeaders)8