Search in sources :

Example 6 with ConnectionContext

use of io.servicetalk.transport.api.ConnectionContext in project servicetalk by apple.

the class AbstractLBHttpConnectionFactory method newConnection.

@Override
public final Single<LoadBalancedStreamingHttpConnection> newConnection(final ResolvedAddress resolvedAddress, @Nullable final ContextMap context, @Nullable final TransportObserver observer) {
    return filterableConnectionFactory.newConnection(resolvedAddress, context, observer).map(conn -> {
        FilterableStreamingHttpConnection filteredConnection = connectionFilterFunction != null ? connectionFilterFunction.create(conn) : conn;
        ConnectionContext ctx = filteredConnection.connectionContext();
        Completable onClosing;
        if (ctx instanceof NettyConnectionContext) {
            // bondolo - I don't believe this is necessary, always the same as filteredConnection.onClose()
            // perhaps this is only needed for testing where the mock doesn't implement onClose()?
            onClosing = ((NettyConnectionContext) ctx).onClosing();
        } else {
            onClosing = filteredConnection.onClose();
        }
        final Publisher<? extends ConsumableEvent<Integer>> maxConcurrency = filteredConnection.transportEventStream(MAX_CONCURRENCY);
        final ReservableRequestConcurrencyController concurrencyController = newConcurrencyController(maxConcurrency, onClosing);
        return new LoadBalancedStreamingHttpConnection(protocolBinding.apply(filteredConnection), concurrencyController, connectStrategy instanceof HttpExecutionStrategy ? (HttpExecutionStrategy) connectStrategy : HttpExecutionStrategies.offloadNone());
    });
}
Also used : NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Completable(io.servicetalk.concurrent.api.Completable) ReservableRequestConcurrencyController(io.servicetalk.client.api.internal.ReservableRequestConcurrencyController) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy)

Example 7 with ConnectionContext

use of io.servicetalk.transport.api.ConnectionContext in project servicetalk by apple.

the class ServerGracefulConnectionClosureHandlingTest method setUp.

@BeforeEach
void setUp() throws Exception {
    AtomicReference<Runnable> serverClose = new AtomicReference<>();
    serverContext = forAddress(localAddress(0)).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(offloadNone()).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

        @Override
        public Completable accept(final ConnectionContext context) {
            ((NettyHttpServerConnection) context).onClosing().whenFinally(serverConnectionClosing::countDown).subscribe();
            context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
            return completed();
        }
    }).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok().addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length())).payloadBody(request.payloadBody().ignoreElements().concat(from(RESPONSE_CONTENT)), RAW_STRING_SERIALIZER).transformMessageBody(payload -> payload.whenFinally(serverClose.get()))));
    serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
    serverClose.set(() -> serverContext.closeAsyncGracefully().subscribe());
    serverAddress = (InetSocketAddress) serverContext.listenAddress();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Socket(java.net.Socket) HttpSerializers.stringStreamingSerializer(io.servicetalk.http.api.HttpSerializers.stringStreamingSerializer) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) OutputStream(java.io.OutputStream) NettyHttpServerConnection(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerConnection) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Completable(io.servicetalk.concurrent.api.Completable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) String.valueOf(java.lang.String.valueOf) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Matchers.is(org.hamcrest.Matchers.is) HttpStreamingSerializer(io.servicetalk.http.api.HttpStreamingSerializer) InputStream(java.io.InputStream) Completable(io.servicetalk.concurrent.api.Completable) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 8 with ConnectionContext

use of io.servicetalk.transport.api.ConnectionContext in project servicetalk by apple.

the class AbstractLBHttpConnectionFactory method newConnection.

@Override
public final Single<LoadBalancedStreamingHttpConnection> newConnection(final ResolvedAddress resolvedAddress, @Nullable final TransportObserver observer) {
    return filterableConnectionFactory.newConnection(resolvedAddress, observer).map(conn -> {
        FilterableStreamingHttpConnection filteredConnection = connectionFilterFunction != null ? connectionFilterFunction.create(conn) : conn;
        ConnectionContext ctx = filteredConnection.connectionContext();
        Completable onClosing;
        if (ctx instanceof NettyConnectionContext) {
            // bondolo - I don't believe this is necessary, always the same as filteredConnection.onClose()
            // perhaps this is only needed for testing where the mock doesn't implement onClose()?
            onClosing = ((NettyConnectionContext) ctx).onClosing();
        } else {
            onClosing = filteredConnection.onClose();
        }
        final Publisher<? extends ConsumableEvent<Integer>> maxConcurrency = filteredConnection.transportEventStream(MAX_CONCURRENCY);
        final ReservableRequestConcurrencyController concurrencyController = newConcurrencyController(maxConcurrency, onClosing);
        return new LoadBalancedStreamingHttpConnection(protocolBinding.apply(filteredConnection), concurrencyController, connectStrategy instanceof HttpExecutionStrategy ? (HttpExecutionStrategy) connectStrategy : HttpExecutionStrategies.offloadNone());
    });
}
Also used : NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Completable(io.servicetalk.concurrent.api.Completable) ReservableRequestConcurrencyController(io.servicetalk.client.api.internal.ReservableRequestConcurrencyController) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy)

Example 9 with ConnectionContext

use of io.servicetalk.transport.api.ConnectionContext in project FrameworkBenchmarks by TechEmpower.

the class Server method main.

public static void main(String[] args) throws Exception {
    /*
         * Disable  AsyncContext
         */
    AsyncContext.disable();
    /*
         *   Factory to implement io pooling
         */
    IoExecutor ioExecutor = NettyIoExecutors.createIoExecutor(Runtime.getRuntime().availableProcessors(), new IoThreadFactory("io-pool"));
    /*
         * Factory to disable headers validation
         */
    DefaultHttpHeadersFactory headersFactory = new DefaultHttpHeadersFactory(false, false);
    HttpSerializationProvider serializer = HttpSerializationProviders.jsonSerializer(new JacksonSerializationProvider());
    // Create a custom server builder with performance enhancements
    HttpServers.forPort(8080).executionStrategy(HttpExecutionStrategies.noOffloadsStrategy()).ioExecutor(ioExecutor).disableDrainingRequestPayloadBody().protocols(HttpProtocolConfigs.h1().headersFactory(headersFactory).build()).appendConnectionAcceptorFilter(delegate -> new ConnectionAcceptor() {

        @Override
        public Completable accept(ConnectionContext context) {
            ((NettyConnectionContext) context).updateFlushStrategy((current, isOrig) -> FlushStrategies.flushOnEnd());
            return delegate.accept(context);
        }
    }).listenAndAwait((ctx, request, responseFactory) -> {
        ((NettyConnectionContext) ctx).updateFlushStrategy(((current, isCurrentOriginal) -> FlushStrategies.flushOnEach()));
        if (request.path().equals("/json")) {
            Map<String, String> obj = new HashMap<String, String>();
            obj.put("message", "Hello, World!");
            return succeeded(responseFactory.ok().payloadBody(obj, serializer.serializerFor(Map.class)).addHeader("Date", getCurrentTime()).addHeader("Server", "ServiceTalk"));
        }
        if (request.path().equals("/plaintext")) {
            return succeeded(responseFactory.ok().payloadBody("Hello, World!", HttpSerializationProviders.textSerializer()).addHeader("Date", getCurrentTime()).addHeader("Server", "ServiceTalk"));
        }
        ;
        return null;
    }).awaitShutdown();
}
Also used : io.servicetalk.transport.netty.internal(io.servicetalk.transport.netty.internal) ZonedDateTime(java.time.ZonedDateTime) Completable(io.servicetalk.concurrent.api.Completable) HttpProtocolConfigs(io.servicetalk.http.netty.HttpProtocolConfigs) HashMap(java.util.HashMap) ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) IoExecutor(io.servicetalk.transport.api.IoExecutor) JacksonSerializationProvider(io.servicetalk.data.jackson.JacksonSerializationProvider) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Map(java.util.Map) DateTimeFormatter(java.time.format.DateTimeFormatter) ZoneOffset(java.time.ZoneOffset) io.servicetalk.http.api(io.servicetalk.http.api) HttpServers(io.servicetalk.http.netty.HttpServers) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) Completable(io.servicetalk.concurrent.api.Completable) IoExecutor(io.servicetalk.transport.api.IoExecutor) JacksonSerializationProvider(io.servicetalk.data.jackson.JacksonSerializationProvider) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ConnectionContext (io.servicetalk.transport.api.ConnectionContext)9 Completable (io.servicetalk.concurrent.api.Completable)6 Buffer (io.servicetalk.buffer.api.Buffer)4 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)4 CONTENT_LENGTH (io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH)4 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)4 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)4 ServerContext (io.servicetalk.transport.api.ServerContext)4 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)4 String.valueOf (java.lang.String.valueOf)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Matchers.contentEqualTo (io.servicetalk.buffer.api.Matchers.contentEqualTo)3 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)3 Single (io.servicetalk.concurrent.api.Single)3 OK (io.servicetalk.http.api.HttpResponseStatus.OK)3 HttpClients.forSingleAddress (io.servicetalk.http.netty.HttpClients.forSingleAddress)3 HttpServers.forAddress (io.servicetalk.http.netty.HttpServers.forAddress)3 HostAndPort (io.servicetalk.transport.api.HostAndPort)3 IOException (java.io.IOException)3 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)3