Search in sources :

Example 51 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class AsyncSharedPoolImpl method get.

@Override
public Cancellable get(Callback<T> callback) {
    ArgumentUtil.notNull(callback, "callback");
    final TimeTrackingCallback timeTrackingCallback = new TimeTrackingCallback(callback);
    final LinkedDeque.Node<Callback<T>> node;
    T item = null;
    boolean create = false;
    while (true) {
        final State state;
        synchronized (_lock) {
            state = _state;
            if (state == State.RUNNING) {
                item = _item.get();
                if (item == null) {
                    node = _waiters.size() < _maxWaiters ? _waiters.addLastNode(timeTrackingCallback) : null;
                    if (_isCreateInProgress) {
                        LOG.debug("{}: item creation is in progress", _name);
                    } else {
                        _isCreateInProgress = true;
                        create = true;
                    }
                    break;
                }
                _checkedOut++;
                _statsTracker.sampleMaxCheckedOut();
            }
        }
        if (state != State.RUNNING) {
            // Defer execution of the callback until we are out of the synchronized block
            timeTrackingCallback.onError(new IllegalStateException(_name + " is " + _state));
            return () -> false;
        }
        // through the item lifecycle before passing back to user callback
        if (_lifecycle.validateGet(item)) {
            timeTrackingCallback.onSuccess(item);
            return () -> false;
        }
        boolean disposed;
        synchronized (_lock) {
            // The connection has gone bad so we proceed to destroy it
            disposed = doDispose(item);
        }
        if (disposed) {
            doDestroy(item, BAD, () -> {
            });
        }
    }
    if (node == null) {
        // This is a recoverable exception. User can simply retry the failed get() operation.
        timeTrackingCallback.onError(new SizeLimitExceededException("AsyncPool " + _name + " reached maximum waiter size: " + _maxWaiters));
        return () -> false;
    }
    // The pool is currently empty we need to construct a new item
    if (create) {
        doCreate();
    }
    return () -> {
        synchronized (_lock) {
            return _waiters.removeNode(node) != null;
        }
    };
}
Also used : SizeLimitExceededException(com.linkedin.r2.SizeLimitExceededException) SimpleCallback(com.linkedin.common.callback.SimpleCallback) Callback(com.linkedin.common.callback.Callback) LinkedDeque(com.linkedin.r2.util.LinkedDeque)

Example 52 with Callback

use of com.linkedin.common.callback.Callback 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()) {
            _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, _requestContext, _wireAttrs, transportCallback);
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) Logger(org.slf4j.Logger) RequestContext(com.linkedin.r2.message.RequestContext) None(com.linkedin.common.util.None) Clock(com.linkedin.util.clock.Clock) Map(java.util.Map) 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) RestResponse(com.linkedin.r2.message.rest.RestResponse) TimeoutException(java.util.concurrent.TimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 53 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestStreamFilterAdapters method testResponseFilterAdapterChangeError.

@Test
public void testResponseFilterAdapterChangeError() {
    FilterChain fc = adaptAndCreateFilterChain(new RestFilter() {

        @Override
        public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
        }

        @Override
        public void onRestError(Throwable ex, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            if (ex instanceof RestException) {
                RestResponse res = ((RestException) ex).getResponse();
                String newEntityStr = res.getEntity().asString("UTF8").replace('1', '0');
                nextFilter.onError(new RestException((res.builder().setEntity(newEntityStr.getBytes()).build())), requestContext, wireAttrs);
            } else {
                nextFilter.onError(new IllegalStateException(), requestContext, wireAttrs);
            }
        }
    });
    fc.onStreamError(simpleStreamException("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    Throwable capturedEx = _beforeFilter.getThrowable();
    Assert.assertTrue(capturedEx instanceof StreamException);
    ((StreamException) capturedEx).getResponse().getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("should not happen");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "02345");
        }
    }));
    fc.onStreamError(new IllegalArgumentException(), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    capturedEx = _beforeFilter.getThrowable();
    Assert.assertTrue(capturedEx instanceof IllegalStateException);
}
Also used : RestFilter(com.linkedin.r2.filter.message.rest.RestFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) FilterChain(com.linkedin.r2.filter.FilterChain) RestException(com.linkedin.r2.message.rest.RestException) ByteString(com.linkedin.data.ByteString) StreamException(com.linkedin.r2.message.stream.StreamException) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) RestRequest(com.linkedin.r2.message.rest.RestRequest) Callback(com.linkedin.common.callback.Callback) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test)

Example 54 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestStreamFilterAdapters method testResponseFilterAdapterPassThrough.

@Test
public void testResponseFilterAdapterPassThrough() {
    FilterChain fc = adaptAndCreateFilterChain(new RestFilter() {

        @Override
        public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            nextFilter.onResponse(res, requestContext, wireAttrs);
        }

        @Override
        public void onRestError(Throwable ex, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            nextFilter.onError(ex, requestContext, wireAttrs);
        }
    });
    fc.onStreamResponse(simpleStreamResponse("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    StreamResponse capturedResponse = _beforeFilter.getResponse();
    capturedResponse.getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("should not happen");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "12345");
        }
    }));
    fc.onStreamError(simpleStreamException("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    Throwable capturedEx = _beforeFilter.getThrowable();
    Assert.assertTrue(capturedEx instanceof StreamException);
    ((StreamException) capturedEx).getResponse().getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("should not happen");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "12345");
        }
    }));
}
Also used : RestFilter(com.linkedin.r2.filter.message.rest.RestFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) FilterChain(com.linkedin.r2.filter.FilterChain) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) StreamException(com.linkedin.r2.message.stream.StreamException) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) RestRequest(com.linkedin.r2.message.rest.RestRequest) Callback(com.linkedin.common.callback.Callback) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test)

Example 55 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestStreamFilterAdapters method testRequestFilterAdapterCallsOnResponse.

@Test
public void testRequestFilterAdapterCallsOnResponse() {
    FilterChain fc = adaptAndCreateFilterChain(new RestFilter() {

        @Override
        public void onRestRequest(RestRequest req, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            nextFilter.onResponse(simpleRestResponse(req.getEntity().asString("UTF8")), requestContext, wireAttrs);
        }
    });
    fc.onStreamRequest(simpleStreamRequest("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    StreamResponse capturedReq = _beforeFilter.getResponse();
    capturedReq.getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("shouldn't have error");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "12345");
        }
    }));
}
Also used : RestFilter(com.linkedin.r2.filter.message.rest.RestFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) FilterChain(com.linkedin.r2.filter.FilterChain) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) RestRequest(com.linkedin.r2.message.rest.RestRequest) Callback(com.linkedin.common.callback.Callback) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test)

Aggregations

Callback (com.linkedin.common.callback.Callback)95 Test (org.testng.annotations.Test)64 AfterTest (org.testng.annotations.AfterTest)43 BeforeTest (org.testng.annotations.BeforeTest)43 RequestContext (com.linkedin.r2.message.RequestContext)37 RestResponse (com.linkedin.r2.message.rest.RestResponse)34 ByteString (com.linkedin.data.ByteString)29 RestRequest (com.linkedin.r2.message.rest.RestRequest)28 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)28 AsyncStatusCollectionResource (com.linkedin.restli.server.twitter.AsyncStatusCollectionResource)28 URI (java.net.URI)28 RestLiCallback (com.linkedin.restli.internal.server.RestLiCallback)26 FilterChainCallback (com.linkedin.restli.internal.server.filter.FilterChainCallback)26 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)26 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)26 RequestExecutionCallback (com.linkedin.restli.server.RequestExecutionCallback)26 RestLiTestHelper.buildResourceModel (com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel)26 EasyMock.anyObject (org.easymock.EasyMock.anyObject)26 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)25 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)22