Search in sources :

Example 51 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class LargeResponseTest method large_response.

@ParameterizedTest
@MethodSource("responseTestArguments")
public void large_response(CloseType closeType, TransferEncoding encoding) throws Exception {
    AtomicBoolean used = new AtomicBoolean();
    Undertow server = startServer(new BlockingHandler(exchange -> {
        long responseBytes = 300 * 1024 * 1024;
        encoding.apply(exchange, responseBytes);
        String sessionId = Base64.getEncoder().encodeToString(exchange.getConnection().getSslSession().getId());
        exchange.getResponseHeaders().put(HttpString.tryFromString("TlsSessionId"), sessionId);
        if (!used.getAndSet(true)) {
            OutputStream out = exchange.getOutputStream();
            for (int i = 0; i < responseBytes; i++) {
                out.write(7);
                // Flush + pause 100ms every 1M for a response time of 30 seconds
                if (i % (1024 * 1024) == 0) {
                    out.flush();
                    Thread.sleep(100);
                }
            }
        }
    }));
    try {
        String uri = "https://localhost:" + getPort(server);
        ClientConfiguration conf = TestConfigurations.create(uri);
        Meter closedConns = DialogueClientMetrics.of(conf.taggedMetricRegistry()).connectionClosedPartiallyConsumedResponse("client");
        String firstSession;
        Channel channel;
        assertThat(closedConns.getCount()).isZero();
        try (ApacheHttpClientChannels.CloseableClient client = ApacheHttpClientChannels.createCloseableHttpClient(conf, "client")) {
            channel = ApacheHttpClientChannels.createSingleUri(uri, client);
            ListenableFuture<Response> response = channel.execute(TestEndpoint.POST, Request.builder().build());
            Response resp = response.get();
            firstSession = resp.getFirstHeader("TlsSessionId").orElseThrow();
            assertThat(resp.code()).isEqualTo(200);
            try (InputStream responseStream = resp.body()) {
                assertThat(responseStream.read()).isEqualTo(7);
                long beforeClose = System.nanoTime();
                closeType.close(responseStream, resp);
                Duration closeDuration = Duration.ofNanos(System.nanoTime() - beforeClose);
                assertThat(closeDuration).isLessThan(Duration.ofSeconds(2));
                assertThat(closedConns.getCount()).isOne();
            }
        }
        // Ensure that the client isn't left in a bad state (connection has been discarded, not incorrectly added
        // back to the pool in an ongoing request state)
        ListenableFuture<Response> response = channel.execute(TestEndpoint.POST, Request.builder().build());
        try (Response resp = response.get()) {
            assertThat(resp.code()).isEqualTo(200);
            assertThat(resp.body()).isEmpty();
            assertThat(resp.getFirstHeader("TlsSessionId").orElseThrow()).as("Expected a new connection").isNotEqualTo(firstSession);
            assertThat(closedConns.getCount()).isOne();
        }
    } finally {
        server.stop();
    }
}
Also used : Iterables(com.google.common.collect.Iterables) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HttpServerExchange(io.undertow.server.HttpServerExchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) TestEndpoint(com.palantir.dialogue.TestEndpoint) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) Meter(com.codahale.metrics.Meter) Duration(java.time.Duration) Request(com.palantir.dialogue.Request) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHandler(io.undertow.server.handlers.BlockingHandler) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Channel(com.palantir.dialogue.Channel) Arguments(org.junit.jupiter.params.provider.Arguments) InetSocketAddress(java.net.InetSocketAddress) TestConfigurations(com.palantir.dialogue.TestConfigurations) HttpHandler(io.undertow.server.HttpHandler) SslSocketFactories(com.palantir.conjure.java.config.ssl.SslSocketFactories) Base64(java.util.Base64) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) Headers(io.undertow.util.Headers) Response(com.palantir.dialogue.Response) InputStream(java.io.InputStream) Meter(com.codahale.metrics.Meter) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Channel(com.palantir.dialogue.Channel) Duration(java.time.Duration) HttpString(io.undertow.util.HttpString) Response(com.palantir.dialogue.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Undertow(io.undertow.Undertow) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 52 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class LargeResponseTest method small_response.

@ParameterizedTest
@MethodSource("responseTestArguments")
public void small_response(CloseType closeType, TransferEncoding encoding) throws Exception {
    Undertow server = startServer(new BlockingHandler(exchange -> {
        long responseBytes = 300;
        encoding.apply(exchange, responseBytes);
        OutputStream out = exchange.getOutputStream();
        for (int i = 0; i < responseBytes; i++) {
            out.write(7);
            out.flush();
        }
    }));
    try {
        String uri = "https://localhost:" + getPort(server);
        ClientConfiguration conf = TestConfigurations.create(uri);
        Meter closedConns = DialogueClientMetrics.of(conf.taggedMetricRegistry()).connectionClosedPartiallyConsumedResponse("client");
        assertThat(closedConns.getCount()).isZero();
        try (ApacheHttpClientChannels.CloseableClient client = ApacheHttpClientChannels.createCloseableHttpClient(conf, "client")) {
            Channel channel = ApacheHttpClientChannels.createSingleUri(uri, client);
            ListenableFuture<Response> response = channel.execute(TestEndpoint.POST, Request.builder().build());
            Response resp = response.get();
            assertThat(resp.code()).isEqualTo(200);
            try (InputStream responseStream = resp.body()) {
                assertThat(responseStream.read()).isEqualTo(7);
                long beforeClose = System.nanoTime();
                closeType.close(responseStream, resp);
                Duration closeDuration = Duration.ofNanos(System.nanoTime() - beforeClose);
                assertThat(closeDuration).isLessThan(Duration.ofSeconds(2));
                assertThat(closedConns.getCount()).as("Small responses below the threshold should not trigger closure").isZero();
            }
        }
    } finally {
        server.stop();
    }
}
Also used : Iterables(com.google.common.collect.Iterables) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HttpServerExchange(io.undertow.server.HttpServerExchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) TestEndpoint(com.palantir.dialogue.TestEndpoint) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) Meter(com.codahale.metrics.Meter) Duration(java.time.Duration) Request(com.palantir.dialogue.Request) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHandler(io.undertow.server.handlers.BlockingHandler) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Channel(com.palantir.dialogue.Channel) Arguments(org.junit.jupiter.params.provider.Arguments) InetSocketAddress(java.net.InetSocketAddress) TestConfigurations(com.palantir.dialogue.TestConfigurations) HttpHandler(io.undertow.server.HttpHandler) SslSocketFactories(com.palantir.conjure.java.config.ssl.SslSocketFactories) Base64(java.util.Base64) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) Headers(io.undertow.util.Headers) Response(com.palantir.dialogue.Response) InputStream(java.io.InputStream) Meter(com.codahale.metrics.Meter) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Channel(com.palantir.dialogue.Channel) Duration(java.time.Duration) HttpString(io.undertow.util.HttpString) Response(com.palantir.dialogue.Response) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Undertow(io.undertow.Undertow) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 53 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class ResponseLeakDetectorTest method before.

@BeforeEach
public void before() {
    mockEndpoint = mock(Endpoint.class);
    response = mock(Response.class);
    metrics = DialogueClientMetrics.of(new DefaultTaggedMetricRegistry());
    lenient().when(mockEndpoint.serviceName()).thenReturn(SERVICE);
    lenient().when(mockEndpoint.endpointName()).thenReturn(ENDPOINT);
    lenient().when(response.body()).thenReturn(new ByteArrayInputStream(new byte[0]));
}
Also used : Response(com.palantir.dialogue.Response) Endpoint(com.palantir.dialogue.Endpoint) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultTaggedMetricRegistry(com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 54 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class ApacheHttpClientChannelsTest method close_doesnt_fail_inflight_requests.

@Test
public void close_doesnt_fail_inflight_requests() throws Exception {
    ClientConfiguration conf = TestConfigurations.create("http://foo");
    Channel channel;
    try (ApacheHttpClientChannels.CloseableClient client = ApacheHttpClientChannels.createCloseableHttpClient(conf, "client")) {
        channel = ApacheHttpClientChannels.createSingleUri("http://foo", client);
        ListenableFuture<Response> response = channel.execute(TestEndpoint.POST, Request.builder().build());
        assertThatThrownBy(() -> Futures.getUnchecked(response)).getCause().isInstanceOfSatisfying(UnknownHostException.class, throwable -> assertThat(throwable.getSuppressed()[0]).satisfies(diagnosticThrowable -> assertThat(diagnosticThrowable.getStackTrace()).as("Diagnostic exception should have an empty stack trace").isEmpty()).isInstanceOfSatisfying(SafeLoggable.class, safeLoggable -> {
            assertThat(Lists.transform(safeLoggable.getArgs(), Arg::getName)).as("Expected a diagnostic exception").containsExactlyInAnyOrder("durationMillis", "connectTimeout", "socketTimeout", "clientName", "serviceName", "endpointName", "requestTraceId", "requestSpanId", "hostIndex");
        }));
    }
    ListenableFuture<Response> again = channel.execute(TestEndpoint.POST, Request.builder().build());
    assertThatThrownBy(() -> Futures.getUnchecked(again)).hasCauseInstanceOf(UnknownHostException.class);
}
Also used : Response(com.palantir.dialogue.Response) AbstractChannelTest(com.palantir.dialogue.AbstractChannelTest) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) TestEndpoint(com.palantir.dialogue.TestEndpoint) Meter(com.codahale.metrics.Meter) OptionalLong(java.util.OptionalLong) Lists(com.google.common.collect.Lists) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) HttpHeaders(com.google.common.net.HttpHeaders) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Duration(java.time.Duration) Map(java.util.Map) Arg(com.palantir.logsafe.Arg) Request(com.palantir.dialogue.Request) OutputStream(java.io.OutputStream) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) RequestBody(com.palantir.dialogue.RequestBody) MoreCollectors(com.google.common.collect.MoreCollectors) Metric(com.codahale.metrics.Metric) IOException(java.io.IOException) SafeLoggable(com.palantir.logsafe.SafeLoggable) Channel(com.palantir.dialogue.Channel) HttpMethod(com.palantir.dialogue.HttpMethod) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) UnknownHostException(java.net.UnknownHostException) TestConfigurations(com.palantir.dialogue.TestConfigurations) Test(org.junit.jupiter.api.Test) Futures(com.google.common.util.concurrent.Futures) Assertions.fail(org.assertj.core.api.Assertions.fail) Optional(java.util.Optional) Gauge(com.codahale.metrics.Gauge) Response(com.palantir.dialogue.Response) SafeLoggable(com.palantir.logsafe.SafeLoggable) Channel(com.palantir.dialogue.Channel) Arg(com.palantir.logsafe.Arg) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) AbstractChannelTest(com.palantir.dialogue.AbstractChannelTest) Test(org.junit.jupiter.api.Test)

Example 55 with Response

use of com.palantir.dialogue.Response in project dialogue by palantir.

the class ApacheHttpClientChannelsTest method countsUnknownHostExceptions.

@Test
public void countsUnknownHostExceptions() throws Exception {
    ClientConfiguration conf = TestConfigurations.create("http://unused");
    try (ApacheHttpClientChannels.CloseableClient client = ApacheHttpClientChannels.createCloseableHttpClient(conf, "testClient")) {
        Meter connectionResolutionError = DialogueClientMetrics.of(conf.taggedMetricRegistry()).connectionResolutionError("testClient");
        assertThat(connectionResolutionError.getCount()).isZero();
        Channel channel = ApacheHttpClientChannels.createSingleUri("http://unknown-host-for-testing.unused", client);
        ListenableFuture<Response> future = channel.execute(TestEndpoint.GET, Request.builder().build());
        try (Response response = Futures.getUnchecked(future)) {
            fail("This request should have failed with an unknown host exception! (code: %d)", response.code());
        } catch (UncheckedExecutionException exception) {
            assertThat(exception.getCause()).isInstanceOf(UnknownHostException.class);
        }
        assertThat(connectionResolutionError.getCount()).isEqualTo(1L);
    }
}
Also used : Response(com.palantir.dialogue.Response) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) UnknownHostException(java.net.UnknownHostException) Meter(com.codahale.metrics.Meter) Channel(com.palantir.dialogue.Channel) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) AbstractChannelTest(com.palantir.dialogue.AbstractChannelTest) Test(org.junit.jupiter.api.Test)

Aggregations

Response (com.palantir.dialogue.Response)93 Test (org.junit.jupiter.api.Test)72 TestResponse (com.palantir.dialogue.TestResponse)56 EndpointChannel (com.palantir.dialogue.EndpointChannel)27 Channel (com.palantir.dialogue.Channel)24 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)22 Endpoint (com.palantir.dialogue.Endpoint)16 Request (com.palantir.dialogue.Request)15 ClientConfiguration (com.palantir.conjure.java.client.config.ClientConfiguration)11 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)10 TestEndpoint (com.palantir.dialogue.TestEndpoint)10 SafeRuntimeException (com.palantir.logsafe.exceptions.SafeRuntimeException)9 Duration (java.time.Duration)9 Meter (com.codahale.metrics.Meter)8 IOException (java.io.IOException)8 Optional (java.util.Optional)7 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 QosException (com.palantir.conjure.java.api.errors.QosException)5 Arrays (java.util.Arrays)5 Stream (java.util.stream.Stream)5