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();
}
}
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();
}
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();
}
}
}
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();
}
}
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;
}
Aggregations