Search in sources :

Example 56 with Connection

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

the class ChannelOperationsHandler method exceptionCaught.

@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable err) {
    Connection connection = Connection.from(ctx.channel());
    ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
    if (ops != null) {
        ops.onInboundError(err);
    } else {
        listener.onUncaughtException(connection, err);
    }
}
Also used : Connection(reactor.netty.Connection)

Example 57 with Connection

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

the class HttpProtocolsTests method doTestResponseTimeout.

private void doTestResponseTimeout(HttpClient client, long expectedTimeout) throws Exception {
    AtomicBoolean onRequest = new AtomicBoolean();
    AtomicBoolean onResponse = new AtomicBoolean();
    AtomicBoolean onDisconnected = new AtomicBoolean();
    AtomicLong timeout = new AtomicLong();
    Predicate<Connection> handlerAvailable = conn -> conn.channel().pipeline().get(NettyPipeline.ResponseTimeoutHandler) != null;
    HttpClient localClient = client.doOnRequest((req, conn) -> onRequest.set(handlerAvailable.test(conn))).doOnResponse((req, conn) -> {
        if (handlerAvailable.test(conn)) {
            ChannelHandler handler = conn.channel().pipeline().get(NettyPipeline.ResponseTimeoutHandler);
            onResponse.set(true);
            timeout.set(((ReadTimeoutHandler) handler).getReaderIdleTimeInMillis());
        }
    }).doOnDisconnected(conn -> onDisconnected.set(handlerAvailable.test(conn)));
    Mono<String> response = localClient.get().uri("/").responseContent().aggregate().asString();
    StepVerifier.create(response).expectNext("testProtocolVariationsResponseTimeout").expectComplete().verify(Duration.ofSeconds(30));
    assertThat(onRequest.get()).isFalse();
    assertThat(onResponse.get()).isTrue();
    assertThat(onDisconnected.get()).isFalse();
    assertThat(timeout.get()).isEqualTo(expectedTimeout);
    Thread.sleep(expectedTimeout + 50);
    StepVerifier.create(response).expectNext("testProtocolVariationsResponseTimeout").expectComplete().verify(Duration.ofSeconds(30));
    assertThat(onRequest.get()).isFalse();
    assertThat(onResponse.get()).isTrue();
    assertThat(onDisconnected.get()).isFalse();
    assertThat(timeout.get()).isEqualTo(expectedTimeout);
}
Also used : ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoggerFactory(org.slf4j.LoggerFactory) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) Retention(java.lang.annotation.Retention) LoggingEvent(ch.qos.logback.classic.spi.LoggingEvent) AfterAll(org.junit.jupiter.api.AfterAll) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ArgumentCaptor(org.mockito.ArgumentCaptor) ByteBuf(io.netty.buffer.ByteBuf) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) Appender(ch.qos.logback.core.Appender) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) HttpServerConfig(reactor.netty.http.server.HttpServerConfig) Connection(reactor.netty.Connection) MethodSource(org.junit.jupiter.params.provider.MethodSource) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Predicate(java.util.function.Predicate) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) Mono(reactor.core.publisher.Mono) HttpClientConfig(reactor.netty.http.client.HttpClientConfig) Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) Mockito(org.mockito.Mockito) Flux(reactor.core.publisher.Flux) AtomicLong(java.util.concurrent.atomic.AtomicLong) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpServer(reactor.netty.http.server.HttpServer) List(java.util.List) Logger(ch.qos.logback.classic.Logger) ChannelHandler(io.netty.channel.ChannelHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) HttpClient(reactor.netty.http.client.HttpClient) RetentionPolicy(java.lang.annotation.RetentionPolicy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) HttpClient(reactor.netty.http.client.HttpClient) Connection(reactor.netty.Connection) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) ChannelHandler(io.netty.channel.ChannelHandler)

Example 58 with Connection

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

the class HttpServerOperations method sendDecodingFailures.

static void sendDecodingFailures(ChannelHandlerContext ctx, ConnectionObserver listener, boolean secure, Throwable t, Object msg) {
    Connection conn = Connection.from(ctx.channel());
    Throwable cause = t.getCause() != null ? t.getCause() : t;
    if (log.isWarnEnabled()) {
        log.warn(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
    }
    ReferenceCountUtil.release(msg);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE : HttpResponseStatus.BAD_REQUEST);
    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    HttpRequest request = null;
    if (msg instanceof HttpRequest) {
        request = (HttpRequest) msg;
    }
    listener.onStateChange(new FailedHttpServerRequest(conn, listener, request, response, secure), REQUEST_DECODING_FAILED);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Connection(reactor.netty.Connection) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 59 with Connection

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

the class DefaultPooledConnectionProviderTest method testRetryConnect.

@Test
@SuppressWarnings("unchecked")
void testRetryConnect() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(1);
    InetSocketAddress address = AddressUtils.createUnresolved("localhost", 12122);
    AddressResolverGroup<SocketAddress> resolverGroup = Mockito.mock(AddressResolverGroup.class);
    AddressResolver<SocketAddress> resolver = Mockito.mock(AddressResolver.class);
    io.netty.util.concurrent.Future<List<SocketAddress>> resolveFuture = Mockito.mock(io.netty.util.concurrent.Future.class);
    List<SocketAddress> resolveAllResult = Arrays.asList(// connection refused
    new InetSocketAddress(NetUtil.LOCALHOST4, 12122), // connection refused
    new InetSocketAddress(NetUtil.LOCALHOST6, 12122), // connection established
    new InetSocketAddress("example.com", 80));
    Mockito.when(resolverGroup.getResolver(group.next())).thenReturn(resolver);
    Mockito.when(resolver.isSupported(address)).thenReturn(true);
    Mockito.when(resolver.isResolved(address)).thenReturn(false);
    Mockito.when(resolver.resolveAll(address)).thenReturn(resolveFuture);
    Mockito.when(resolveFuture.isDone()).thenReturn(true);
    Mockito.when(resolveFuture.cause()).thenReturn(null);
    Mockito.when(resolveFuture.getNow()).thenReturn(resolveAllResult);
    ConnectionProvider pool = ConnectionProvider.create("testRetryConnect", 1);
    Supplier<? extends SocketAddress> remoteAddress = () -> address;
    ConnectionObserver observer = ConnectionObserver.emptyListener();
    ClientTransportConfigImpl config = new ClientTransportConfigImpl(group, pool, Collections.emptyMap(), remoteAddress, resolverGroup);
    Connection conn = null;
    try {
        conn = pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(5));
        assertThat(((InetSocketAddress) conn.address()).getHostString()).isEqualTo("example.com");
    } finally {
        if (conn != null) {
            conn.disposeNow(Duration.ofSeconds(5));
        }
        pool.disposeLater().block(Duration.ofSeconds(5));
        group.shutdownGracefully().get(5, TimeUnit.SECONDS);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) Connection(reactor.netty.Connection) ConnectionObserver(reactor.netty.ConnectionObserver) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) List(java.util.List) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 60 with Connection

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

the class DefaultPooledConnectionProviderTest method testDisposeInactivePoolsInBackground.

@Test
void testDisposeInactivePoolsInBackground() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(1);
    InetSocketAddress address = AddressUtils.createUnresolved("example.com", 80);
    ConnectionProvider.Builder builder = ConnectionProvider.builder("testDisposeInactivePoolsInBackground").maxConnections(1).disposeInactivePoolsInBackground(Duration.ofMillis(100), Duration.ofSeconds(1));
    VirtualTimeScheduler vts = VirtualTimeScheduler.create();
    DefaultPooledConnectionProvider pool = new DefaultPooledConnectionProvider(builder, SchedulerClock.of(vts));
    Supplier<? extends SocketAddress> remoteAddress = () -> address;
    ConnectionObserver observer = ConnectionObserver.emptyListener();
    ClientTransportConfigImpl config = new ClientTransportConfigImpl(group, pool, Collections.emptyMap(), remoteAddress, DefaultAddressResolverGroup.INSTANCE);
    Connection conn = null;
    try {
        conn = pool.acquire(config, observer, remoteAddress, config.resolverInternal()).block(Duration.ofSeconds(5));
        assertThat(((InetSocketAddress) conn.address()).getHostString()).isEqualTo("example.com");
    } finally {
        if (conn != null) {
            CountDownLatch latch = new CountDownLatch(1);
            conn.channel().close().addListener(f -> latch.countDown());
            assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
        }
        assertThat(pool.channelPools.size()).isEqualTo(1);
        vts.advanceTimeBy(Duration.ofSeconds(5));
        await().atMost(500, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS).untilAsserted(() -> assertThat(pool.channelPools.size()).isEqualTo(0));
        pool.disposeLater().block(Duration.ofSeconds(5));
        group.shutdownGracefully().get(5, TimeUnit.SECONDS);
    }
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) VirtualTimeScheduler(reactor.test.scheduler.VirtualTimeScheduler) InetSocketAddress(java.net.InetSocketAddress) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

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