Search in sources :

Example 21 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project herddb by diennea.

the class NettyConnector method createNettyChannel.

private static herddb.network.Channel createNettyChannel(SocketAddress address, String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup) throws IOException, SSLException, InterruptedException {
    if (networkGroup == null) {
        throw new IOException("Connection using network is disabled, cannot connect to " + host + ":" + port);
    }
    Class<? extends Channel> channelType;
    MultithreadEventLoopGroup group = networkGroup;
    final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    Bootstrap b = new Bootstrap();
    AtomicReference<NettyChannel> result = new AtomicReference<>();
    channelType = detectChannelType(networkGroup);
    b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).handler(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel ch) throws Exception {
            try {
                NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                result.set(channel);
                channel.setMessagesReceiver(receiver);
                if (ssl) {
                    ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                if (socketTimeout > 0) {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                }
                ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                // 
                ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder());
                ch.pipeline().addLast(new ClientInboundMessageHandler(channel));
            } catch (Throwable t) {
                LOGGER.log(Level.SEVERE, "error connecting", t);
                ch.close();
            }
        }
    });
    LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
    b.connect(address).sync();
    NettyChannel nettyChannel = result.get();
    if (!nettyChannel.isValid()) {
        throw new IOException("returned channel is not valid");
    }
    return nettyChannel;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) MultithreadEventLoopGroup(io.netty.channel.MultithreadEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext)

Example 22 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project reactor-netty by reactor.

the class HttpClientOperations method onOutboundComplete.

@Override
@SuppressWarnings("FutureReturnValueIgnored")
protected void onOutboundComplete() {
    if (isWebsocket() || isInboundCancelled()) {
        return;
    }
    if (markSentHeaderAndBody()) {
        if (log.isDebugEnabled()) {
            log.debug(format(channel(), "No sendHeaders() called before complete, sending " + "zero-length header"));
        }
        // "FutureReturnValueIgnored" this is deliberate
        channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER));
    } else if (markSentBody()) {
        // "FutureReturnValueIgnored" this is deliberate
        channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }
    listener().onStateChange(this, HttpClientState.REQUEST_SENT);
    if (responseTimeout != null) {
        addHandler(NettyPipeline.ResponseTimeoutHandler, new ReadTimeoutHandler(responseTimeout.toMillis(), TimeUnit.MILLISECONDS));
    }
    channel().read();
    if (channel().parent() != null) {
        channel().parent().read();
    }
}
Also used : ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Example 23 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project reactor-netty by reactor.

the class HttpClientTest method doTestIssue1159.

private void doTestIssue1159(boolean onHttpRequestLevel, long expectedTimeout) {
    AtomicBoolean onRequest = new AtomicBoolean();
    AtomicBoolean onResponse = new AtomicBoolean();
    AtomicBoolean onDisconnected = new AtomicBoolean();
    AtomicLong timeout = new AtomicLong();
    String response = createHttpClientForContextWithAddress().doOnRequest((req, conn) -> {
        if (onHttpRequestLevel) {
            req.responseTimeout(Duration.ofMillis(200));
        }
        onRequest.set(conn.channel().pipeline().get(NettyPipeline.ResponseTimeoutHandler) != null);
    }).doOnResponse((req, conn) -> {
        ChannelHandler handler = conn.channel().pipeline().get(NettyPipeline.ResponseTimeoutHandler);
        if (handler != null) {
            onResponse.set(true);
            timeout.set(((ReadTimeoutHandler) handler).getReaderIdleTimeInMillis());
        }
    }).doOnDisconnected(conn -> onDisconnected.set(conn.channel().pipeline().get(NettyPipeline.ResponseTimeoutHandler) != null)).responseTimeout(Duration.ofMillis(100)).post().uri("/").responseContent().aggregate().asString().block(Duration.ofSeconds(30));
    assertThat(response).isEqualTo("testIssue1159");
    assertThat(onRequest.get()).isFalse();
    assertThat(onResponse.get()).isTrue();
    assertThat(onDisconnected.get()).isFalse();
    assertThat(timeout.get()).isEqualTo(expectedTimeout);
}
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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) ChannelHandler(io.netty.channel.ChannelHandler)

Example 24 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project reactor-netty by reactor.

the class FluxReceiveTest method testByteBufsReleasedWhenTimeoutUsingHandlers.

@Test
void testByteBufsReleasedWhenTimeoutUsingHandlers() {
    byte[] content = new byte[1024 * 8];
    Random rndm = new Random();
    rndm.nextBytes(content);
    DisposableServer server1 = createServer().route(routes -> routes.get("/target", (req, res) -> req.receive().thenMany(res.sendByteArray(Flux.just(content).delayElements(Duration.ofMillis(100)))))).bindNow();
    DisposableServer server2 = createServer().route(routes -> routes.get("/forward", (req, res) -> createClient(server1.port()).doOnConnected(c -> c.addHandlerFirst(new ReadTimeoutHandler(50, TimeUnit.MILLISECONDS))).get().uri("/target").responseContent().aggregate().asString().log().then())).bindNow();
    Flux.range(0, 50).flatMap(i -> createClient(server2.port()).get().uri("/forward").responseContent().log().onErrorResume(t -> Mono.empty())).blockLast(Duration.ofSeconds(15));
    server1.disposeNow();
    server2.disposeNow();
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) ConnectionObserver(reactor.netty.ConnectionObserver) CoreSubscriber(reactor.core.CoreSubscriber) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Duration(java.time.Duration) Subscription(org.reactivestreams.Subscription) Connection(reactor.netty.Connection) DisposableServer(reactor.netty.DisposableServer) Random(java.util.Random) DisposableServer(reactor.netty.DisposableServer) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 25 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project reactor-netty by reactor.

the class Application method main.

public static void main(String[] args) {
    HttpClient client = HttpClient.create().doOnConnected(conn -> conn.addHandler(new ReadTimeoutHandler(10, TimeUnit.SECONDS))).doOnChannelInit((observer, channel, remoteAddress) -> channel.pipeline().addFirst(// <2>
    new LoggingHandler("reactor.netty.examples")));
    client.get().uri("https://example.com/").response().block();
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) LoggingHandler(io.netty.handler.logging.LoggingHandler) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClient(reactor.netty.http.client.HttpClient) LoggingHandler(io.netty.handler.logging.LoggingHandler) HttpClient(reactor.netty.http.client.HttpClient) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Aggregations

ReadTimeoutHandler (io.netty.handler.timeout.ReadTimeoutHandler)26 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelHandler (io.netty.channel.ChannelHandler)6 ChannelPipeline (io.netty.channel.ChannelPipeline)6 LoggingHandler (io.netty.handler.logging.LoggingHandler)6 TimeUnit (java.util.concurrent.TimeUnit)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 SocketChannel (io.netty.channel.socket.SocketChannel)5 Channel (io.netty.channel.Channel)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)4 IOException (java.io.IOException)4 InetSocketAddress (java.net.InetSocketAddress)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Connection (reactor.netty.Connection)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 ByteBuf (io.netty.buffer.ByteBuf)3 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)3 SslContext (io.netty.handler.ssl.SslContext)3 SSLException (javax.net.ssl.SSLException)3