Search in sources :

Example 1 with FullHttpRequest

use of com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest in project couchbase-jvm-clients by couchbase.

the class RawManager method callManagement.

private static Mono<RawManagerResponse> callManagement(final Cluster cluster, final RawManagerRequest request, final RawManagerOptions options) {
    final ClusterEnvironment environment = cluster.environment();
    final RawManagerOptions.Built opts = options.build();
    JsonSerializer serializer = opts.serializer() != null ? opts.serializer() : environment.jsonSerializer();
    Duration timeout = opts.timeout().orElse(environment.timeoutConfig().managementTimeout());
    RetryStrategy retryStrategy = opts.retryStrategy().orElse(environment.retryStrategy());
    final GenericManagerRequest req = new GenericManagerRequest(timeout, cluster.core().context(), retryStrategy, () -> {
        FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, request.method(), request.uri());
        for (Map.Entry<String, Object> e : opts.httpHeaders().entrySet()) {
            httpRequest.headers().set(e.getKey(), e.getValue());
        }
        return httpRequest;
    }, request.method().equals(HttpMethod.GET), null);
    cluster.core().send(req);
    return Reactor.wrap(req, req.response(), true).map(res -> new RawManagerResponse(request.serviceType(), serializer, res.httpStatus(), res.content()));
}
Also used : FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultFullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultFullHttpRequest) Duration(java.time.Duration) JsonSerializer(com.couchbase.client.java.codec.JsonSerializer) ClusterEnvironment(com.couchbase.client.java.env.ClusterEnvironment) GenericManagerRequest(com.couchbase.client.core.msg.manager.GenericManagerRequest) RetryStrategy(com.couchbase.client.core.retry.RetryStrategy) Map(java.util.Map)

Example 2 with FullHttpRequest

use of com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest in project couchbase-jvm-clients by couchbase.

the class ChunkedMessageHandler method write.

@Override
@SuppressWarnings("unchecked")
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
    // toes.
    if (!pipelined && currentRequest != null) {
        RetryOrchestrator.maybeRetry(endpointContext, (REQ) msg, RetryReason.NOT_PIPELINED_REQUEST_IN_FLIGHT);
        if (endpoint != null) {
            endpoint.decrementOutstandingRequests();
        }
        return;
    }
    try {
        currentRequest = (REQ) msg;
        FullHttpRequest encoded = currentRequest.encode();
        encoded.headers().set(HttpHeaderNames.HOST, remoteHost);
        encoded.headers().set(HttpHeaderNames.USER_AGENT, endpointContext.environment().userAgent().formattedLong());
        chunkResponseParser.updateRequestContext(currentRequest.context());
        dispatchTimingStart = System.nanoTime();
        if (currentRequest.requestSpan() != null) {
            RequestTracer tracer = endpointContext.environment().requestTracer();
            currentDispatchSpan = tracer.requestSpan(TracingIdentifiers.SPAN_DISPATCH, currentRequest.requestSpan());
            if (!CbTracing.isInternalTracer(tracer)) {
                setCommonDispatchSpanAttributes(currentDispatchSpan, ctx.channel().attr(ChannelAttributes.CHANNEL_ID_KEY).get(), ioContext.localHostname(), ioContext.localPort(), endpoint.remoteHostname(), endpoint.remotePort(), currentRequest.operationId());
            }
        }
        ctx.write(encoded, promise);
    } catch (Throwable t) {
        currentRequest.response().completeExceptionally(t);
        if (endpoint != null) {
            endpoint.decrementOutstandingRequests();
        }
    }
}
Also used : FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) RequestTracer(com.couchbase.client.core.cnc.RequestTracer)

Example 3 with FullHttpRequest

use of com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest in project couchbase-jvm-clients by couchbase.

the class NonChunkedHttpMessageHandler method write.

/**
 * Writes a given request and encodes it.
 *
 * @param ctx the channel handler context.
 * @param msg the msg to write.
 * @param promise the promise that will be passed along.
 */
@Override
@SuppressWarnings("unchecked")
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
    // toes.
    if (currentRequest != null) {
        RetryOrchestrator.maybeRetry(endpointContext, (Request<? extends Response>) msg, RetryReason.NOT_PIPELINED_REQUEST_IN_FLIGHT);
        if (endpoint != null) {
            endpoint.decrementOutstandingRequests();
        }
        return;
    }
    if (msg instanceof NonChunkedHttpRequest) {
        try {
            currentRequest = (NonChunkedHttpRequest<Response>) msg;
            FullHttpRequest encoded = ((NonChunkedHttpRequest<Response>) msg).encode();
            encoded.headers().set(HttpHeaderNames.HOST, remoteHost);
            encoded.headers().set(HttpHeaderNames.USER_AGENT, endpointContext.environment().userAgent().formattedLong());
            dispatchTimingStart = System.nanoTime();
            if (currentRequest.requestSpan() != null) {
                RequestTracer tracer = endpointContext.environment().requestTracer();
                currentDispatchSpan = tracer.requestSpan(TracingIdentifiers.SPAN_DISPATCH, currentRequest.requestSpan());
                if (!CbTracing.isInternalTracer(tracer)) {
                    setCommonDispatchSpanAttributes(currentDispatchSpan, ctx.channel().attr(ChannelAttributes.CHANNEL_ID_KEY).get(), ioContext.localHostname(), ioContext.localPort(), endpoint.remoteHostname(), endpoint.remotePort(), currentRequest.operationId());
                }
            }
            ctx.write(encoded, promise);
        } catch (Throwable t) {
            currentRequest.response().completeExceptionally(t);
            if (endpoint != null) {
                endpoint.decrementOutstandingRequests();
            }
        }
    } else {
        if (endpoint != null) {
            endpoint.decrementOutstandingRequests();
        }
        eventBus.publish(new InvalidRequestDetectedEvent(ioContext, serviceType, msg));
        ctx.channel().close().addListener(f -> eventBus.publish(new ChannelClosedProactivelyEvent(ioContext, ChannelClosedProactivelyEvent.Reason.INVALID_REQUEST_DETECTED)));
    }
}
Also used : FullHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpResponse) Response(com.couchbase.client.core.msg.Response) FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) ChannelClosedProactivelyEvent(com.couchbase.client.core.cnc.events.io.ChannelClosedProactivelyEvent) NonChunkedHttpRequest(com.couchbase.client.core.msg.NonChunkedHttpRequest) RequestTracer(com.couchbase.client.core.cnc.RequestTracer) InvalidRequestDetectedEvent(com.couchbase.client.core.cnc.events.io.InvalidRequestDetectedEvent)

Example 4 with FullHttpRequest

use of com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest 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)

Example 5 with FullHttpRequest

use of com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest in project couchbase-jvm-clients by couchbase.

the class ManagerMessageHandler method write.

@Override
@SuppressWarnings({ "unchecked" })
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
    if (msg instanceof ManagerRequest) {
        if (currentRequest != null) {
            RetryOrchestrator.maybeRetry(coreContext, (ManagerRequest<Response>) msg, RetryReason.NOT_PIPELINED_REQUEST_IN_FLIGHT);
            if (endpoint != null) {
                endpoint.decrementOutstandingRequests();
            }
            return;
        }
        try {
            currentRequest = (ManagerRequest<Response>) msg;
            FullHttpRequest encoded = currentRequest.encode();
            encoded.headers().set(HttpHeaderNames.HOST, remoteHost);
            encoded.headers().set(HttpHeaderNames.USER_AGENT, endpoint.context().environment().userAgent().formattedLong());
            ctx.writeAndFlush(encoded);
        } catch (Throwable t) {
            currentRequest.response().completeExceptionally(t);
            if (endpoint != null) {
                endpoint.decrementOutstandingRequests();
            }
        }
        currentContent.clear();
    } else {
        if (endpoint != null) {
            endpoint.decrementOutstandingRequests();
        }
        eventBus.publish(new InvalidRequestDetectedEvent(ioContext, ServiceType.MANAGER, msg));
        ctx.channel().close().addListener(f -> eventBus.publish(new ChannelClosedProactivelyEvent(ioContext, ChannelClosedProactivelyEvent.Reason.INVALID_REQUEST_DETECTED)));
    }
}
Also used : BucketConfigStreamingResponse(com.couchbase.client.core.msg.manager.BucketConfigStreamingResponse) HttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse) Response(com.couchbase.client.core.msg.Response) ManagerRequest(com.couchbase.client.core.msg.manager.ManagerRequest) FullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest) ChannelClosedProactivelyEvent(com.couchbase.client.core.cnc.events.io.ChannelClosedProactivelyEvent) InvalidRequestDetectedEvent(com.couchbase.client.core.cnc.events.io.InvalidRequestDetectedEvent)

Aggregations

FullHttpRequest (com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest)14 DefaultFullHttpRequest (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultFullHttpRequest)7 ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)4 Test (org.junit.jupiter.api.Test)3 RequestTracer (com.couchbase.client.core.cnc.RequestTracer)2 ChannelClosedProactivelyEvent (com.couchbase.client.core.cnc.events.io.ChannelClosedProactivelyEvent)2 InvalidRequestDetectedEvent (com.couchbase.client.core.cnc.events.io.InvalidRequestDetectedEvent)2 FullHttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpResponse)2 HttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse)2 Response (com.couchbase.client.core.msg.Response)2 GenericManagerRequest (com.couchbase.client.core.msg.manager.GenericManagerRequest)2 Core (com.couchbase.client.core.Core)1 EmbeddedChannel (com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)1 DefaultFullHttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultFullHttpResponse)1 DefaultHttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpContent)1 DefaultHttpResponse (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse)1 DefaultLastHttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent)1 HttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent)1 HttpMethod (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpMethod)1 LastHttpContent (com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent)1