Java Code Examples for com.couchbase.client.core.RequestCancelledException

The following examples show how to use com.couchbase.client.core.RequestCancelledException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: couchbase-jvm-core   Source File: AbstractGenericHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Cancells any outstanding operations which are currently on the wire.
 *
 * @param ctx the handler context.
 */
private void handleOutstandingOperations(final ChannelHandlerContext ctx) {
    if (sentRequestQueue.isEmpty()) {
        LOGGER.trace(logIdent(ctx, endpoint) + "Not cancelling operations - sent queue is empty.");
        return;
    }

    LOGGER.debug(logIdent(ctx, endpoint) + "Cancelling " + sentRequestQueue.size() + " outstanding requests.");
    while (!sentRequestQueue.isEmpty()) {
        REQUEST req = sentRequestQueue.poll();
        try {
            sideEffectRequestToCancel(req);
            failSafe(env().scheduler(), moveResponseOut, req.observable(),
                    new RequestCancelledException("Request cancelled in-flight."));
        } catch (Exception ex) {
            LOGGER.info(
                "Exception thrown while cancelling outstanding operation: {}",
                user(req.toString()),
                ex
            );
        }
    }

    sentRequestTimings.clear();
}
 
Example 2
@Test(expected = RequestCancelledException.class)
public void shouldCancelRequestOnFailFastStrategy() {
    Endpoint endpoint1 = mock(Endpoint.class);
    EndpointStates e1s = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint1.states()).thenReturn(e1s.states());
    when(endpoint1.connect()).thenReturn(Observable.just(LifecycleState.DISCONNECTED));
    when(endpoint1.disconnect()).thenReturn(Observable.just(LifecycleState.DISCONNECTING));
    CoreEnvironment env = mock(CoreEnvironment.class);
    when(env.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);

    int endpoints = 1;
    SelectionStrategy strategy = mock(SelectionStrategy.class);
    when(strategy.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    CoreContext ctx = new CoreContext(env, null);
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, endpoints,
            endpoints, strategy, factory);

    CouchbaseRequest request = mock(CouchbaseRequest.class);
    when(request.isActive()).thenReturn(true);
    AsyncSubject<CouchbaseResponse> response = AsyncSubject.create();
    when(request.observable()).thenReturn(response);
    service.send(request);

    response.toBlocking().single();
}
 
Example 3
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBePutIntoRetryWhenFixed() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.BINARY, ef, ssc(2, 2), ss);
    ms.connect().toBlocking().single();
    ef.advanceAll(LifecycleState.CONNECTED);

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr = mockRequest();
    CouchbaseRequest request = mr.value1();
    TestSubscriber<CouchbaseResponse> subscriber = mr.value2();

    when(ss.select(same(request), any(List.class))).thenReturn(null);
    ms.send(request);

    assertEquals(0, ef.endpointSendCalled());
    subscriber.assertError(RequestCancelledException.class);
}
 
Example 4
Source Project: couchbase-jvm-core   Source File: CouchbaseNodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = RequestCancelledException.class)
public void shouldCancelIfServiceCouldNotBeLocated() {
    ServiceRegistry registryMock = mock(ServiceRegistry.class);
    Service serviceMock = mock(Service.class);
    when(registryMock.serviceBy(ServiceType.BINARY, "bucket")).thenReturn(serviceMock);
    when(serviceMock.states()).thenReturn(Observable.<LifecycleState>empty());
    CoreEnvironment env = mock(CoreEnvironment.class);
    when(env.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);

    CoreContext ctx = new CoreContext(env, null);
    CouchbaseNode node = new CouchbaseNode(host, registryMock, ctx, ServiceFactory.INSTANCE);

    CouchbaseRequest request = mock(CouchbaseRequest.class);
    when(request.isActive()).thenReturn(true);
    AsyncSubject<CouchbaseResponse> response = AsyncSubject.create();
    when(request.observable()).thenReturn(response);
    node.send(request);

    response.toBlocking().single();
}
 
Example 5
Source Project: couchbase-jvm-core   Source File: KeyValueHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPropagateErrorOnEncode() {
    String id = "key";
    ByteBuf content = Unpooled.buffer();
    content.release(); // provoke a IllegalReferenceCountException
    UpsertRequest request = new UpsertRequest(id, content, BUCKET);
    request.partition((short) 1);


    TestSubscriber<CouchbaseResponse> ts = TestSubscriber.create();
    request.observable().subscribe(ts);

    try {
        channel.writeOutbound(request);
        fail("Expected exception, none thrown.");
    } catch (EncoderException ex) {
        assertTrue(ex.getCause() instanceof IllegalReferenceCountException);
    }

    List<Throwable> onErrorEvents = ts.getOnErrorEvents();
    assertTrue(onErrorEvents.get(0) instanceof RequestCancelledException);
    assertTrue(onErrorEvents.get(0).getCause() instanceof IllegalReferenceCountException);
}
 
Example 6
Source Project: couchbase-jvm-core   Source File: RetryHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Either retry or cancel a request, based on the strategy used.
 *
 * @param environment the core environment for context.
 * @param request the request to either retry or cancel.
 * @param responseBuffer the response buffer where to maybe retry on.
 */
public static void retryOrCancel(final CoreEnvironment environment, final CouchbaseRequest request,
    final EventSink<ResponseEvent> responseBuffer) {
    if (!request.isActive()) {
        return;
    }

    if (environment.retryStrategy().shouldRetry(request, environment)) {
        retry(request, responseBuffer);
    } else {
        request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling "
            + "instead of retrying."));
    }
}
 
Example 7
Source Project: couchbase-jvm-core   Source File: AbstractGenericHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, REQUEST msg, List<Object> out) throws Exception {
    ENCODED request;
    try {
        request = encodeRequest(ctx, msg);
    } catch (Exception ex) {
        msg.observable().onError(new RequestCancelledException("Error while encoding Request, cancelling.", ex));
        // we need to re-throw the error because netty expects either an exception
        // or at least one message encoded. just returning won't work
        throw ex;
    }
    sentRequestQueue.offer(msg);
    out.add(request);
    sentRequestTimings.offer(System.nanoTime());

    if (localId == null) {
        populateInfo(ctx);
    }

    msg.lastLocalSocket(localSocket);
    msg.lastRemoteSocket(remoteSocket);
    msg.lastLocalId(localId);

    if (env().operationTracingEnabled() && msg.span() != null) {
        Scope scope = env().tracer()
            .buildSpan("dispatch_to_server")
            .asChildOf(msg.span())
            .withTag("peer.address", remoteSocket)
            .withTag("local.address", localSocket)
            .withTag("local.id", localId)
            .startActive(false);
        dispatchSpans.offer(scope.span());
        scope.close();
    }
}
 
Example 8
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWhenMinEqMax() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onConnectTransition(new Func1<Endpoint, LifecycleState>() {
        @Override
        public LifecycleState call(Endpoint endpoint) {
            return LifecycleState.CONNECTING;
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr3 = mockRequest();


    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ef.advanceAll(LifecycleState.CONNECTED);
    ms.send(mr2.value1());
    ef.advanceAll(LifecycleState.CONNECTED);
    ms.send(mr3.value1());
    ef.advanceAll(LifecycleState.CONNECTED);

    assertEquals(4, ef.endpointSendCalled());

    mr1.value2().assertNoTerminalEvent();
    mr2.value2().assertNoTerminalEvent();
    mr3.value2().assertError(RequestCancelledException.class);
}
 
Example 9
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryAndAccountForPending() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onConnectTransition(new Func1<Endpoint, LifecycleState>() {
        @Override
        public LifecycleState call(Endpoint endpoint) {
            return LifecycleState.CONNECTING;
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr3 = mockRequest();


    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ms.send(mr2.value1());
    ms.send(mr3.value1());
    ef.advanceAll(LifecycleState.CONNECTED);

    // 2 request sends + 2 flushes
    assertEquals(4, ef.endpointSendCalled());

    mr1.value2().assertNoTerminalEvent();
    mr2.value2().assertNoTerminalEvent();
    mr3.value2().assertError(RequestCancelledException.class);
}
 
Example 10
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWhenSocketOpenFailedOnSend() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.connect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    states.onNext(LifecycleState.DISCONNECTED);
                    return Observable.error(new Exception("something happened"));
                }
            });
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr3 = mockRequest();

    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ms.send(mr2.value1());
    ms.send(mr3.value1());

    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
    mr2.value2().assertError(RequestCancelledException.class);
    mr3.value2().assertError(RequestCancelledException.class);
}
 
Example 11
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWhenSocketOpenResultIsDisconnected() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onConnectTransition(new Func1<Endpoint, LifecycleState>() {
        @Override
        public LifecycleState call(Endpoint endpoint) {
            return LifecycleState.DISCONNECTED;
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();


    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ms.send(mr2.value1());

    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
    mr2.value2().assertError(RequestCancelledException.class);
}
 
Example 12
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWhenSocketOpenResultIsDisconnecting() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onConnectTransition(new Func1<Endpoint, LifecycleState>() {
        @Override
        public LifecycleState call(Endpoint endpoint) {
            return LifecycleState.DISCONNECTING;
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();


    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ms.send(mr2.value1());

    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
    mr2.value2().assertError(RequestCancelledException.class);
}
 
Example 13
Source Project: couchbase-jvm-core   Source File: PooledServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreateNewEndpointOrAcceptRequestIfNodeIsDown() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.connect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    states.onNext(LifecycleState.DISCONNECTING);
                    return Observable.error(new ConnectException("could not connect to remote"));
                }
            });
        }
    });

    SelectionStrategy ss = new RoundRobinSelectionStrategy();
    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 1), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();

    ms.send(mr1.value1());
    ef.advanceAll(LifecycleState.CONNECTED);

    assertEquals(1, ef.endpointCount());

    mr1.value2().assertError(RequestCancelledException.class);

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    ms.send(mr2.value1());

    // Second request should not create another endpoint
    assertEquals(1, ef.endpointCount());
    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
}
 
Example 14
Source Project: couchbase-jvm-core   Source File: ViewHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    ViewQueryRequest requestMock1 = mock(ViewQueryRequest.class);
    when(requestMock1.query()).thenReturn("{...}");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    ViewQueryRequest requestMock2 = mock(ViewQueryRequest.class);
    when(requestMock2.query()).thenReturn("{...}");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 15
Source Project: couchbase-jvm-core   Source File: QueryHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    RawQueryRequest requestMock1 = mock(RawQueryRequest.class);
    when(requestMock1.query()).thenReturn("SELECT * FROM `foo`");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    RawQueryRequest requestMock2 = mock(RawQueryRequest.class);
    when(requestMock2.query()).thenReturn("SELECT * FROM `foo`");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);

    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 16
Source Project: couchbase-jvm-core   Source File: SearchHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    SearchQueryRequest requestMock1 = mock(SearchQueryRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock1.payload()).thenReturn("");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    SearchQueryRequest requestMock2 = mock(SearchQueryRequest.class);
    when(requestMock2.path()).thenReturn("");
    when(requestMock2.payload()).thenReturn("");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 17
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    GetDesignDocumentsRequest requestMock1 = mock(GetDesignDocumentsRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    GetDesignDocumentsRequest requestMock2 = mock(GetDesignDocumentsRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}