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