use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.
the class MemcacheProtocolVerificationHandlerTest method shouldCloseOnInvalidResponses.
/**
* Verifies that invalid responses are not let through.
*
* @param inputHolder the bad input packets.
*/
@ParameterizedTest(name = "{0}")
@MethodSource
void shouldCloseOnInvalidResponses(final InputHolder inputHolder) {
SimpleEventBus eventBus = new SimpleEventBus(true);
CoreEnvironment env = mock(CoreEnvironment.class);
EndpointContext ctx = mock(EndpointContext.class);
when(ctx.environment()).thenReturn(env);
when(env.eventBus()).thenReturn(eventBus);
final EmbeddedChannel channel = new EmbeddedChannel(new MemcacheProtocolVerificationHandler(ctx));
try {
channel.writeInbound(inputHolder.input);
assertFalse(channel.isOpen());
InvalidPacketDetectedEvent event = (InvalidPacketDetectedEvent) eventBus.publishedEvents().get(0);
assertEquals(Event.Severity.ERROR, event.severity());
assertEquals(Event.Category.IO.path(), event.category());
assertTrue(event.description().contains("Invalid Packet detected:"));
} finally {
channel.finishAndReleaseAll();
}
}
use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.
the class SaslListMechanismsHandlerTest 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());
SaslListMechanismsHandler handler = new SaslListMechanismsHandler(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("SASL Mechanism listing timed out after 100ms", connect.cause().getMessage());
}
use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.
the class SelectBucketHandlerTest method setup.
@BeforeEach
void setup() {
channel = new EmbeddedChannel();
SimpleEventBus simpleEventBus = new SimpleEventBus(true);
CoreEnvironment env = mock(CoreEnvironment.class);
TimeoutConfig timeoutConfig = mock(TimeoutConfig.class);
when(env.eventBus()).thenReturn(simpleEventBus);
when(env.timeoutConfig()).thenReturn(timeoutConfig);
when(timeoutConfig.connectTimeout()).thenReturn(Duration.ofMillis(10));
CoreContext coreContext = new CoreContext(mock(Core.class), 1, env, mock(Authenticator.class));
endpointContext = new EndpointContext(coreContext, new HostAndPort("127.0.0.1", 1234), null, ServiceType.KV, Optional.empty(), Optional.empty(), Optional.empty());
}
use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.
the class ReactiveBatchHelper method existsBytes.
/**
* Performs the bulk logic of fetching a config and splitting up the observe requests.
*
* @param collection the collection on which the query should be performed.
* @param ids the list of ids which should be checked.
* @return a flux of all
*/
private static Flux<byte[]> existsBytes(final Collection collection, final java.util.Collection<String> ids) {
final Core core = collection.core();
final CoreEnvironment env = core.context().environment();
BucketConfig config = core.clusterConfig().bucketConfig(collection.bucketName());
if (core.configurationProvider().bucketConfigLoadInProgress() || config == null) {
// and then try again. In a steady state this should not happen.
return Mono.delay(Duration.ofMillis(100), env.scheduler()).flatMapMany(ign -> existsBytes(collection, ids));
}
long start = System.nanoTime();
if (!(config instanceof CouchbaseBucketConfig)) {
throw new IllegalStateException("Only couchbase (and ephemeral) buckets are supported at this point!");
}
Map<NodeIdentifier, Map<byte[], Short>> nodeEntries = new HashMap<>(config.nodes().size());
for (NodeInfo node : config.nodes()) {
nodeEntries.put(node.identifier(), new HashMap<>(ids.size() / config.nodes().size()));
}
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
CollectionIdentifier ci = new CollectionIdentifier(collection.bucketName(), Optional.of(collection.scopeName()), Optional.of(collection.name()));
for (String id : ids) {
byte[] encodedId = id.getBytes(StandardCharsets.UTF_8);
int partitionId = KeyValueLocator.partitionForKey(encodedId, cbc.numberOfPartitions());
int nodeId = cbc.nodeIndexForActive(partitionId, false);
NodeInfo nodeInfo = cbc.nodeAtIndex(nodeId);
nodeEntries.get(nodeInfo.identifier()).put(encodedId, (short) partitionId);
}
List<Mono<MultiObserveViaCasResponse>> responses = new ArrayList<>(nodeEntries.size());
List<MultiObserveViaCasRequest> requests = new ArrayList<>(nodeEntries.size());
for (Map.Entry<NodeIdentifier, Map<byte[], Short>> node : nodeEntries.entrySet()) {
if (node.getValue().isEmpty()) {
// service enabled and 2) have keys that we need to fetch
continue;
}
MultiObserveViaCasRequest request = new MultiObserveViaCasRequest(env.timeoutConfig().kvTimeout(), core.context(), env.retryStrategy(), ci, node.getKey(), node.getValue(), PMGET_PREDICATE);
core.send(request);
requests.add(request);
responses.add(Reactor.wrap(request, request.response(), true));
}
return Flux.merge(responses).flatMap(response -> Flux.fromIterable(response.observed().keySet())).onErrorMap(throwable -> {
BatchErrorContext ctx = new BatchErrorContext(Collections.unmodifiableList(requests));
return new BatchHelperFailureException("Failed to perform BatchHelper bulk operation", throwable, ctx);
}).doOnComplete(() -> core.context().environment().eventBus().publish(new BatchHelperExistsCompletedEvent(Duration.ofNanos(System.nanoTime() - start), new BatchErrorContext(Collections.unmodifiableList(requests)))));
}
use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.
the class NodeTest method sendsEventsIntoEventBus.
@Test
void sendsEventsIntoEventBus() {
Core core = mock(Core.class);
SimpleEventBus eventBus = new SimpleEventBus(true, Collections.singletonList(NodeStateChangedEvent.class));
CoreEnvironment env = CoreEnvironment.builder().eventBus(eventBus).build();
CoreContext ctx = new CoreContext(core, 1, env, mock(Authenticator.class));
try {
Node node = new Node(ctx, mock(NodeIdentifier.class), NO_ALTERNATE) {
@Override
protected Service createService(ServiceType serviceType, int port, Optional<String> bucket) {
Service s = mock(Service.class);
when(s.type()).thenReturn(serviceType);
when(s.states()).thenReturn(DirectProcessor.create());
when(s.state()).thenReturn(ServiceState.IDLE);
return s;
}
};
node.addService(ServiceType.QUERY, 2, Optional.empty()).block();
node.addService(ServiceType.KV, 1, Optional.of("bucket")).block();
node.addService(ServiceType.KV, 1, Optional.of("bucket")).block();
node.removeService(ServiceType.KV, Optional.of("bucket")).block();
node.removeService(ServiceType.QUERY, Optional.empty()).block();
node.removeService(ServiceType.QUERY, Optional.empty()).block();
node.disconnect().block();
node.disconnect().block();
node.addService(ServiceType.QUERY, 2, Optional.empty()).block();
node.removeService(ServiceType.QUERY, Optional.empty()).block();
List<Event> events = eventBus.publishedEvents();
assertTrue(events.remove(0) instanceof NodeConnectedEvent);
assertTrue(events.get(0) instanceof ServiceAddedEvent);
assertTrue(events.get(1) instanceof ServiceAddedEvent);
assertTrue(events.get(2) instanceof ServiceAddIgnoredEvent);
assertTrue(events.get(3) instanceof ServiceRemovedEvent);
assertTrue(events.get(4) instanceof ServiceRemovedEvent);
assertTrue(events.get(5) instanceof ServiceRemoveIgnoredEvent);
assertTrue(events.get(6) instanceof NodeDisconnectedEvent);
assertTrue(events.get(7) instanceof NodeDisconnectIgnoredEvent);
assertTrue(events.get(8) instanceof ServiceAddIgnoredEvent);
assertTrue(events.get(9) instanceof ServiceRemoveIgnoredEvent);
} finally {
env.shutdown();
}
}
Aggregations