Search in sources :

Example 46 with DisposableServer

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

the class TcpServerTests method testGracefulShutdown.

@Test
void testGracefulShutdown() throws Exception {
    CountDownLatch latch1 = new CountDownLatch(2);
    CountDownLatch latch2 = new CountDownLatch(2);
    CountDownLatch latch3 = new CountDownLatch(1);
    LoopResources loop = LoopResources.create("testGracefulShutdown");
    DisposableServer disposableServer = TcpServer.create().port(0).runOn(loop).doOnConnection(c -> {
        c.onDispose().subscribe(null, null, latch2::countDown);
        latch1.countDown();
    }).channelGroup(new DefaultChannelGroup(new DefaultEventExecutor())).handle((in, out) -> out.sendString(Mono.just("delay1000").delayElement(Duration.ofSeconds(1)))).wiretap(true).bindNow(Duration.ofSeconds(30));
    TcpClient client = TcpClient.create().remoteAddress(disposableServer::address).wiretap(true);
    AtomicReference<String> result = new AtomicReference<>();
    Flux.merge(client.connect(), client.connect()).flatMap(conn -> conn.inbound().receive().asString()).collect(Collectors.joining()).subscribe(s -> {
        result.set(s);
        latch3.countDown();
    });
    assertThat(latch1.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    // Stop accepting incoming requests, wait at most 3s for the active requests to finish
    disposableServer.disposeNow();
    // Dispose the event loop
    loop.disposeLater().block(Duration.ofSeconds(30));
    assertThat(latch2.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    assertThat(latch3.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    assertThat(result.get()).isNotNull().isEqualTo("delay1000delay1000");
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) DisposableServer(reactor.netty.DisposableServer) LoopResources(reactor.netty.resources.LoopResources) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 47 with DisposableServer

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

the class TcpServerTests method testEchoWithLineBasedFrameDecoder.

@Test
void testEchoWithLineBasedFrameDecoder() throws Exception {
    CountDownLatch latch = new CountDownLatch(2);
    DisposableServer server = TcpServer.create().port(0).doOnConnection(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(256))).handle((in, out) -> out.sendString(in.receive().asString().doOnNext(s -> {
        if ("4".equals(s)) {
            latch.countDown();
        }
    }).map(s -> s + "\n"))).bindNow();
    assertThat(server).isNotNull();
    Connection client = TcpClient.create().port(server.port()).doOnConnected(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(256))).handle((in, out) -> out.sendString(Flux.just("1\n", "2\n", "3\n", "4\n")).then(in.receive().asString().doOnNext(s -> {
        if ("4".equals(s)) {
            latch.countDown();
        }
    }).then())).connectNow();
    assertThat(client).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
}
Also used : SNIHostName(javax.net.ssl.SNIHostName) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) BiFunction(java.util.function.BiFunction) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) ConnectionObserver(reactor.netty.ConnectionObserver) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) NettyPipeline(reactor.netty.NettyPipeline) Duration(java.time.Duration) Logger(reactor.util.Logger) Path(java.nio.file.Path) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) LoopResources(reactor.netty.resources.LoopResources) ChannelGroup(io.netty.channel.group.ChannelGroup) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ChannelBindException(reactor.netty.ChannelBindException) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) Exceptions(reactor.core.Exceptions) DisposableServer(reactor.netty.DisposableServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Connection(reactor.netty.Connection) SslContext(io.netty.handler.ssl.SslContext) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) SslProvider(io.netty.handler.ssl.SslProvider) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) NettyInbound(reactor.netty.NettyInbound) Timeout(org.junit.jupiter.api.Timeout) FileSystems(java.nio.file.FileSystems) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 48 with DisposableServer

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

the class TransportEventLoopMetricsTest method testEventLoopMetrics.

@Test
void testEventLoopMetrics() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    DisposableServer server = null;
    Connection client = null;
    LoopResources loop = null;
    try {
        loop = LoopResources.create(TransportEventLoopMetricsTest.class.getName(), 3, true);
        server = TcpServer.create().port(0).metrics(true).runOn(loop).doOnConnection(c -> {
            EventLoop eventLoop = c.channel().eventLoop();
            IntStream.range(0, 10).forEach(i -> eventLoop.execute(() -> {
            }));
            if (eventLoop instanceof SingleThreadEventExecutor) {
                SingleThreadEventExecutor singleThreadEventExecutor = (SingleThreadEventExecutor) eventLoop;
                String[] tags = new String[] { NAME, singleThreadEventExecutor.threadProperties().name() };
                assertThat(getGaugeValue(EVENT_LOOP_PREFIX + PENDING_TASKS, tags)).isEqualTo(10);
                latch.countDown();
            }
        }).wiretap(true).bindNow();
        assertThat(server).isNotNull();
        client = TcpClient.create().port(server.port()).wiretap(true).connectNow();
        assertThat(client).isNotNull();
        assertThat(latch.await(5, TimeUnit.SECONDS)).as("Did not find 10 pending tasks from meter").isTrue();
    } finally {
        if (client != null) {
            client.disposeNow();
        }
        if (server != null) {
            server.disposeNow();
        }
        if (loop != null) {
            loop.disposeLater().block(Duration.ofSeconds(10));
        }
    }
}
Also used : LoopResources(reactor.netty.resources.LoopResources) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) EVENT_LOOP_PREFIX(reactor.netty.Metrics.EVENT_LOOP_PREFIX) SimpleMeterRegistry(io.micrometer.api.instrument.simple.SimpleMeterRegistry) SingleThreadEventExecutor(io.netty.util.concurrent.SingleThreadEventExecutor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) NAME(reactor.netty.Metrics.NAME) EventLoop(io.netty.channel.EventLoop) Test(org.junit.jupiter.api.Test) TcpClient(reactor.netty.tcp.TcpClient) TimeUnit(java.util.concurrent.TimeUnit) PENDING_TASKS(reactor.netty.Metrics.PENDING_TASKS) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) MeterRegistry(io.micrometer.api.instrument.MeterRegistry) Duration(java.time.Duration) Metrics(io.micrometer.api.instrument.Metrics) TcpServer(reactor.netty.tcp.TcpServer) Connection(reactor.netty.Connection) DisposableServer(reactor.netty.DisposableServer) Gauge(io.micrometer.api.instrument.Gauge) EventLoop(io.netty.channel.EventLoop) DisposableServer(reactor.netty.DisposableServer) SingleThreadEventExecutor(io.netty.util.concurrent.SingleThreadEventExecutor) LoopResources(reactor.netty.resources.LoopResources) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 49 with DisposableServer

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

the class TcpEmissionTest method testBackpressure.

@ParameterizedTest
@ValueSource(booleans = { true, false })
void testBackpressure(boolean flushOnEach) throws Exception {
    byte[] array = new byte[32];
    Random random = new Random();
    final int emissionCount = 130;
    DisposableServer server = TcpServer.create().handle((inbound, outbound) -> outbound.send(Flux.fromStream(IntStream.range(0, emissionCount).mapToObj(i -> {
        random.nextBytes(array);
        return Unpooled.copiedBuffer(array);
    })), b -> flushOnEach)).host("localhost").port(0).bindNow();
    CountDownLatch latch = new CountDownLatch(1);
    AtomicLong cnt = new AtomicLong();
    try (Socket socket = new Socket("localhost", server.port());
        InputStream is = socket.getInputStream()) {
        byte[] buffer = new byte[32];
        while (true) {
            is.read(buffer, 0, 4);
            if (cnt.incrementAndGet() >= emissionCount * 8) {
                latch.countDown();
                break;
            }
        }
    } finally {
        server.disposeNow();
    }
    assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
}
Also used : ValueSource(org.junit.jupiter.params.provider.ValueSource) IntStream(java.util.stream.IntStream) Socket(java.net.Socket) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) DisposableServer(reactor.netty.DisposableServer) InputStream(java.io.InputStream) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) DisposableServer(reactor.netty.DisposableServer) InputStream(java.io.InputStream) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 50 with DisposableServer

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

the class TcpResourcesTest method blockShouldFail.

@Test
void blockShouldFail() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);
    DisposableServer server = TcpServer.create().port(port).handle((in, out) -> {
        try {
            in.receive().blockFirst();
        } catch (RuntimeException e) {
            latch.countDown();
            throw e;
        }
        return Flux.never();
    }).bindNow();
    Connection client = TcpClient.newConnection().port(port).handle((in, out) -> {
        try {
            out.sendString(Flux.just("Hello World!")).then().block();
        } catch (RuntimeException e) {
            latch.countDown();
            throw e;
        }
        return Mono.never();
    }).connectNow();
    assertThat(latch.await(5, TimeUnit.SECONDS)).as("latch was counted down").isTrue();
    client.dispose();
    server.disposeNow();
}
Also used : LoopResources(reactor.netty.resources.LoopResources) BeforeEach(org.junit.jupiter.api.BeforeEach) EventLoopGroup(io.netty.channel.EventLoopGroup) SocketAddress(java.net.SocketAddress) SocketUtils(reactor.netty.SocketUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Mono(reactor.core.publisher.Mono) Supplier(java.util.function.Supplier) 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) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) TransportConfig(reactor.netty.transport.TransportConfig) Duration(java.time.Duration) Connection(reactor.netty.Connection) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DisposableServer(reactor.netty.DisposableServer) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Aggregations

DisposableServer (reactor.netty.DisposableServer)137 Mono (reactor.core.publisher.Mono)84 Test (org.junit.jupiter.api.Test)79 Duration (java.time.Duration)71 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)71 AtomicReference (java.util.concurrent.atomic.AtomicReference)68 Flux (reactor.core.publisher.Flux)68 Connection (reactor.netty.Connection)67 TimeUnit (java.util.concurrent.TimeUnit)65 LoopResources (reactor.netty.resources.LoopResources)60 List (java.util.List)58 CountDownLatch (java.util.concurrent.CountDownLatch)57 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)56 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)55 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)54 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)54 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)53 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)53 Assumptions.assumeThat (org.assertj.core.api.Assumptions.assumeThat)53 StepVerifier (reactor.test.StepVerifier)53