use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.
the class PasswordAuthenticatorTest method shouldNotNegotiatePlainWithNonTlsByDefault.
@Test
void shouldNotNegotiatePlainWithNonTlsByDefault() {
PasswordAuthenticator authenticator = PasswordAuthenticator.create("user", "pass");
EndpointContext ctx = mock(EndpointContext.class);
when(ctx.environment()).thenReturn(ENV);
EmbeddedChannel channel = new EmbeddedChannel();
authenticator.authKeyValueConnection(ctx, channel.pipeline());
SaslAuthenticationHandler handler = channel.pipeline().get(SaslAuthenticationHandler.class);
assertFalse(handler.allowedMechanisms().contains(SaslMechanism.PLAIN));
}
use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.
the class SearchMock method loadSearchTestCase.
/**
* Given JSON in the form expected, e.g. those from https://github.com/chvck/sdk-testcases which contains the
* returned JSON from the search service in a field "data", returns the completed SearchResult that the API
* would return.
*/
public static SearchResult loadSearchTestCase(InputStream json) throws ExecutionException, InterruptedException, IOException {
// The idea is to fake packets that have come from the search service.
// Start by preparing the packets.
JsonObject jo = JsonObject.fromJson(toByteArray(json));
JsonObject data = jo.getObject("data");
byte[] b = data.toString().getBytes(StandardCharsets.UTF_8);
ByteBuf bytes = Unpooled.wrappedBuffer(b);
HttpContent content = new DefaultLastHttpContent(bytes);
HttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
// Fake some core stuff
Core mockedCore = mock(Core.class);
CoreEnvironment env = CoreEnvironment.create();
CoreContext ctx = new CoreContext(mockedCore, 0, env, PasswordAuthenticator.create("Administrator", "password"));
// Our ChunkedSearchMessageHandler needs to be initialised by pretending we've sent an outbound SearchRequest
// through it
SearchRequest req = new SearchRequest(Duration.ofSeconds(10), ctx, BestEffortRetryStrategy.INSTANCE, null, null, null, null);
// ChunkedSearchMessageHandler will try to encode() the SearchRequest. Rather than mocking everything required
// to get that working, just mock the encode method.
SearchRequest spiedReq = spy(req);
doReturn(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "localhost")).when(spiedReq).encode();
doAnswer(v -> {
EndpointContext endpointContext = new EndpointContext(ctx, new HostAndPort(null, 0), null, null, null, Optional.of("bucket"), null);
BaseEndpoint endpoint = mock(BaseEndpoint.class);
when(endpoint.context()).thenReturn(endpointContext);
when(endpoint.pipelined()).thenReturn(false);
// ChunkedSearchMessageHandler does most of the work in handling responses from the service
ChunkedSearchMessageHandler handler = new ChunkedSearchMessageHandler(endpoint, endpointContext);
// Netty's EmbeddedChannel lets us test ChannelHandlers like ChunkedSearchMessageHandler. It's a Netty Channel
// that doesn't touch the network at all.
final EmbeddedChannel channel = new EmbeddedChannel(handler);
// Writing the request is necessary to estabish some initial state inChunkedSearchMessageHandler
channel.writeAndFlush(spiedReq);
// Finally we can do the interesting bit of passing our fake FTS service response into
// ChunkedSearchMessageHandler
channel.writeInbound(resp);
channel.writeInbound(content);
return null;
}).when(mockedCore).send(any());
CompletableFuture<SearchResult> future = SearchAccessor.searchQueryAsync(mockedCore, req, DefaultJsonSerializer.create());
SearchResult result = future.get();
return result;
}
use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.
the class ErrorMapLoadingHandlerTest method failConnectIfPromiseTimesOut.
/**
* This test makes sure that the timer fires if the connect future is not completed
* otherwise.
*/
@Test
void failConnectIfPromiseTimesOut() throws Exception {
channel = new EmbeddedChannel();
eventBus = new SimpleEventBus(true);
CoreEnvironment env = mock(CoreEnvironment.class);
TimeoutConfig timeoutConfig = mock(TimeoutConfig.class);
when(env.eventBus()).thenReturn(eventBus);
when(env.timeoutConfig()).thenReturn(timeoutConfig);
when(timeoutConfig.connectTimeout()).thenReturn(Duration.ofMillis(100));
CoreContext coreContext = new CoreContext(mock(Core.class), 1, env, mock(Authenticator.class));
EndpointContext endpointContext = new EndpointContext(coreContext, new HostAndPort("127.0.0.1", 1234), null, ServiceType.KV, Optional.empty(), Optional.empty(), Optional.empty());
ErrorMapLoadingHandler handler = new ErrorMapLoadingHandler(endpointContext);
channel.pipeline().addLast(handler);
final ChannelFuture connect = channel.connect(new InetSocketAddress("1.2.3.4", 1234));
channel.pipeline().fireChannelActive();
Thread.sleep(Duration.ofMillis(100).toMillis() + 5);
channel.runScheduledPendingTasks();
assertTrue(connect.isDone());
assertTrue(connect.cause() instanceof TimeoutException);
assertEquals("KV Error Map loading timed out after 100ms", connect.cause().getMessage());
}
use of com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel in project couchbase-jvm-clients by couchbase.
the class KeyValueMessageHandlerTest method retriesCertainResponseStatusCodes.
/**
* Certain status codes are identified that should be passed to the retry orchestrator rathen than complete
* the response right away.
*/
@Test
void retriesCertainResponseStatusCodes() {
List<MemcacheProtocol.Status> retryOnThese = Arrays.asList(MemcacheProtocol.Status.LOCKED, MemcacheProtocol.Status.TEMPORARY_FAILURE, MemcacheProtocol.Status.SYNC_WRITE_IN_PROGRESS, MemcacheProtocol.Status.SYNC_WRITE_RE_COMMIT_IN_PROGRESS);
List<RetryReason> retryReasons = Arrays.asList(RetryReason.KV_LOCKED, RetryReason.KV_TEMPORARY_FAILURE, RetryReason.KV_SYNC_WRITE_IN_PROGRESS, RetryReason.KV_SYNC_WRITE_RE_COMMIT_IN_PROGRESS);
int i = 0;
for (MemcacheProtocol.Status status : retryOnThese) {
EmbeddedChannel channel = new EmbeddedChannel(new KeyValueMessageHandler(null, CTX, Optional.of(BUCKET)));
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, status.status(), request.opaque(), 0, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER);
channel.writeInbound(getResponse);
assertEquals(CancellationReason.noMoreRetries(retryReasons.get(i)), request.cancellationReason());
assertEquals(0, getResponse.refCnt());
i++;
} 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 opaqueIsIncreasing.
/**
* This test sends two get requests and makes sure the latter one has a higher opaque then the
* former one.
*/
@Test
void opaqueIsIncreasing() {
EmbeddedChannel channel = new EmbeddedChannel(new KeyValueMessageHandler(null, CTX, Optional.of(BUCKET)));
try {
channel.writeOutbound(new GetRequest("key", Duration.ofSeconds(1), CTX, CID, null, null));
channel.flushOutbound();
ByteBuf request = channel.readOutbound();
int firstOpaque = MemcacheProtocol.opaque(request);
assertTrue(firstOpaque > 0);
ReferenceCountUtil.release(request);
channel.writeOutbound(new GetRequest("key", Duration.ofSeconds(1), CTX, CID, null, null));
channel.flushOutbound();
request = channel.readOutbound();
int secondOpaque = MemcacheProtocol.opaque(request);
assertTrue(secondOpaque > firstOpaque);
ReferenceCountUtil.release(request);
} finally {
channel.finishAndReleaseAll();
}
}
Aggregations