use of com.nike.fastbreak.CircuitBreaker in project riposte by Nike-Inc.
the class AsyncCompletionHandlerWithTracingAndMdcSupportTest method constructor_sets_values_with_subspan_when_subtracing_is_on.
@DataProvider(value = { "NULL", "EMPTY", "HAS_EXISTING_SPAN" }, splitBy = "\\|")
@Test
public void constructor_sets_values_with_subspan_when_subtracing_is_on(ExistingSpanStackState existingSpanStackState) {
// given
CompletableFuture cfResponse = mock(CompletableFuture.class);
AsyncResponseHandler responseHandlerFunc = mock(AsyncResponseHandler.class);
String method = UUID.randomUUID().toString();
String url = UUID.randomUUID().toString();
Optional<CircuitBreaker<Response>> circuitBreaker = Optional.of(mock(CircuitBreaker.class));
Span initialSpan = null;
switch(existingSpanStackState) {
case NULL:
case //intentional fall-through
EMPTY:
resetTracingAndMdc();
break;
case HAS_EXISTING_SPAN:
initialSpan = Tracer.getInstance().startRequestWithRootSpan("overallReqSpan");
break;
default:
throw new IllegalArgumentException("Unhandled state: " + existingSpanStackState.name());
}
Deque<Span> spanStack = (existingSpanStackState == EMPTY) ? new LinkedList<>() : Tracer.getInstance().getCurrentSpanStackCopy();
Map<String, String> mdcInfo = (existingSpanStackState == EMPTY) ? new HashMap<>() : MDC.getCopyOfContextMap();
resetTracingAndMdc();
Deque<Span> spanStackBeforeCall = Tracer.getInstance().getCurrentSpanStackCopy();
Map<String, String> mdcInfoBeforeCall = MDC.getCopyOfContextMap();
// when
AsyncCompletionHandlerWithTracingAndMdcSupport instance = new AsyncCompletionHandlerWithTracingAndMdcSupport(cfResponse, responseHandlerFunc, true, method, url, circuitBreaker, spanStack, mdcInfo);
// then
assertThat(instance.completableFutureResponse).isSameAs(cfResponse);
assertThat(instance.responseHandlerFunction).isSameAs(responseHandlerFunc);
assertThat(instance.performSubSpanAroundDownstreamCalls).isEqualTo(true);
assertThat(instance.circuitBreakerManualTask).isSameAs(circuitBreaker);
int initialSpanStackSize = (spanStack == null) ? 0 : spanStack.size();
assertThat(instance.distributedTraceStackToUse).hasSize(initialSpanStackSize + 1);
Span subspan = (Span) instance.distributedTraceStackToUse.peek();
assertThat(instance.mdcContextToUse.get(Tracer.TRACE_ID_MDC_KEY)).isEqualTo(subspan.getTraceId());
if (existingSpanStackState == ExistingSpanStackState.NULL || existingSpanStackState == EMPTY) {
assertThat(instance.distributedTraceStackToUse).hasSize(1);
} else {
assertThat(instance.distributedTraceStackToUse.peekLast()).isEqualTo(initialSpan);
assertThat(subspan).isNotEqualTo(initialSpan);
assertThat(subspan.getTraceId()).isEqualTo(initialSpan.getTraceId());
assertThat(subspan.getParentSpanId()).isEqualTo(initialSpan.getSpanId());
assertThat(subspan.getSpanName()).isEqualTo(instance.getSubspanSpanName(method, url));
}
assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isEqualTo(spanStackBeforeCall);
assertThat(MDC.getCopyOfContextMap()).isEqualTo(mdcInfoBeforeCall);
}
use of com.nike.fastbreak.CircuitBreaker in project riposte by Nike-Inc.
the class AsyncHttpClientHelper method executeAsyncHttpRequest.
/**
* Executes the given request asynchronously, handling the response with the given responseHandlerFunction, and
* returns a {@link CompletableFuture} that represents the result of executing the
* responseHandlerFunction on the downstream response. Any error anywhere along the way will cause the returned
* future to be completed with {@link CompletableFuture#completeExceptionally(Throwable)}.
* <p/>
* <b>Distributed Tracing and MDC for the downstream call:</b> The given {@code distributedTraceStackForCall} and
* {@code mdcContextForCall} arguments are used to setup distributed trace and MDC info for the downstream call so
* that the callback will be performed with that data attached to whatever thread the callback is done on.
*/
public <O> CompletableFuture<O> executeAsyncHttpRequest(RequestBuilderWrapper requestBuilderWrapper, AsyncResponseHandler<O> responseHandlerFunction, Deque<Span> distributedTraceStackForCall, Map<String, String> mdcContextForCall) {
CompletableFuture<O> completableFutureResponse = new CompletableFuture<>();
try {
Optional<ManualModeTask<Response>> circuitBreakerManualTask = getCircuitBreaker(requestBuilderWrapper).map(CircuitBreaker::newManualModeTask);
// If we have a circuit breaker, give it a chance to throw an exception if the circuit is open/tripped
circuitBreakerManualTask.ifPresent(ManualModeTask::throwExceptionIfCircuitBreakerIsOpen);
// Setup the async completion handler for the call.
AsyncCompletionHandlerWithTracingAndMdcSupport<O> asyncCompletionHandler = new AsyncCompletionHandlerWithTracingAndMdcSupport<>(completableFutureResponse, responseHandlerFunction, performSubSpanAroundDownstreamCalls, requestBuilderWrapper.httpMethod, requestBuilderWrapper.url, circuitBreakerManualTask, distributedTraceStackForCall, mdcContextForCall);
// Add distributed trace headers to the downstream call if we have a span.
Span spanForCall = asyncCompletionHandler.getSpanForCall();
if (spanForCall != null) {
requestBuilderWrapper.requestBuilder.setHeader(TraceHeaders.TRACE_SAMPLED, String.valueOf(spanForCall.isSampleable()));
requestBuilderWrapper.requestBuilder.setHeader(TraceHeaders.TRACE_ID, spanForCall.getTraceId());
requestBuilderWrapper.requestBuilder.setHeader(TraceHeaders.SPAN_ID, spanForCall.getSpanId());
requestBuilderWrapper.requestBuilder.setHeader(TraceHeaders.PARENT_SPAN_ID, spanForCall.getParentSpanId());
requestBuilderWrapper.requestBuilder.setHeader(TraceHeaders.SPAN_NAME, spanForCall.getSpanName());
}
// Execute the downstream call. The completableFutureResponse will be completed or completed exceptionally
// depending on the result of the call.
requestBuilderWrapper.requestBuilder.execute(asyncCompletionHandler);
} catch (Throwable t) {
// normal when the circuit breaker associated with this request has been tripped.
if (!(t instanceof CircuitBreakerOpenException)) {
logger.error("An error occurred while trying to set up an async HTTP call for method {} and URL {}. " + "The CompletableFuture will be instantly failed with this error", requestBuilderWrapper.httpMethod, requestBuilderWrapper.url, t);
}
completableFutureResponse.completeExceptionally(t);
}
return completableFutureResponse;
}
use of com.nike.fastbreak.CircuitBreaker in project riposte by Nike-Inc.
the class ProxyRouterEndpointExecutionHandler method getCircuitBreaker.
protected Optional<CircuitBreaker<HttpResponse>> getCircuitBreaker(DownstreamRequestFirstChunkInfo downstreamReqFirstChunkInfo, ChannelHandlerContext ctx) {
if (downstreamReqFirstChunkInfo == null || downstreamReqFirstChunkInfo.disableCircuitBreaker)
return Optional.empty();
// custom one is not specified.
if (downstreamReqFirstChunkInfo.customCircuitBreaker.isPresent())
return downstreamReqFirstChunkInfo.customCircuitBreaker;
// No custom circuit breaker. Use the default for the given request's host.
EventLoop nettyEventLoop = ctx.channel().eventLoop();
CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(downstreamReqFirstChunkInfo.host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop));
return Optional.of(new CircuitBreakerDelegate<>(defaultStatusCodeCircuitBreaker, httpResponse -> (httpResponse == null ? null : httpResponse.getStatus().code())));
}
Aggregations