use of io.github.resilience4j.ratelimiter.operator.RateLimiterOperator in project resilience4j by resilience4j.
the class RateLimiterMethodInterceptor method invoke.
@SuppressWarnings("unchecked")
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
RateLimiter annotation = invocation.getMethod().getAnnotation(RateLimiter.class);
RecoveryFunction<?> recoveryFunction = annotation.recovery().newInstance();
if (registry == null) {
registry = RateLimiterRegistry.ofDefaults();
}
io.github.resilience4j.ratelimiter.RateLimiter rateLimiter = registry.rateLimiter(annotation.name());
if (rateLimiter == null) {
return invocation.proceed();
}
Class<?> returnType = invocation.getMethod().getReturnType();
if (Promise.class.isAssignableFrom(returnType)) {
Promise<?> result = (Promise<?>) proceed(invocation, rateLimiter, recoveryFunction);
if (result != null) {
RateLimiterTransformer transformer = RateLimiterTransformer.of(rateLimiter).recover(recoveryFunction);
result = result.transform(transformer);
}
return result;
} else if (Observable.class.isAssignableFrom(returnType)) {
Observable<?> result = (Observable<?>) proceed(invocation, rateLimiter, recoveryFunction);
if (result != null) {
RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (Flowable.class.isAssignableFrom(returnType)) {
Flowable<?> result = (Flowable<?>) proceed(invocation, rateLimiter, recoveryFunction);
if (result != null) {
RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (Single.class.isAssignableFrom(returnType)) {
Single<?> result = (Single<?>) proceed(invocation, rateLimiter, recoveryFunction);
if (result != null) {
RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
}
return result;
} else if (CompletionStage.class.isAssignableFrom(returnType)) {
RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
Duration timeoutDuration = rateLimiterConfig.getTimeoutDuration();
if (rateLimiter.getPermission(timeoutDuration)) {
return proceed(invocation, rateLimiter, recoveryFunction);
} else {
final CompletableFuture promise = new CompletableFuture<>();
Throwable t = new RequestNotPermitted("Request not permitted for limiter: " + rateLimiter.getName());
try {
promise.complete(recoveryFunction.apply(t));
} catch (Throwable t2) {
promise.completeExceptionally(t2);
}
return promise;
}
}
return handleProceedWithException(invocation, rateLimiter, recoveryFunction);
}
Aggregations