use of io.github.resilience4j.bulkhead.operator.BulkheadOperator in project resilience4j by resilience4j.
the class BulkheadMethodInterceptor method invoke.
@SuppressWarnings("unchecked")
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Bulkhead annotation = invocation.getMethod().getAnnotation(Bulkhead.class);
RecoveryFunction<?> recoveryFunction = annotation.recovery().newInstance();
if (registry == null) {
registry = BulkheadRegistry.ofDefaults();
}
io.github.resilience4j.bulkhead.Bulkhead bulkhead = registry.bulkhead(annotation.name());
if (bulkhead == null) {
return invocation.proceed();
}
Class<?> returnType = invocation.getMethod().getReturnType();
if (Promise.class.isAssignableFrom(returnType)) {
Promise<?> result = (Promise<?>) invocation.proceed();
if (result != null) {
BulkheadTransformer transformer = BulkheadTransformer.of(bulkhead).recover(recoveryFunction);
result = result.transform(transformer);
}
return result;
} else if (Observable.class.isAssignableFrom(returnType)) {
Observable<?> result = (Observable<?>) invocation.proceed();
if (result != null) {
BulkheadOperator operator = BulkheadOperator.of(bulkhead);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (Flowable.class.isAssignableFrom(returnType)) {
Flowable<?> result = (Flowable<?>) invocation.proceed();
if (result != null) {
BulkheadOperator operator = BulkheadOperator.of(bulkhead);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (Single.class.isAssignableFrom(returnType)) {
Single<?> result = (Single<?>) invocation.proceed();
if (result != null) {
BulkheadOperator operator = BulkheadOperator.of(bulkhead);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (CompletionStage.class.isAssignableFrom(returnType)) {
if (bulkhead.isCallPermitted()) {
return ((CompletionStage<?>) invocation.proceed()).handle((o, throwable) -> {
bulkhead.onComplete();
if (throwable != null) {
try {
return recoveryFunction.apply(throwable);
} catch (Exception e) {
throw Exceptions.uncheck(throwable);
}
} else {
return o;
}
});
} else {
final CompletableFuture promise = new CompletableFuture<>();
Throwable t = new BulkheadFullException(String.format("Bulkhead '%s' is full", bulkhead.getName()));
try {
promise.complete(recoveryFunction.apply(t));
} catch (Throwable t2) {
promise.completeExceptionally(t2);
}
return promise;
}
}
return handleOther(invocation, bulkhead, recoveryFunction);
}
Aggregations