Search in sources :

Example 1 with CoreContext

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());
    }
}
Also used : CoreContext(com.couchbase.client.core.CoreContext) PipedInputStream(java.io.PipedInputStream) InputStream(java.io.InputStream) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) IOException(java.io.IOException) AnalyticsChunkRow(com.couchbase.client.core.msg.analytics.AnalyticsChunkRow) SQLException(java.sql.SQLException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) InvalidArgumentException(com.couchbase.client.core.error.InvalidArgumentException) InvalidDefinitionException(com.fasterxml.jackson.databind.exc.InvalidDefinitionException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AnalyticsResponse(com.couchbase.client.core.msg.analytics.AnalyticsResponse) AnalyticsRequest(com.couchbase.client.core.msg.analytics.AnalyticsRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Core(com.couchbase.client.core.Core)

Example 2 with CoreContext

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);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) SocketAddress(java.net.SocketAddress) SimpleChannelInboundHandler(com.couchbase.client.core.deps.io.netty.channel.SimpleChannelInboundHandler) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) ServerBootstrap(com.couchbase.client.core.deps.io.netty.bootstrap.ServerBootstrap) CoreIntegrationTest(com.couchbase.client.core.util.CoreIntegrationTest) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) LocalAddress(com.couchbase.client.core.deps.io.netty.channel.local.LocalAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServiceType(com.couchbase.client.core.service.ServiceType) CoreContext(com.couchbase.client.core.CoreContext) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) UnexpectedEndpointDisconnectedEvent(com.couchbase.client.core.cnc.events.endpoint.UnexpectedEndpointDisconnectedEvent) ServiceContext(com.couchbase.client.core.service.ServiceContext) Channel(com.couchbase.client.core.deps.io.netty.channel.Channel) ChannelHandlerContext(com.couchbase.client.core.deps.io.netty.channel.ChannelHandlerContext) Util.waitUntilCondition(com.couchbase.client.test.Util.waitUntilCondition) ChannelInitializer(com.couchbase.client.core.deps.io.netty.channel.ChannelInitializer) Event(com.couchbase.client.core.cnc.Event) LocalServerChannel(com.couchbase.client.core.deps.io.netty.channel.local.LocalServerChannel) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) DefaultEventLoopGroup(com.couchbase.client.core.deps.io.netty.channel.DefaultEventLoopGroup) Test(org.junit.jupiter.api.Test) SimpleEventBus(com.couchbase.client.core.cnc.SimpleEventBus) AfterEach(org.junit.jupiter.api.AfterEach) List(java.util.List) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) Collections(java.util.Collections) CoreContext(com.couchbase.client.core.CoreContext) LocalAddress(com.couchbase.client.core.deps.io.netty.channel.local.LocalAddress) ServiceContext(com.couchbase.client.core.service.ServiceContext) UnexpectedEndpointDisconnectedEvent(com.couchbase.client.core.cnc.events.endpoint.UnexpectedEndpointDisconnectedEvent) UnexpectedEndpointDisconnectedEvent(com.couchbase.client.core.cnc.events.endpoint.UnexpectedEndpointDisconnectedEvent) Event(com.couchbase.client.core.cnc.Event) CoreIntegrationTest(com.couchbase.client.core.util.CoreIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 3 with CoreContext

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());
}
Also used : CoreContext(com.couchbase.client.core.CoreContext) ServiceContext(com.couchbase.client.core.service.ServiceContext) TestNodeConfig(com.couchbase.client.test.TestNodeConfig) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 4 with CoreContext

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());
}
Also used : CoreContext(com.couchbase.client.core.CoreContext) ServiceContext(com.couchbase.client.core.service.ServiceContext) TestNodeConfig(com.couchbase.client.test.TestNodeConfig) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 5 with CoreContext

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

Aggregations

CoreContext (com.couchbase.client.core.CoreContext)52 Core (com.couchbase.client.core.Core)46 Test (org.junit.jupiter.api.Test)25 CoreEnvironment (com.couchbase.client.core.env.CoreEnvironment)22 Authenticator (com.couchbase.client.core.env.Authenticator)17 SimpleEventBus (com.couchbase.client.core.cnc.SimpleEventBus)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 EndpointContext (com.couchbase.client.core.endpoint.EndpointContext)12 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 ArrayList (java.util.ArrayList)10 EmbeddedChannel (com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)9 HostAndPort (com.couchbase.client.core.util.HostAndPort)9 List (java.util.List)8 TimeoutConfig (com.couchbase.client.core.env.TimeoutConfig)7 ServiceContext (com.couchbase.client.core.service.ServiceContext)7 Duration (java.time.Duration)7 Optional (java.util.Optional)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 SeedNode (com.couchbase.client.core.env.SeedNode)6 Event (com.couchbase.client.core.cnc.Event)5