Search in sources :

Example 1 with ByteBuf

use of com.couchbase.client.core.deps.io.netty.buffer.ByteBuf in project couchbase-jvm-clients by couchbase.

the class ErrorMapLoadingHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
    if (msg instanceof ByteBuf) {
        if (successful((ByteBuf) msg)) {
            Optional<ErrorMap> loadedMap = extractErrorMap((ByteBuf) msg);
            loadedMap.ifPresent(errorMap -> ctx.channel().attr(ChannelAttributes.ERROR_MAP_KEY).set(errorMap));
            endpointContext.environment().eventBus().publish(new ErrorMapLoadedEvent(ioContext, latency.orElse(Duration.ZERO), loadedMap));
        } else {
            endpointContext.environment().eventBus().publish(new ErrorMapLoadingFailedEvent(ioContext, latency.orElse(Duration.ZERO), status((ByteBuf) msg)));
        }
        interceptedConnectPromise.trySuccess();
        ctx.pipeline().remove(this);
    } else {
        interceptedConnectPromise.tryFailure(new CouchbaseException("Unexpected response " + "type on channel read, this is a bug - please report. " + msg));
    }
    ReferenceCountUtil.release(msg);
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) Duration(java.time.Duration) ErrorMapLoadingFailedEvent(com.couchbase.client.core.cnc.events.io.ErrorMapLoadingFailedEvent) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) ErrorMapLoadedEvent(com.couchbase.client.core.cnc.events.io.ErrorMapLoadedEvent)

Example 2 with ByteBuf

use of com.couchbase.client.core.deps.io.netty.buffer.ByteBuf in project couchbase-jvm-clients by couchbase.

the class FeatureNegotiatingHandler method channelRead.

/**
 * As soon as we get a response, turn it into a list of negotiated server features.
 *
 * <p>Since the server might respond with a non-success status code, this case is handled
 * and we would move on without any negotiated features but make sure the proper event
 * is raised.</p>
 *
 * @param ctx the {@link ChannelHandlerContext} for which the channel read operation is made.
 * @param msg the incoming msg that needs to be parsed.
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof ByteBuf) {
        Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
        if (!successful((ByteBuf) msg)) {
            endpointContext.environment().eventBus().publish(new FeaturesNegotiationFailedEvent(ioContext, status((ByteBuf) msg)));
        }
        Set<ServerFeature> negotiated = extractFeaturesFromBody((ByteBuf) msg);
        ctx.channel().attr(ChannelAttributes.SERVER_FEATURE_KEY).set(negotiated);
        endpointContext.environment().eventBus().publish(new FeaturesNegotiatedEvent(ioContext, latency.orElse(Duration.ZERO), new ArrayList<>(negotiated)));
        interceptedConnectPromise.trySuccess();
        ctx.pipeline().remove(this);
    } else {
        interceptedConnectPromise.tryFailure(new CouchbaseException("Unexpected response " + "type on channel read, this is a bug - please report. " + msg));
    }
    ReferenceCountUtil.release(msg);
}
Also used : FeaturesNegotiationFailedEvent(com.couchbase.client.core.cnc.events.io.FeaturesNegotiationFailedEvent) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ArrayList(java.util.ArrayList) Duration(java.time.Duration) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) FeaturesNegotiatedEvent(com.couchbase.client.core.cnc.events.io.FeaturesNegotiatedEvent)

Example 3 with ByteBuf

use of com.couchbase.client.core.deps.io.netty.buffer.ByteBuf in project couchbase-jvm-clients by couchbase.

the class FeatureNegotiatingHandler method buildHelloRequest.

/**
 * Helper method to build the HELLO request which will be sent to the server.
 *
 * @param ctx the {@link ChannelHandlerContext} for which the channel active operation is made.
 * @return the created request as a {@link ByteBuf}.
 */
private ByteBuf buildHelloRequest(final ChannelHandlerContext ctx) {
    ByteBuf key = buildHelloKey(ctx);
    ByteBuf body = ctx.alloc().buffer(features.size() * 2);
    for (ServerFeature feature : features) {
        body.writeShort(feature.value());
    }
    ByteBuf request = MemcacheProtocol.request(ctx.alloc(), MemcacheProtocol.Opcode.HELLO, noDatatype(), noPartition(), BaseKeyValueRequest.nextOpaque(), noCas(), noExtras(), key, body);
    key.release();
    body.release();
    return request;
}
Also used : ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)

Example 4 with ByteBuf

use of com.couchbase.client.core.deps.io.netty.buffer.ByteBuf in project couchbase-jvm-clients by couchbase.

the class KeyValueMessageHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    try {
        if (msg instanceof ByteBuf) {
            decode(ctx, (ByteBuf) msg);
        } else {
            ioContext.environment().eventBus().publish(new UnsupportedResponseTypeReceivedEvent(ioContext, msg));
            closeChannelWithReason(ioContext, ctx, ChannelClosedProactivelyEvent.Reason.INVALID_RESPONSE_FORMAT_DETECTED);
        }
    } finally {
        if (endpoint != null) {
            endpoint.markRequestCompletion();
        }
        ReferenceCountUtil.release(msg);
    }
}
Also used : UnsupportedResponseTypeReceivedEvent(com.couchbase.client.core.cnc.events.io.UnsupportedResponseTypeReceivedEvent) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)

Example 5 with ByteBuf

use of com.couchbase.client.core.deps.io.netty.buffer.ByteBuf 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();
}
Also used : FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) QueryRequest(com.couchbase.client.core.msg.query.QueryRequest) 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) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) BaseEndpoint(com.couchbase.client.core.endpoint.BaseEndpoint) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) 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) Test(org.junit.jupiter.api.Test)

Aggregations

ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)107 Test (org.junit.jupiter.api.Test)54 InetSocketAddress (java.net.InetSocketAddress)17 EmbeddedChannel (com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)12 ChannelFuture (com.couchbase.client.core.deps.io.netty.channel.ChannelFuture)11 Duration (java.time.Duration)10 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)9 CoreContext (com.couchbase.client.core.CoreContext)8 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)8 CompressionConfig (com.couchbase.client.core.env.CompressionConfig)6 ResponseStatus (com.couchbase.client.core.msg.ResponseStatus)6 GetRequest (com.couchbase.client.core.msg.kv.GetRequest)6 ChannelHandlerContext (com.couchbase.client.core.deps.io.netty.channel.ChannelHandlerContext)5 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)5 ArrayList (java.util.ArrayList)5 DurabilityTimeoutCoercedEvent (com.couchbase.client.core.cnc.events.io.DurabilityTimeoutCoercedEvent)4 FeaturesNegotiatedEvent (com.couchbase.client.core.cnc.events.io.FeaturesNegotiatedEvent)4 CompositeByteBuf (com.couchbase.client.core.deps.io.netty.buffer.CompositeByteBuf)4 FullHttpRequest (com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest)4 BaseEndpoint (com.couchbase.client.core.endpoint.BaseEndpoint)4