Search in sources :

Example 1 with Response

use of com.couchbase.client.core.msg.Response in project couchbase-jvm-clients by couchbase.

the class NonChunkedHttpMessageHandler method channelRead.

/**
 * Parses the full http response and sends it to decode into the request.
 *
 * @param ctx the channel handler context.
 * @param msg the FullHttpResponse from the server.
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    try {
        if (msg instanceof FullHttpResponse) {
            try {
                currentRequest.context().dispatchLatency(System.nanoTime() - dispatchTimingStart);
                if (currentDispatchSpan != null) {
                    currentDispatchSpan.end();
                }
                FullHttpResponse httpResponse = (FullHttpResponse) msg;
                ResponseStatus responseStatus = HttpProtocol.decodeStatus(httpResponse.status());
                if (!currentRequest.completed()) {
                    if (responseStatus == ResponseStatus.SUCCESS) {
                        Response response = currentRequest.decode(httpResponse, channelContext);
                        currentRequest.succeed(response);
                    } else {
                        String body = httpResponse.content().toString(StandardCharsets.UTF_8);
                        Exception error = currentRequest.bypassExceptionTranslation() ? failRequestWithHttpStatusCodeException(httpResponse.status(), body, currentRequest) : failRequestWith(httpResponse.status(), body, currentRequest);
                        currentRequest.fail(error);
                    }
                } else {
                    ioContext.environment().orphanReporter().report(currentRequest);
                }
            } catch (Throwable ex) {
                currentRequest.fail(ex);
            } finally {
                currentRequest = null;
                currentDispatchSpan = null;
                endpoint.markRequestCompletion();
            }
        } else {
            ioContext.environment().eventBus().publish(new UnsupportedResponseTypeReceivedEvent(ioContext, msg));
            closeChannelWithReason(ioContext, ctx, ChannelClosedProactivelyEvent.Reason.INVALID_RESPONSE_FORMAT_DETECTED);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : FullHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpResponse) Response(com.couchbase.client.core.msg.Response) HttpResponseStatus(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponseStatus) ResponseStatus(com.couchbase.client.core.msg.ResponseStatus) UnsupportedResponseTypeReceivedEvent(com.couchbase.client.core.cnc.events.io.UnsupportedResponseTypeReceivedEvent) FullHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpResponse) HttpStatusCodeException(com.couchbase.client.core.error.HttpStatusCodeException)

Example 2 with Response

use of com.couchbase.client.core.msg.Response 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 3 with Response

use of com.couchbase.client.core.msg.Response 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)

Example 4 with Response

use of com.couchbase.client.core.msg.Response in project couchbase-jvm-clients by couchbase.

the class ManagerMessageHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpResponse) {
        currentResponse = ((HttpResponse) msg);
        if (isStreamingConfigRequest()) {
            streamingResponse = (BucketConfigStreamingResponse) currentRequest.decode(currentResponse, null);
            currentRequest.succeed(streamingResponse);
            ctx.pipeline().addFirst(new IdleStateHandler(coreContext.environment().ioConfig().configIdleRedialTimeout().toMillis(), 0, 0, TimeUnit.MILLISECONDS));
        }
    } else if (msg instanceof HttpContent) {
        currentContent.writeBytes(((HttpContent) msg).content());
        if (isStreamingConfigRequest()) {
            // there might be more than one config in the full batch, so keep iterating until all are pushed
            while (true) {
                String encodedConfig = currentContent.toString(StandardCharsets.UTF_8);
                int separatorIndex = encodedConfig.indexOf("\n\n\n\n");
                // if -1 is returned it means that no full config has been located yet, need to wait for more chunks
                if (separatorIndex >= 0) {
                    String content = encodedConfig.substring(0, separatorIndex);
                    streamingResponse.pushConfig(content.trim());
                    currentContent.clear();
                    currentContent.writeBytes(encodedConfig.substring(separatorIndex + 4).getBytes(StandardCharsets.UTF_8));
                } else {
                    break;
                }
            }
        }
        if (msg instanceof LastHttpContent) {
            if (isStreamingConfigRequest()) {
                streamingResponse.completeStream();
                streamingResponse = null;
                ctx.pipeline().remove(IdleStateHandler.class);
            } else {
                byte[] copy = new byte[currentContent.readableBytes()];
                currentContent.readBytes(copy);
                Response response = currentRequest.decode(currentResponse, copy);
                currentRequest.succeed(response);
            }
            currentRequest = null;
            if (endpoint != null) {
                endpoint.markRequestCompletion();
            }
        }
    } else {
        ioContext.environment().eventBus().publish(new UnsupportedResponseTypeReceivedEvent(ioContext, msg));
    }
    ReferenceCountUtil.release(msg);
}
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) IdleStateHandler(com.couchbase.client.core.deps.io.netty.handler.timeout.IdleStateHandler) HttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse) UnsupportedResponseTypeReceivedEvent(com.couchbase.client.core.cnc.events.io.UnsupportedResponseTypeReceivedEvent) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) LastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.LastHttpContent) HttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent)

Example 5 with Response

use of com.couchbase.client.core.msg.Response in project couchbase-jvm-clients by couchbase.

the class PooledService method connectReservedEndpoint.

/**
 * Connect the reserved endpoint and dispatch the request into it if possible.
 * <p>
 * Note that there are two synchronized sections in this method, because the subscription callback works on
 * a different thread.
 *
 * @param request the request that needs to bee dispatched.
 */
private synchronized <R extends Request<? extends Response>> void connectReservedEndpoint(final R request) {
    if (!disconnected.get()) {
        Endpoint endpoint = createEndpoint();
        endpointStates.register(endpoint, endpoint);
        endpoint.states().skipUntil(s -> s == EndpointState.CONNECTING).filter(s -> s == EndpointState.CONNECTED || s == EndpointState.DISCONNECTED).takeUntil(s -> s == EndpointState.CONNECTED || s == EndpointState.DISCONNECTED).publishOn(context().environment().scheduler()).subscribe(s -> {
            synchronized (PooledService.this) {
                reservedEndpoints.remove(endpoint);
                if (disconnected.get()) {
                    endpoint.disconnect();
                    endpointStates.deregister(endpoint);
                    RetryOrchestrator.maybeRetry(serviceContext, request, RetryReason.ENDPOINT_NOT_AVAILABLE);
                } else {
                    endpoints.add(endpoint);
                    if (s == EndpointState.CONNECTED) {
                        endpoint.send(request);
                    } else if (s == EndpointState.DISCONNECTED) {
                        RetryOrchestrator.maybeRetry(serviceContext, request, RetryReason.ENDPOINT_NOT_AVAILABLE);
                    }
                }
            }
        });
        endpoint.connect();
        reservedEndpoints.add(endpoint);
    }
}
Also used : RetryOrchestrator(com.couchbase.client.core.retry.RetryOrchestrator) EndpointState(com.couchbase.client.core.endpoint.EndpointState) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Endpoint(com.couchbase.client.core.endpoint.Endpoint) Request(com.couchbase.client.core.msg.Request) CompositeStateful(com.couchbase.client.core.util.CompositeStateful) HashMap(java.util.HashMap) ServiceStateChangedEvent(com.couchbase.client.core.cnc.events.service.ServiceStateChangedEvent) RetryReason(com.couchbase.client.core.retry.RetryReason) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) ServiceDisconnectInitiatedEvent(com.couchbase.client.core.cnc.events.service.ServiceDisconnectInitiatedEvent) Duration(java.time.Duration) Map(java.util.Map) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) EndpointDiagnostics(com.couchbase.client.core.diagnostics.EndpointDiagnostics) ServiceConnectInitiatedEvent(com.couchbase.client.core.cnc.events.service.ServiceConnectInitiatedEvent) Collections(java.util.Collections) Response(com.couchbase.client.core.msg.Response) IdleEndpointRemovedEvent(com.couchbase.client.core.cnc.events.service.IdleEndpointRemovedEvent) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Endpoint(com.couchbase.client.core.endpoint.Endpoint)

Aggregations

Response (com.couchbase.client.core.msg.Response)12 ChannelClosedProactivelyEvent (com.couchbase.client.core.cnc.events.io.ChannelClosedProactivelyEvent)4 InvalidRequestDetectedEvent (com.couchbase.client.core.cnc.events.io.InvalidRequestDetectedEvent)4 Request (com.couchbase.client.core.msg.Request)4 KeyValueRequest (com.couchbase.client.core.msg.kv.KeyValueRequest)4 RequestSpan (com.couchbase.client.core.cnc.RequestSpan)3 RequestTracer (com.couchbase.client.core.cnc.RequestTracer)3 UnsupportedResponseTypeReceivedEvent (com.couchbase.client.core.cnc.events.io.UnsupportedResponseTypeReceivedEvent)3 BaseEndpoint (com.couchbase.client.core.endpoint.BaseEndpoint)3 ResponseStatus (com.couchbase.client.core.msg.ResponseStatus)3 RetryReason (com.couchbase.client.core.retry.RetryReason)3 ServiceType (com.couchbase.client.core.service.ServiceType)3 Optional (java.util.Optional)3 KeyValueErrorMapCodeHandledEvent (com.couchbase.client.core.cnc.events.io.KeyValueErrorMapCodeHandledEvent)2 UnknownResponseStatusReceivedEvent (com.couchbase.client.core.cnc.events.io.UnknownResponseStatusReceivedEvent)2 ConfigurationProvider (com.couchbase.client.core.config.ConfigurationProvider)2 MemcachedBucketConfig (com.couchbase.client.core.config.MemcachedBucketConfig)2 FullHttpRequest (com.couchbase.client.core.deps.io.netty.handler.codec.http.FullHttpRequest)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