Search in sources :

Example 51 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class Http2PoolTest method maxLifeTimeMaxConnectionsNotReached.

@Test
void maxLifeTimeMaxConnectionsNotReached() throws Exception {
    PoolBuilder<Connection, PoolConfig<Connection>> poolBuilder = PoolBuilder.from(Mono.fromSupplier(() -> {
        Channel channel = new EmbeddedChannel(new TestChannelId(), Http2FrameCodecBuilder.forClient().build());
        return Connection.from(channel);
    })).idleResourceReuseLruOrder().maxPendingAcquireUnbounded().sizeBetween(0, 2);
    Http2Pool http2Pool = poolBuilder.build(config -> new Http2Pool(config, 10));
    Connection connection1 = null;
    Connection connection2 = null;
    try {
        PooledRef<Connection> acquired1 = http2Pool.acquire().block();
        assertThat(acquired1).isNotNull();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        connection1 = acquired1.poolable();
        ChannelId id1 = connection1.channel().id();
        Thread.sleep(10);
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        PooledRef<Connection> acquired2 = http2Pool.acquire().block();
        assertThat(acquired2).isNotNull();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(2);
        assertThat(http2Pool.connections.size()).isEqualTo(2);
        connection2 = acquired2.poolable();
        ChannelId id2 = connection2.channel().id();
        assertThat(id1).isNotEqualTo(id2);
        acquired1.invalidate().block();
        acquired2.invalidate().block();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(0);
        assertThat(http2Pool.connections.size()).isEqualTo(0);
    } finally {
        if (connection1 != null) {
            ((EmbeddedChannel) connection1.channel()).finishAndReleaseAll();
            connection1.dispose();
        }
        if (connection2 != null) {
            ((EmbeddedChannel) connection2.channel()).finishAndReleaseAll();
            connection2.dispose();
        }
    }
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) Connection(reactor.netty.Connection) PoolConfig(reactor.netty.internal.shaded.reactor.pool.PoolConfig) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelId(io.netty.channel.ChannelId) Test(org.junit.jupiter.api.Test)

Example 52 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class Http2PoolTest method evictClosedConnectionMaxConnectionsReached.

@Test
void evictClosedConnectionMaxConnectionsReached() throws Exception {
    PoolBuilder<Connection, PoolConfig<Connection>> poolBuilder = PoolBuilder.from(Mono.fromSupplier(() -> {
        Channel channel = new EmbeddedChannel(new TestChannelId(), Http2FrameCodecBuilder.forClient().build());
        return Connection.from(channel);
    })).idleResourceReuseLruOrder().maxPendingAcquireUnbounded().sizeBetween(0, 1);
    Http2Pool http2Pool = poolBuilder.build(config -> new Http2Pool(config, -1));
    Connection connection = null;
    try {
        PooledRef<Connection> acquired1 = http2Pool.acquire().block();
        assertThat(acquired1).isNotNull();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        connection = acquired1.poolable();
        CountDownLatch latch = new CountDownLatch(1);
        ((EmbeddedChannel) connection.channel()).finishAndReleaseAll();
        connection.onDispose(latch::countDown);
        connection.dispose();
        assertThat(latch.await(1, TimeUnit.SECONDS)).as("latch await").isTrue();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        http2Pool.acquire(Duration.ofMillis(10)).as(StepVerifier::create).expectError(PoolAcquireTimeoutException.class).verify(Duration.ofSeconds(1));
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        acquired1.invalidate().block();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(0);
        assertThat(http2Pool.connections.size()).isEqualTo(0);
    } finally {
        if (connection != null) {
            ((EmbeddedChannel) connection.channel()).finishAndReleaseAll();
            connection.dispose();
        }
    }
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) Connection(reactor.netty.Connection) PoolConfig(reactor.netty.internal.shaded.reactor.pool.PoolConfig) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) PoolAcquireTimeoutException(reactor.netty.internal.shaded.reactor.pool.PoolAcquireTimeoutException) CountDownLatch(java.util.concurrent.CountDownLatch) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Example 53 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class HttpClientTest method doTestRetry.

private void doTestRetry(boolean retryDisabled, boolean expectRetry) throws Exception {
    ExecutorService threadPool = Executors.newCachedThreadPool();
    int serverPort = SocketUtils.findAvailableTcpPort();
    ConnectionResetByPeerServer server = new ConnectionResetByPeerServer(serverPort);
    Future<?> serverFuture = threadPool.submit(server);
    if (!server.await(10, TimeUnit.SECONDS)) {
        throw new IOException("fail to start test server");
    }
    AtomicInteger doOnRequest = new AtomicInteger();
    AtomicInteger doOnRequestError = new AtomicInteger();
    AtomicInteger doOnResponseError = new AtomicInteger();
    HttpClient client = createClient(serverPort).doOnRequest((req, conn) -> doOnRequest.getAndIncrement()).doOnError((req, t) -> doOnRequestError.getAndIncrement(), (res, t) -> doOnResponseError.getAndIncrement());
    if (retryDisabled) {
        client = client.disableRetry(retryDisabled);
    }
    AtomicReference<Throwable> error = new AtomicReference<>();
    StepVerifier.create(client.request(HttpMethod.GET).uri("/").send((req, out) -> {
        if (expectRetry) {
            return Mono.error(new IOException("Connection reset by peer"));
        }
        return out;
    }).responseContent()).expectErrorMatches(t -> {
        error.set(t);
        return t.getMessage() != null && (t.getMessage().contains("Connection reset by peer") || // https://github.com/reactor/reactor-netty/issues/1673
        t.getMessage().contains("readAddress(..)") || t.getMessage().contains("Connection prematurely closed BEFORE response"));
    }).verify(Duration.ofSeconds(30));
    int requestCount = 1;
    int requestErrorCount = 1;
    if (expectRetry && !(error.get() instanceof PrematureCloseException)) {
        requestCount = 2;
        requestErrorCount = 2;
    }
    assertThat(doOnRequest.get()).isEqualTo(requestCount);
    assertThat(doOnRequestError.get()).isEqualTo(requestErrorCount);
    assertThat(doOnResponseError.get()).isEqualTo(0);
    server.close();
    assertThat(serverFuture.get()).isNull();
    threadPool.shutdown();
    assertThat(threadPool.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
}
Also used : Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) Tuples(reactor.util.function.Tuples) Disabled(org.junit.jupiter.api.Disabled) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) HttpResources(reactor.netty.http.HttpResources) TcpClient(reactor.netty.tcp.TcpClient) Future(java.util.concurrent.Future) Loggers(reactor.util.Loggers) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) CharsetUtil(io.netty.util.CharsetUtil) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) Context(reactor.util.context.Context) Set(java.util.Set) ConnectionPoolMetrics(reactor.netty.resources.ConnectionPoolMetrics) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) SSLException(javax.net.ssl.SSLException) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) HttpServer(reactor.netty.http.server.HttpServer) LogLevel(io.netty.handler.logging.LogLevel) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) SocketUtils(reactor.netty.SocketUtils) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslProvider(reactor.netty.tcp.SslProvider) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) SslContext(io.netty.handler.ssl.SslContext) Files(java.nio.file.Files) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) Channel(io.netty.channel.Channel) AtomicLong(java.util.concurrent.atomic.AtomicLong) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) Sinks(reactor.core.publisher.Sinks) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ChannelId(io.netty.channel.ChannelId) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) TransportConfig(reactor.netty.transport.TransportConfig) SocketChannel(java.nio.channels.SocketChannel) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) Logger(reactor.util.Logger) ByteBufMono(reactor.netty.ByteBufMono) URI(java.net.URI) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelGroup(io.netty.channel.group.ChannelGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) StandardOpenOption(java.nio.file.StandardOpenOption) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpVersion(io.netty.handler.codec.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Queues(reactor.util.concurrent.Queues) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) TcpServer(reactor.netty.tcp.TcpServer) ChannelHandler(io.netty.channel.ChannelHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException)

Example 54 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class HttpRedirectTest method testHttpRequestIfRedirectHttpToHttpsEnabled.

@Test
void testHttpRequestIfRedirectHttpToHttpsEnabled() {
    Http11SslContextSpec sslContext = Http11SslContextSpec.forServer(ssc.certificate(), ssc.privateKey());
    disposableServer = createServer().host("localhost").secure(spec -> spec.sslContext(sslContext), true).bindNow();
    AtomicReference<Connection> connectionRef = new AtomicReference<>();
    HttpClient client = HttpClient.create().doOnConnected(connectionRef::set).host(disposableServer.host()).port(disposableServer.port());
    String uri = String.format("http://%s:%d/for-test/123", disposableServer.host(), disposableServer.port());
    StepVerifier.create(client.get().uri(uri).response().doOnNext(response -> {
        String location = response.responseHeaders().get(HttpHeaderNames.LOCATION);
        String expectedLocation = uri.replace("http://", "https://");
        assertThat(response.status()).isEqualTo(HttpResponseStatus.PERMANENT_REDIRECT);
        assertThat(location).isEqualTo(expectedLocation);
        assertThat(connectionRef.get().isDisposed()).isTrue();
    })).expectNextCount(1).expectComplete().verify(Duration.ofSeconds(30));
}
Also used : Connection(reactor.netty.Connection) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) AtomicReference(java.util.concurrent.atomic.AtomicReference) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 55 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class ChannelOperationsHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) {
    // fireChannelActive will be triggered regardless that the channel might be closed in the meantime
    if (ctx.channel().isActive()) {
        Connection c = Connection.from(ctx.channel());
        listener.onStateChange(c, ConnectionObserver.State.CONNECTED);
        ChannelOperations<?, ?> ops = opsFactory.create(c, listener, null);
        if (ops != null) {
            ops.bind();
            listener.onStateChange(ops, ConnectionObserver.State.CONFIGURED);
        }
    }
}
Also used : Connection(reactor.netty.Connection)

Aggregations

Connection (reactor.netty.Connection)137 Test (org.junit.jupiter.api.Test)69 CountDownLatch (java.util.concurrent.CountDownLatch)52 Duration (java.time.Duration)49 Mono (reactor.core.publisher.Mono)47 InetSocketAddress (java.net.InetSocketAddress)41 TimeUnit (java.util.concurrent.TimeUnit)39 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)38 LoopResources (reactor.netty.resources.LoopResources)38 ByteBuf (io.netty.buffer.ByteBuf)35 Flux (reactor.core.publisher.Flux)35 DisposableServer (reactor.netty.DisposableServer)35 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)33 AtomicReference (java.util.concurrent.atomic.AtomicReference)32 List (java.util.List)31 IOException (java.io.IOException)30 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)30 ChannelOption (io.netty.channel.ChannelOption)29 Unpooled (io.netty.buffer.Unpooled)28 Charset (java.nio.charset.Charset)28