Search in sources :

Example 1 with ConnectionAcceptor

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

the class ConnectionAcceptorFilterTest method testAppend.

@Test
void testAppend() throws Exception {
    Deque<Integer> createOrder = new ArrayDeque<>();
    Deque<Integer> connectOrder = new ArrayDeque<>();
    class AcceptorOrder implements ConnectionAcceptor {

        final int order;

        ConnectionAcceptor original;

        AcceptorOrder(int order, ConnectionAcceptor original) {
            this.order = order;
            this.original = original;
        }

        @Override
        public Completable accept(ConnectionContext context) {
            connectOrder.add(order);
            return original.accept(context);
        }

        @Override
        public Completable closeAsync() {
            return Completable.completed();
        }
    }
    class FilterOrder implements ConnectionAcceptorFactory {

        final int order;

        FilterOrder(int order) {
            this.order = order;
        }

        @Override
        public ConnectionAcceptor create(ConnectionAcceptor original) {
            createOrder.add(order);
            return new AcceptorOrder(order, original);
        }
    }
    FilterOrder first = new FilterOrder(1);
    FilterOrder second = new FilterOrder(2);
    ConnectionAcceptorFactory combined = first.append(second);
    ConnectionAcceptor acceptor = combined.create(ConnectionAcceptor.ACCEPT_ALL);
    @SuppressWarnings("unused") Void nothing = acceptor.accept(mock(ConnectionContext.class)).toFuture().get();
    assertThat(nothing, is(nullValue()));
    assertThat(createOrder, is(hasSize(2)));
    assertThat(createOrder, is(containsInRelativeOrder(2, 1)));
    assertThat(connectOrder, is(hasSize(2)));
    assertThat(connectOrder, is(containsInRelativeOrder(1, 2)));
}
Also used : ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) ConnectionAcceptorFactory(io.servicetalk.transport.api.ConnectionAcceptorFactory) ArrayDeque(java.util.ArrayDeque) Test(org.junit.jupiter.api.Test)

Example 2 with ConnectionAcceptor

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

the class AbstractNettyHttpServerTest method startServer.

private void startServer() throws Exception {
    final InetSocketAddress bindAddress = localAddress(0);
    service(new TestServiceStreaming(publisherSupplier));
    // A small SNDBUF is needed to test that the server defers closing the connection until writes are complete.
    // However, if it is too small, tests that expect certain chunks of data will see those chunks broken up
    // differently.
    final HttpServerBuilder serverBuilder = HttpServers.forAddress(bindAddress).executor(serverExecutor).socketOption(StandardSocketOptions.SO_SNDBUF, 100).protocols(protocol).transportObserver(serverTransportObserver).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true);
    configureServerBuilder(serverBuilder);
    if (sslEnabled) {
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    }
    if (nonOffloadingServiceFilterFactory != null) {
        serverBuilder.appendNonOffloadingServiceFilter(nonOffloadingServiceFilterFactory);
    }
    if (serviceFilterFactory != null) {
        serverBuilder.appendServiceFilter(serviceFilterFactory);
    }
    if (serverLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        serverBuilder.lifecycleObserver(serverLifecycleObserver);
    }
    serverContext = awaitIndefinitelyNonNull(listen(serverBuilder.ioExecutor(serverIoExecutor).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(connectionAcceptor))).beforeOnSuccess(ctx -> LOGGER.debug("Server started on {}.", ctx.listenAddress())).beforeOnError(throwable -> LOGGER.debug("Failed starting server on {}.", bindAddress)));
    final SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = newClientBuilder();
    if (sslEnabled) {
        clientBuilder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build());
    }
    if (connectionFactoryFilter != null) {
        clientBuilder.appendConnectionFactoryFilter(connectionFactoryFilter);
    }
    if (connectionFilterFactory != null) {
        clientBuilder.appendConnectionFilter(connectionFilterFactory);
    }
    if (clientTransportObserver != NoopTransportObserver.INSTANCE) {
        clientBuilder.appendConnectionFactoryFilter(new TransportObserverConnectionFactoryFilter<>(clientTransportObserver));
    }
    if (clientLifecycleObserver != NoopHttpLifecycleObserver.INSTANCE) {
        clientBuilder.appendClientFilter(new HttpLifecycleObserverRequesterFilter(clientLifecycleObserver));
    }
    if (clientFilterFactory != null) {
        clientBuilder.appendClientFilter(clientFilterFactory);
    }
    httpClient = clientBuilder.ioExecutor(clientIoExecutor).executor(clientExecutor).executionStrategy(defaultStrategy()).protocols(protocol).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).buildStreaming();
    httpConnection = httpClient.reserveConnection(httpClient.get("/")).toFuture().get();
}
Also used : HttpLifecycleObserver(io.servicetalk.http.api.HttpLifecycleObserver) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) StreamingHttpConnectionFilterFactory(io.servicetalk.http.api.StreamingHttpConnectionFilterFactory) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) StreamingHttpServiceFilterFactory(io.servicetalk.http.api.StreamingHttpServiceFilterFactory) ConnectionAcceptor(io.servicetalk.transport.api.ConnectionAcceptor) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BeforeAll(org.junit.jupiter.api.BeforeAll) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) Executor(io.servicetalk.concurrent.api.Executor) HttpProtocolConfig(io.servicetalk.http.api.HttpProtocolConfig) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) StandardSocketOptions(java.net.StandardSocketOptions) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) InetSocketAddress(java.net.InetSocketAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) Matchers.is(org.hamcrest.Matchers.is) Strictness(org.mockito.quality.Strictness) Assertions.fail(org.junit.jupiter.api.Assertions.fail) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) MockitoSettings(org.mockito.junit.jupiter.MockitoSettings) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpProtocolConfigs.h1Default(io.servicetalk.http.netty.HttpProtocolConfigs.h1Default) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpServerContext(io.servicetalk.http.api.HttpServerContext) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpProtocolVersion(io.servicetalk.http.api.HttpProtocolVersion) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DefaultThreadFactory(io.servicetalk.concurrent.api.DefaultThreadFactory) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ACCEPT_ALL(io.servicetalk.transport.api.ConnectionAcceptor.ACCEPT_ALL) NettyIoExecutors(io.servicetalk.transport.netty.NettyIoExecutors) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) ServerContext(io.servicetalk.transport.api.ServerContext) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single(io.servicetalk.concurrent.api.Single) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ExecutionException(java.util.concurrent.ExecutionException) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) IoExecutor(io.servicetalk.transport.api.IoExecutor) AfterEach(org.junit.jupiter.api.AfterEach) Boolean.parseBoolean(java.lang.Boolean.parseBoolean) TransportObserverConnectionFactoryFilter(io.servicetalk.client.api.TransportObserverConnectionFactoryFilter) Executors.newCachedThreadExecutor(io.servicetalk.concurrent.api.Executors.newCachedThreadExecutor) NORM_PRIORITY(java.lang.Thread.NORM_PRIORITY) Executors(io.servicetalk.concurrent.api.Executors) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) NoopTransportObserver(io.servicetalk.transport.netty.internal.NoopTransportObserver) HostAndPort(io.servicetalk.transport.api.HostAndPort) InetSocketAddress(java.net.InetSocketAddress) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 3 with ConnectionAcceptor

use of io.servicetalk.transport.api.ConnectionAcceptor 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

ConnectionAcceptor (io.servicetalk.transport.api.ConnectionAcceptor)3 IoExecutor (io.servicetalk.transport.api.IoExecutor)2 Buffer (io.servicetalk.buffer.api.Buffer)1 DEFAULT_ALLOCATOR (io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR)1 ConnectionFactoryFilter (io.servicetalk.client.api.ConnectionFactoryFilter)1 TransportObserverConnectionFactoryFilter (io.servicetalk.client.api.TransportObserverConnectionFactoryFilter)1 AsyncCloseables.newCompositeCloseable (io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable)1 AsyncContext (io.servicetalk.concurrent.api.AsyncContext)1 BlockingTestUtils.awaitIndefinitelyNonNull (io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull)1 Completable (io.servicetalk.concurrent.api.Completable)1 DefaultThreadFactory (io.servicetalk.concurrent.api.DefaultThreadFactory)1 Executor (io.servicetalk.concurrent.api.Executor)1 Executors (io.servicetalk.concurrent.api.Executors)1 Executors.newCachedThreadExecutor (io.servicetalk.concurrent.api.Executors.newCachedThreadExecutor)1 Publisher (io.servicetalk.concurrent.api.Publisher)1 Single (io.servicetalk.concurrent.api.Single)1 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)1 JacksonSerializationProvider (io.servicetalk.data.jackson.JacksonSerializationProvider)1 io.servicetalk.http.api (io.servicetalk.http.api)1 FilterableStreamingHttpConnection (io.servicetalk.http.api.FilterableStreamingHttpConnection)1