Search in sources :

Example 66 with DisposableServer

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

the class HttpCompressionClientServerTests method testServerCompressionPredicateTrue.

private void testServerCompressionPredicateTrue(HttpServer server, HttpClient client, boolean useScheduler) throws Exception {
    disposableServer = server.compress((req, res) -> true).handle((in, out) -> useScheduler ? out.sendString(Mono.just("reply").subscribeOn(Schedulers.boundedElastic())) : out.sendString(Mono.just("reply"))).bindNow(Duration.ofSeconds(10));
    // don't activate compression on the client options to avoid auto-handling (which removes the header)
    Tuple2<HttpHeaders, byte[]> resp = // edit the header manually to attempt to trigger compression on server side
    client.port(disposableServer.port()).headers(h -> h.add("Accept-Encoding", "gzip")).get().uri("/test").responseSingle((res, byteBufMono) -> Mono.just(res.responseHeaders()).zipWith(byteBufMono.asByteArray())).block(Duration.ofSeconds(10));
    assertThat(resp).isNotNull();
    assertThat(resp.getT1().get("content-encoding")).isEqualTo("gzip");
    byte[] replyBuffer = resp.getT2();
    assertThat(new String(replyBuffer, Charset.defaultCharset())).isNotEqualTo("reply");
    GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(replyBuffer));
    byte[] deflatedBuf = new byte[1024];
    int readable = gis.read(deflatedBuf);
    gis.close();
    assertThat(readable).isGreaterThan(0);
    String deflated = new String(deflatedBuf, 0, readable, Charset.defaultCharset());
    assertThat(deflated).isEqualTo("reply");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SocketUtils(reactor.netty.SocketUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) Retention(java.lang.annotation.Retention) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) MethodSource(org.junit.jupiter.params.provider.MethodSource) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Target(java.lang.annotation.Target) Mono(reactor.core.publisher.Mono) ElementType(java.lang.annotation.ElementType) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpServer(reactor.netty.http.server.HttpServer) DisposableServer(reactor.netty.DisposableServer) RetentionPolicy(java.lang.annotation.RetentionPolicy) HttpClient(reactor.netty.http.client.HttpClient) GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 67 with DisposableServer

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

the class HttpCompressionClientServerTests method serverCompressionEnabledSmallResponse.

@ParameterizedCompressionTest
void serverCompressionEnabledSmallResponse(HttpServer server, HttpClient client) {
    disposableServer = server.compress(25).handle((in, out) -> out.header("content-length", "5").sendString(Mono.just("reply"))).bindNow(Duration.ofSeconds(10));
    // don't activate compression on the client options to avoid auto-handling (which removes the header)
    Tuple2<String, HttpHeaders> resp = // edit the header manually to attempt to trigger compression on server side
    client.port(disposableServer.port()).headers(h -> h.add("Accept-Encoding", "gzip")).get().uri("/test").response((res, byteBufFlux) -> byteBufFlux.asString().zipWith(Mono.just(res.responseHeaders()))).blockFirst(Duration.ofSeconds(10));
    assertThat(resp).isNotNull();
    // check the server didn't send the gzip header, only transfer-encoding
    HttpHeaders headers = resp.getT2();
    assertThat(headers.get("conTENT-encoding")).isNull();
    // check the server sent plain text
    String reply = resp.getT1();
    assertThat(reply).isEqualTo("reply");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SocketUtils(reactor.netty.SocketUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) Retention(java.lang.annotation.Retention) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) MethodSource(org.junit.jupiter.params.provider.MethodSource) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Target(java.lang.annotation.Target) Mono(reactor.core.publisher.Mono) ElementType(java.lang.annotation.ElementType) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpServer(reactor.netty.http.server.HttpServer) DisposableServer(reactor.netty.DisposableServer) RetentionPolicy(java.lang.annotation.RetentionPolicy) HttpClient(reactor.netty.http.client.HttpClient) HttpHeaders(io.netty.handler.codec.http.HttpHeaders)

Example 68 with DisposableServer

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

the class HttpCompressionClientServerTests method serverCompressionPredicateFalse.

@ParameterizedCompressionTest
void serverCompressionPredicateFalse(HttpServer server, HttpClient client) {
    disposableServer = server.compress((req, res) -> false).handle((in, out) -> out.sendString(Flux.just("reply").hide())).bindNow(Duration.ofSeconds(10));
    // don't activate compression on the client options to avoid auto-handling (which removes the header)
    Tuple2<String, HttpHeaders> resp = // edit the header manually to attempt to trigger compression on server side
    client.port(disposableServer.port()).headers(h -> h.add("Accept-Encoding", "gzip")).get().uri("/test").response((res, buf) -> buf.asString().zipWith(Mono.just(res.responseHeaders()))).blockFirst(Duration.ofSeconds(10));
    assertThat(resp).isNotNull();
    // check the server didn't send the gzip header, only transfer-encoding
    HttpHeaders headers = resp.getT2();
    assertThat(headers.get("transFER-encoding")).isEqualTo("chunked");
    assertThat(headers.get("conTENT-encoding")).isNull();
    // check the server sent plain text
    assertThat(resp.getT1()).isEqualTo("reply");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SocketUtils(reactor.netty.SocketUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) Retention(java.lang.annotation.Retention) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) MethodSource(org.junit.jupiter.params.provider.MethodSource) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Target(java.lang.annotation.Target) Mono(reactor.core.publisher.Mono) ElementType(java.lang.annotation.ElementType) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpServer(reactor.netty.http.server.HttpServer) DisposableServer(reactor.netty.DisposableServer) RetentionPolicy(java.lang.annotation.RetentionPolicy) HttpClient(reactor.netty.http.client.HttpClient) HttpHeaders(io.netty.handler.codec.http.HttpHeaders)

Example 69 with DisposableServer

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

the class FluxReceiveTest method testByteBufsReleasedWhenTimeout.

@Test
void testByteBufsReleasedWhenTimeout() {
    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()).get().uri("/target").responseContent().aggregate().asString().log().timeout(Duration.ofMillis(50)).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) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 70 with DisposableServer

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

the class DefaultPooledConnectionProviderTest method testIssue673_TimeoutException.

@Test
void testIssue673_TimeoutException() throws InterruptedException {
    DisposableServer server = TcpServer.create().port(0).handle((in, out) -> out.sendString(Mono.just("test").delayElement(Duration.ofMillis(100)))).wiretap(true).bindNow();
    DefaultPooledConnectionProvider provider = (DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue673_TimeoutException").maxConnections(1).pendingAcquireMaxCount(4).pendingAcquireTimeout(Duration.ofMillis(10)).build();
    CountDownLatch latch = new CountDownLatch(2);
    try {
        AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
        List<? extends Signal<? extends Connection>> list = Flux.range(0, 5).flatMapDelayError(i -> TcpClient.create(provider).port(server.port()).doOnConnected(conn -> {
            ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools = provider.channelPools;
            pool.set(pools.get(pools.keySet().toArray()[0]));
        }).doOnDisconnected(conn -> latch.countDown()).handle((in, out) -> in.receive().then()).wiretap(true).connect().materialize(), 256, 32).collectList().doFinally(fin -> latch.countDown()).block(Duration.ofSeconds(30));
        assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch 30s").isTrue();
        assertThat(list).isNotNull().hasSize(5);
        int onNext = 0;
        int onError = 0;
        String msg = "Pool#acquire(Duration) has been pending for more than the configured timeout of 10ms";
        for (int i = 0; i < 5; i++) {
            Signal<? extends Connection> signal = list.get(i);
            if (signal.isOnNext()) {
                onNext++;
            } else if (signal.getThrowable() instanceof TimeoutException && msg.equals(signal.getThrowable().getMessage())) {
                onError++;
            }
        }
        assertThat(onNext).isEqualTo(1);
        assertThat(onError).isEqualTo(4);
        assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
        assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
    } finally {
        server.disposeNow();
        provider.dispose();
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) SocketAddress(java.net.SocketAddress) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) InstrumentedPool(reactor.pool.InstrumentedPool) TimeoutException(java.util.concurrent.TimeoutException) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) PoolAcquirePendingLimitException(reactor.pool.PoolAcquirePendingLimitException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) NameResolverProvider(reactor.netty.transport.NameResolverProvider) PooledRef(reactor.pool.PooledRef) AddressResolver(io.netty.resolver.AddressResolver) Awaitility.await(org.awaitility.Awaitility.await) AddressUtils(reactor.netty.transport.AddressUtils) Signal(reactor.core.publisher.Signal) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SchedulerClock(reactor.scheduler.clock.SchedulerClock) LockSupport(java.util.concurrent.locks.LockSupport) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) DisposableServer(reactor.netty.DisposableServer) TcpClientTests(reactor.netty.tcp.TcpClientTests) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TcpResources(reactor.netty.tcp.TcpResources) ConnectException(java.net.ConnectException) Connection(reactor.netty.Connection) ClientTransportConfig(reactor.netty.transport.ClientTransportConfig) EventLoopGroup(io.netty.channel.EventLoopGroup) VirtualTimeScheduler(reactor.test.scheduler.VirtualTimeScheduler) NetUtil(io.netty.util.NetUtil) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) Flux(reactor.core.publisher.Flux) ChannelMetricsRecorder(reactor.netty.channel.ChannelMetricsRecorder) TcpServer(reactor.netty.tcp.TcpServer) DefaultAddressResolverGroup(io.netty.resolver.DefaultAddressResolverGroup) Collections(java.util.Collections) ConcurrentMap(java.util.concurrent.ConcurrentMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) DisposableServer(reactor.netty.DisposableServer) InstrumentedPool(reactor.pool.InstrumentedPool) TimeoutException(java.util.concurrent.TimeoutException) 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