Search in sources :

Example 1 with EmbeddedChannel

use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.

the class ManagerMessageHandlerTest method disconnectsEndpointOnRedialTimeout.

/**
 * When a http streaming connection is outstanding, the handler needs to notify the endpoint that it disconnects
 * itself in an orderly manner.
 */
@Test
void disconnectsEndpointOnRedialTimeout() throws Exception {
    CoreEnvironment env = CoreEnvironment.builder().ioConfig(IoConfig.configIdleRedialTimeout(Duration.ofSeconds(2))).build();
    try {
        CoreContext ctx = new CoreContext(mock(Core.class), 1, env, PasswordAuthenticator.create(USER, PASS));
        BaseEndpoint endpoint = mock(BaseEndpoint.class);
        EndpointContext endpointContext = mock(EndpointContext.class);
        when(endpointContext.environment()).thenReturn(env);
        when(endpoint.context()).thenReturn(endpointContext);
        EmbeddedChannel channel = new EmbeddedChannel(new ManagerMessageHandler(endpoint, ctx));
        BucketConfigStreamingRequest request = new BucketConfigStreamingRequest(Duration.ofSeconds(1), ctx, BestEffortRetryStrategy.INSTANCE, "bucket", ctx.authenticator());
        channel.write(request);
        HttpRequest outboundHeader = channel.readOutbound();
        assertEquals(HttpMethod.GET, outboundHeader.method());
        assertEquals("/pools/default/bs/bucket", outboundHeader.uri());
        assertEquals(HttpVersion.HTTP_1_1, outboundHeader.protocolVersion());
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        HttpContent httpContent = new DefaultHttpContent(Unpooled.copiedBuffer("{}\n\n\n\n", StandardCharsets.UTF_8));
        channel.writeInbound(httpResponse, httpContent);
        BucketConfigStreamingResponse response = request.response().get();
        assertEquals("{}", response.configs().blockFirst());
        waitUntilCondition(() -> {
            channel.runPendingTasks();
            MockingDetails mockingDetails = Mockito.mockingDetails(endpoint);
            return mockingDetails.getInvocations().stream().anyMatch(i -> i.getMethod().getName().equals("disconnect"));
        });
        channel.finish();
    } finally {
        env.shutdown();
    }
}
Also used : HttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpRequest) CoreContext(com.couchbase.client.core.CoreContext) BucketConfigStreamingResponse(com.couchbase.client.core.msg.manager.BucketConfigStreamingResponse) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) DefaultHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) HttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) MockingDetails(org.mockito.MockingDetails) BucketConfigStreamingRequest(com.couchbase.client.core.msg.manager.BucketConfigStreamingRequest) BaseEndpoint(com.couchbase.client.core.endpoint.BaseEndpoint) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) HttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent) Core(com.couchbase.client.core.Core) Test(org.junit.jupiter.api.Test)

Example 2 with EmbeddedChannel

use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.

the class QueryMessageHandlerTest method reportsCompletionOnlyOnceStreamingEnds.

/**
 * To avoid accidentally pipelining requests, we need to make sure that the handler only reports completion
 * once the streaming is fully completed, and not just the response completable future initially completed.
 *
 * <p>We send a request, make sure it is encoded correctly and then stream back the chunks, making sure the
 * final completion is only signaled once the last chunk arrived.</p>
 */
@Test
void reportsCompletionOnlyOnceStreamingEnds() {
    BaseEndpoint endpoint = mock(BaseEndpoint.class);
    EmbeddedChannel channel = new EmbeddedChannel(new QueryMessageHandler(endpoint, ENDPOINT_CTX));
    byte[] query = "doesn'tmatter".getBytes(CharsetUtil.UTF_8);
    QueryRequest request = new QueryRequest(ENV.timeoutConfig().queryTimeout(), CORE_CTX, ENV.retryStrategy(), CORE_CTX.authenticator(), "statement", query, false, null, null, null, null, null);
    channel.writeAndFlush(request);
    FullHttpRequest encodedRequest = channel.readOutbound();
    assertEquals("doesn'tmatter", encodedRequest.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.release(encodedRequest);
    verify(endpoint, never()).markRequestCompletion();
    assertFalse(request.response().isDone());
    ByteBuf fullResponse = Unpooled.copiedBuffer(readResource("success_response.json", QueryMessageHandlerTest.class), CharsetUtil.UTF_8);
    // send the header back first
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    channel.writeInbound(response);
    assertFalse(request.response().isDone());
    // send first chunk, should complete the future but not mark the endpoint completion
    HttpContent firstChunk = new DefaultHttpContent(fullResponse.readBytes(500));
    channel.writeInbound(firstChunk);
    assertTrue(request.response().isDone());
    verify(endpoint, never()).markRequestCompletion();
    // send the second chunk, no change
    HttpContent secondChunk = new DefaultHttpContent(fullResponse.readBytes(500));
    channel.writeInbound(secondChunk);
    verify(endpoint, never()).markRequestCompletion();
    // send the last chunk, mark for completion finally
    LastHttpContent lastChunk = new DefaultLastHttpContent(fullResponse.readBytes(fullResponse.readableBytes()));
    channel.writeInbound(lastChunk);
    verify(endpoint, times(1)).markRequestCompletion();
    channel.finishAndReleaseAll();
}
Also used : FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) QueryRequest(com.couchbase.client.core.msg.query.QueryRequest) DefaultHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) HttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) BaseEndpoint(com.couchbase.client.core.endpoint.BaseEndpoint) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) DefaultHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) HttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent) Test(org.junit.jupiter.api.Test)

Example 3 with EmbeddedChannel

use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.

the class KeyValueMessageHandlerTest method closesChannelOnCertainStatusCodes.

/**
 * As part of the KV error map, certain status codes have been identified as "must close" on the channel
 * to avoid further problems.
 *
 * <p>This test makes sure that on all of those codes, the channel gets closed accordingly.</p>
 */
@Test
void closesChannelOnCertainStatusCodes() {
    Set<MemcacheProtocol.Status> closeOnThese = EnumSet.of(MemcacheProtocol.Status.INTERNAL_SERVER_ERROR, MemcacheProtocol.Status.NO_BUCKET, MemcacheProtocol.Status.NOT_INITIALIZED);
    for (MemcacheProtocol.Status status : closeOnThese) {
        EmbeddedChannel channel = new EmbeddedChannel(new KeyValueMessageHandler(null, CTX, Optional.of(BUCKET)));
        try {
            GetRequest request1 = new GetRequest("key", Duration.ofSeconds(1), CTX, CID, FailFastRetryStrategy.INSTANCE, null);
            channel.writeOutbound(request1);
            ByteBuf getResponse = MemcacheProtocol.response(channel.alloc(), MemcacheProtocol.Opcode.GET, (byte) 0, status.status(), request1.opaque(), 0, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER);
            channel.writeInbound(getResponse);
            assertFalse(channel.isOpen());
            assertEquals(0, getResponse.refCnt());
        } finally {
            channel.finishAndReleaseAll();
        }
    }
}
Also used : GetRequest(com.couchbase.client.core.msg.kv.GetRequest) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 4 with EmbeddedChannel

use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.

the class KeyValueMessageHandlerTest method attemptsRetryIfInstructedByErrorMap.

/**
 * If an unknown response code is returned and the consulted error map indicates a retry, it should be passed to
 * the retry orchestrator for correct handling.
 */
@Test
void attemptsRetryIfInstructedByErrorMap() {
    EmbeddedChannel channel = new EmbeddedChannel(new KeyValueMessageHandler(null, CTX, Optional.of(BUCKET)));
    ErrorMap errorMap = mock(ErrorMap.class);
    Map<Short, ErrorMap.ErrorCode> errors = new HashMap<>();
    ErrorMap.ErrorCode code = mock(ErrorMap.ErrorCode.class);
    errors.put((short) 0xFF, code);
    Set<ErrorMap.ErrorAttribute> attributes = new HashSet<>();
    attributes.add(ErrorMap.ErrorAttribute.RETRY_NOW);
    when(code.attributes()).thenReturn(attributes);
    when(errorMap.errors()).thenReturn(errors);
    channel.attr(ChannelAttributes.ERROR_MAP_KEY).set(errorMap);
    channel.pipeline().fireChannelActive();
    try {
        GetRequest request = new GetRequest("key", Duration.ofSeconds(1), CTX, CID, FailFastRetryStrategy.INSTANCE, null);
        channel.writeOutbound(request);
        ByteBuf getResponse = MemcacheProtocol.response(channel.alloc(), MemcacheProtocol.Opcode.GET, (byte) 0, (short) 0xFF, request.opaque(), 0, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER);
        channel.writeInbound(getResponse);
        ExecutionException exception = assertThrows(ExecutionException.class, () -> request.response().get());
        assertTrue(exception.getCause() instanceof RequestCanceledException);
        assertEquals("NO_MORE_RETRIES", request.cancellationReason().identifier());
        assertEquals(RetryReason.KV_ERROR_MAP_INDICATED, request.cancellationReason().innerReason());
        assertEquals(0, getResponse.refCnt());
    } finally {
        channel.finishAndReleaseAll();
    }
}
Also used : HashMap(java.util.HashMap) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) RequestCanceledException(com.couchbase.client.core.error.RequestCanceledException) GetRequest(com.couchbase.client.core.msg.kv.GetRequest) ExecutionException(java.util.concurrent.ExecutionException) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 5 with EmbeddedChannel

use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.

the class ChunkedHandlerSwitcherTest method setupChannel.

/**
 * Helper method to setup the channel with all the needed handlers and switcher.
 *
 * @return the embedded channel to use.
 */
private EmbeddedChannel setupChannel() {
    EmbeddedChannel channel = new EmbeddedChannel();
    channel.pipeline().addFirst(ChunkedHandlerSwitcher.SWITCHER_IDENTIFIER, new TestChunkedHandlerSwitcher(new TestChunkedMessageHandler(), new TestNonChunkedMessageHandler(), SearchRequest.class));
    assertNotNull(channel.pipeline().get(TestChunkedHandlerSwitcher.class));
    assertNull(channel.pipeline().get(ChunkedMessageHandler.class));
    assertNull(channel.pipeline().get(NonChunkedHttpMessageHandler.class));
    channel.pipeline().fireChannelActive();
    return channel;
}
Also used : SearchRequest(com.couchbase.client.core.msg.search.SearchRequest) ChunkedMessageHandler(com.couchbase.client.core.io.netty.chunk.ChunkedMessageHandler) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)

Aggregations

EmbeddedChannel (com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)32 Test (org.junit.jupiter.api.Test)23 EndpointContext (com.couchbase.client.core.endpoint.EndpointContext)15 ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)13 Core (com.couchbase.client.core.Core)8 CoreContext (com.couchbase.client.core.CoreContext)8 CoreEnvironment (com.couchbase.client.core.env.CoreEnvironment)8 BaseEndpoint (com.couchbase.client.core.endpoint.BaseEndpoint)7 SimpleEventBus (com.couchbase.client.core.cnc.SimpleEventBus)6 GetRequest (com.couchbase.client.core.msg.kv.GetRequest)6 DefaultHttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse)5 DefaultLastHttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent)5 HttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent)5 HttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 EndpointDisconnectedEvent (com.couchbase.client.core.cnc.events.endpoint.EndpointDisconnectedEvent)4 DefaultHttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent)4 HostAndPort (com.couchbase.client.core.util.HostAndPort)4 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 MethodSource (org.junit.jupiter.params.provider.MethodSource)4