Search in sources :

Example 91 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestDisruptor method testStreamTimeoutDisrupt.

@Test
public void testStreamTimeoutDisrupt() throws Exception {
    final Map<String, Object> properties = new HashMap<>();
    properties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, String.valueOf(REQUEST_TIMEOUT));
    final Client client = _clientProvider.createClient(FilterChains.empty(), properties);
    final RequestContext requestContext = new RequestContext();
    requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.timeout());
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean success = new AtomicBoolean(false);
    client.streamRequest(new StreamRequestBuilder(getHttpURI()).build(EntityStreams.emptyStream()), requestContext, new Callback<StreamResponse>() {

        @Override
        public void onSuccess(StreamResponse result) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            success.set(e instanceof TimeoutException);
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS), "Test execution timeout");
    Assert.assertTrue(success.get(), "Unexpected transport response");
}
Also used : HashMap(java.util.HashMap) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RequestContext(com.linkedin.r2.message.RequestContext) Client(com.linkedin.r2.transport.common.Client) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test) AbstractServiceTest(test.r2.integ.clientserver.providers.AbstractServiceTest)

Example 92 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestDisruptor method testRestTimeoutDisrupt.

@Test
public void testRestTimeoutDisrupt() throws Exception {
    final Map<String, Object> properties = new HashMap<>();
    properties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, String.valueOf(REQUEST_TIMEOUT));
    final Client client = _clientProvider.createClient(FilterChains.empty(), properties);
    final RequestContext requestContext = new RequestContext();
    requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.timeout());
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean success = new AtomicBoolean(false);
    client.restRequest(new RestRequestBuilder(getHttpURI()).build(), requestContext, new Callback<RestResponse>() {

        @Override
        public void onSuccess(RestResponse result) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            success.set(e instanceof TimeoutException);
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS), "Test execution timeout");
    Assert.assertTrue(success.get(), "Unexpected transport response");
}
Also used : HashMap(java.util.HashMap) RestResponse(com.linkedin.r2.message.rest.RestResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) Client(com.linkedin.r2.transport.common.Client) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test) AbstractServiceTest(test.r2.integ.clientserver.providers.AbstractServiceTest)

Example 93 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TransportHealthCheck method checkHealth.

@Override
public void checkHealth(Callback<None> callback) {
    final long startTime = _clock.currentTimeMillis();
    TransportCallback<RestResponse> transportCallback = response -> {
        long delay = _clock.currentTimeMillis() - startTime;
        if (response.hasError()) {
            // Currently treat all errors as failure
            _log.debug("checkHealth: error response for request ({}): {}", _restRequest.getURI(), response.getError());
            callback.onError(new Exception("Error from " + _restRequest.getURI() + " : " + response.getError()));
        } else if (delay > _responseTimeThreshold) {
            _log.debug("checkHealth: return delay ({}ms) longer than threshold for request {}", delay, _restRequest.getURI());
            callback.onError(new TimeoutException("HealthCheck Timeout: " + delay + "ms for " + _restRequest.getURI()));
        } else if (!_healthCheckResponseValidator.validateResponse(response.getResponse())) {
            _log.error("checkHealth: response validating error for request ({}): {}", _restRequest.getURI(), response);
            callback.onError(new Throwable("HealthCheck Response Error"));
        } else {
            _log.debug("checkHealth successful for client {}", _clientToCheck);
            callback.onSuccess(None.none());
        }
    };
    _clientToCheck.restRequest(_restRequest, _requestContextSupplier.get(), _wireAttrsSupplier.get(), transportCallback);
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) Logger(org.slf4j.Logger) Clock(com.linkedin.util.clock.Clock) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Callback(com.linkedin.common.callback.Callback) TransportClient(com.linkedin.r2.transport.common.bridge.client.TransportClient) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) RestResponse(com.linkedin.r2.message.rest.RestResponse) Supplier(java.util.function.Supplier) RequestContext(com.linkedin.r2.message.RequestContext) None(com.linkedin.common.util.None) Map(java.util.Map) RestResponse(com.linkedin.r2.message.rest.RestResponse) TimeoutException(java.util.concurrent.TimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 94 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestHttpNettyStreamClient method testResponseSize.

public void testResponseSize(AbstractNettyStreamClient client, int responseSize, int expectedResult) throws Exception {
    Server server = new HttpServerBuilder().responseSize(responseSize).build();
    try {
        server.start();
        RestRequest r = new RestRequestBuilder(new URI(URL)).build();
        FutureCallback<StreamResponse> cb = new FutureCallback<>();
        TransportCallback<StreamResponse> callback = new TransportCallbackAdapter<>(cb);
        client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback);
        StreamResponse response = cb.get(30, TimeUnit.SECONDS);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Throwable> error = new AtomicReference<>();
        response.getEntityStream().setReader(new Reader() {

            @Override
            public void onInit(ReadHandle rh) {
                rh.request(Integer.MAX_VALUE);
            }

            @Override
            public void onDataAvailable(ByteString data) {
            }

            @Override
            public void onDone() {
                latch.countDown();
            }

            @Override
            public void onError(Throwable e) {
                error.set(e);
                latch.countDown();
            }
        });
        if (!latch.await(30, TimeUnit.SECONDS)) {
            Assert.fail("Timeout waiting for response");
        }
        if (expectedResult == TOO_LARGE) {
            Assert.assertNotNull(error.get(), "Max response size exceeded, expected exception. ");
            verifyCauseChain(error.get(), TooLongFrameException.class);
        }
        if (expectedResult == RESPONSE_OK) {
            Assert.assertNull(error.get(), "Unexpected Exception: response size <= max size");
        }
    } catch (ExecutionException e) {
        if (expectedResult == RESPONSE_OK) {
            Assert.fail("Unexpected ExecutionException, response was <= max response size.", e);
        }
        verifyCauseChain(e, RemoteInvocationException.class, TooLongFrameException.class);
    } finally {
        server.stop();
    }
}
Also used : TransportCallbackAdapter(com.linkedin.r2.transport.common.bridge.client.TransportCallbackAdapter) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Server(org.eclipse.jetty.server.Server) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) HttpServerBuilder(com.linkedin.r2.testutils.server.HttpServerBuilder) Reader(com.linkedin.r2.message.stream.entitystream.Reader) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ReadHandle(com.linkedin.r2.message.stream.entitystream.ReadHandle) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(com.linkedin.common.callback.FutureCallback)

Example 95 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestHttpNettyStreamClient method testStreamRequests.

/**
 * Tests implementations of {@link AbstractNettyStreamClient} with different request dimensions.
 *
 * @param client Client implementation of {@link AbstractNettyStreamClient}
 * @param method HTTP request method
 * @param requestSize Request content size
 * @param responseSize Response content size
 * @param isFullRequest Whether to buffer a full request before stream
 * @throws Exception
 */
@Test(dataProvider = "requestResponseParameters")
public void testStreamRequests(AbstractNettyStreamClient client, String method, int requestSize, int responseSize, boolean isFullRequest) throws Exception {
    AtomicInteger succeeded = new AtomicInteger(0);
    AtomicInteger failed = new AtomicInteger(0);
    Server server = new HttpServerBuilder().responseSize(responseSize).build();
    try {
        server.start();
        CountDownLatch latch = new CountDownLatch(REQUEST_COUNT);
        for (int i = 0; i < REQUEST_COUNT; i++) {
            StreamRequest request = new StreamRequestBuilder(new URI(URL)).setMethod(method).setHeader(HttpHeaderNames.HOST.toString(), HOST_NAME.toString()).build(EntityStreams.newEntityStream(new ByteStringWriter(ByteString.copy(new byte[requestSize]))));
            RequestContext context = new RequestContext();
            context.putLocalAttr(R2Constants.IS_FULL_REQUEST, isFullRequest);
            client.streamRequest(request, context, new HashMap<>(), new TransportCallbackAdapter<>(new Callback<StreamResponse>() {

                @Override
                public void onSuccess(StreamResponse response) {
                    response.getEntityStream().setReader(new Reader() {

                        ReadHandle _rh;

                        int _consumed = 0;

                        @Override
                        public void onDataAvailable(ByteString data) {
                            _consumed += data.length();
                            _rh.request(1);
                        }

                        @Override
                        public void onDone() {
                            succeeded.incrementAndGet();
                            latch.countDown();
                        }

                        @Override
                        public void onError(Throwable e) {
                            failed.incrementAndGet();
                            latch.countDown();
                        }

                        @Override
                        public void onInit(ReadHandle rh) {
                            _rh = rh;
                            _rh.request(1);
                        }
                    });
                }

                @Override
                public void onError(Throwable e) {
                    failed.incrementAndGet();
                    latch.countDown();
                }
            }));
        }
        if (!latch.await(30, TimeUnit.SECONDS)) {
            Assert.fail("Timeout waiting for responses. " + succeeded + " requests succeeded and " + failed + " requests failed out of total " + REQUEST_COUNT + " requests");
        }
        Assert.assertEquals(latch.getCount(), 0);
        Assert.assertEquals(failed.get(), 0);
        Assert.assertEquals(succeeded.get(), REQUEST_COUNT);
        FutureCallback<None> shutdownCallback = new FutureCallback<>();
        client.shutdown(shutdownCallback);
        shutdownCallback.get(30, TimeUnit.SECONDS);
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) HttpServerBuilder(com.linkedin.r2.testutils.server.HttpServerBuilder) Reader(com.linkedin.r2.message.stream.entitystream.Reader) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URI(java.net.URI) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) ReadHandle(com.linkedin.r2.message.stream.entitystream.ReadHandle) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) FutureCallback(com.linkedin.common.callback.FutureCallback) Callback(com.linkedin.common.callback.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RequestContext(com.linkedin.r2.message.RequestContext) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)78 RequestContext (com.linkedin.r2.message.RequestContext)46 CountDownLatch (java.util.concurrent.CountDownLatch)40 TimeoutException (java.util.concurrent.TimeoutException)40 None (com.linkedin.common.util.None)33 FutureCallback (com.linkedin.common.callback.FutureCallback)32 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)26 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)25 URI (java.net.URI)25 RestRequest (com.linkedin.r2.message.rest.RestRequest)21 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)21 ByteString (com.linkedin.data.ByteString)19 HashMap (java.util.HashMap)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 RestResponse (com.linkedin.r2.message.rest.RestResponse)18 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)17 ExecutionException (java.util.concurrent.ExecutionException)17 TransportClient (com.linkedin.r2.transport.common.bridge.client.TransportClient)15 IOException (java.io.IOException)15 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)13