use of com.couchbase.client.core.CoreContext in project couchbase-jdbc-driver by couchbaselabs.
the class AnalyticsProtocol method fetchResult.
@Override
public JsonParser fetchResult(QueryServiceResponse response, SubmitStatementOptions options) throws SQLException {
int p = response.handle.lastIndexOf("/");
if (p < 0) {
throw new SQLNonTransientConnectionException("Protocol error - could not extract deferred ID");
}
String handlePath = response.handle.substring(p);
Core core = connectionHandle.core();
CoreContext ctx = core.context();
AnalyticsRequest request = new AnalyticsRequest(getTimeout(options), ctx, ctx.environment().retryStrategy(), ctx.authenticator(), null, AnalyticsRequest.NO_PRIORITY, true, UUID.randomUUID().toString(), "", null, null, null, QUERY_RESULT_ENDPOINT_PATH + handlePath, HttpMethod.GET);
core.send(request);
try {
AnalyticsResponse analyticsResponse = block(request.response());
PipedOutputStream pos = new PipedOutputStream();
InputStream is = new PipedInputStream(pos);
rowExecutor.submit(() -> {
try {
final AtomicBoolean first = new AtomicBoolean(true);
Stream<AnalyticsChunkRow> rows = analyticsResponse.rows().toStream();
pos.write('[');
rows.forEach(row -> {
try {
if (!first.compareAndSet(true, false)) {
pos.write(',');
}
pos.write(row.data());
} catch (IOException e) {
throw new RuntimeException("Failed to parse JSON row", e);
}
});
pos.write(']');
} catch (Exception e) {
throw new RuntimeException("Failure during streaming rows", e);
} finally {
try {
pos.close();
} catch (IOException e) {
// ignored.
}
}
});
return driverContext.getGenericObjectReader().getFactory().createParser(is);
} catch (JsonProcessingException e) {
throw getErrorReporter().errorInProtocol(e);
} catch (IOException e) {
throw getErrorReporter().errorInConnection(e);
} catch (Exception e) {
throw getErrorReporter().errorInConnection(e.getMessage());
}
}
use of com.couchbase.client.core.CoreContext in project couchbase-jvm-clients by couchbase.
the class BaseEndpointIntegrationTest method mustReconnectWhenChannelCloses.
/**
* When the underlying channel closes, the endpoint must continue to reconnect until being instructed
* to stop with an explicit disconnect command.
*/
@Test
void mustReconnectWhenChannelCloses() {
LocalServerController localServerController = startLocalServer(eventLoopGroup);
ServiceContext serviceContext = new ServiceContext(new CoreContext(null, 1, env, authenticator()), "127.0.0.1", 1234, ServiceType.KV, Optional.empty());
BaseEndpoint endpoint = new BaseEndpoint("127.0.0.1", 1234, eventLoopGroup, serviceContext, CircuitBreakerConfig.enabled(false).build(), ServiceType.QUERY, false) {
@Override
protected PipelineInitializer pipelineInitializer() {
return (endpoint, pipeline) -> {
};
}
@Override
protected SocketAddress remoteAddress() {
return new LocalAddress("server");
}
};
List<EndpointState> transitions = Collections.synchronizedList(new ArrayList<>());
endpoint.states().subscribe(transitions::add);
assertEquals(0, localServerController.connectAttempts.get());
assertNull(localServerController.channel.get());
endpoint.connect();
waitUntilCondition(() -> endpoint.state() == EndpointState.CONNECTED);
waitUntilCondition(() -> localServerController.connectAttempts.get() == 1);
assertNotNull(localServerController.channel.get());
localServerController.channel.get().close().awaitUninterruptibly();
List<EndpointState> expectedTransitions = Arrays.asList(// initial state
EndpointState.DISCONNECTED, // initial connect attempt
EndpointState.CONNECTING, // properly connected the first time
EndpointState.CONNECTED, // disconnected when we kill the channel from the server side
EndpointState.DISCONNECTED, // endpoint should be reconnecting now
EndpointState.CONNECTING, // finally, we are able to reconnect completely
EndpointState.CONNECTED);
waitUntilCondition(() -> transitions.size() == expectedTransitions.size());
assertEquals(expectedTransitions, transitions);
waitUntilCondition(() -> localServerController.connectAttempts.get() >= 2);
endpoint.disconnect();
waitUntilCondition(() -> endpoint.state() == EndpointState.DISCONNECTED);
boolean hasDisconnectEvent = false;
for (Event event : eventBus.publishedEvents()) {
if (event instanceof UnexpectedEndpointDisconnectedEvent) {
hasDisconnectEvent = true;
break;
}
}
assertTrue(hasDisconnectEvent);
}
use of com.couchbase.client.core.CoreContext in project couchbase-jvm-clients by couchbase.
the class KeyValueEndpointIntegrationTest method beforeAll.
@BeforeAll
static void beforeAll() {
TestNodeConfig node = config().nodes().get(0);
env = environment().build();
core = Core.create(env, authenticator(), seedNodes());
serviceContext = new ServiceContext(new CoreContext(core, 1, env, authenticator()), node.hostname(), node.ports().get(Services.KV), ServiceType.KV, Optional.empty());
}
use of com.couchbase.client.core.CoreContext in project couchbase-jvm-clients by couchbase.
the class ViewEndpointIntegrationTest method beforeAll.
@BeforeAll
static void beforeAll() {
TestNodeConfig node = config().nodes().get(0);
env = environment().ioConfig(IoConfig.captureTraffic(ServiceType.VIEWS)).build();
serviceContext = new ServiceContext(new CoreContext(null, 1, env, authenticator()), node.hostname(), node.ports().get(Services.VIEW), ServiceType.VIEWS, Optional.empty());
}
use of com.couchbase.client.core.CoreContext 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();
}
}
Aggregations