Please wait. This can take some minutes ...
                    
                 
             
         
        
            
                
                    
                    
                        Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. 
                        
                        Project price only 1 $ 
                        
                            You can buy this project and download/modify it how often you want.
                        
                        
                        
                     
                 
             
         
             
    
    
    io.micronaut.retry.intercept.RecoveryInterceptor Maven / Gradle / Ivy 
    
/*
 * Copyright 2017-2020 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.retry.intercept;
import io.micronaut.aop.InterceptPhase;
import io.micronaut.aop.InterceptedMethod;
import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import io.micronaut.context.BeanContext;
import io.micronaut.inject.BeanDefinition;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.inject.MethodExecutionHandle;
import io.micronaut.inject.qualifiers.Qualifiers;
import io.micronaut.retry.annotation.Fallback;
import io.micronaut.retry.annotation.Recoverable;
import io.micronaut.retry.exception.FallbackException;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/**
 * A {@link MethodInterceptor} that will attempt to execute a {@link Fallback}
 * when the target method is in an error state.
 *
 * @author graemerocher
 * @since 1.0
 */
@Singleton
public class RecoveryInterceptor implements MethodInterceptor {
    /**
     * Positioned before the {@link io.micronaut.retry.annotation.Retryable} interceptor.
     */
    public static final int POSITION = InterceptPhase.RETRY.getPosition() - 10;
    private static final Logger LOG = LoggerFactory.getLogger(RecoveryInterceptor.class);
    private static final String FALLBACK_NOT_FOUND = "FALLBACK_NOT_FOUND";
    private final BeanContext beanContext;
    /**
     * @param beanContext The bean context to allow for DI of class annotated with {@link jakarta.inject.Inject}.
     */
    public RecoveryInterceptor(BeanContext beanContext) {
        this.beanContext = beanContext;
    }
    @Override
    public int getOrder() {
        return POSITION;
    }
    @Override
    public Object intercept(MethodInvocationContext context) {
        if (context.getAttribute(FALLBACK_NOT_FOUND, Boolean.class).orElse(Boolean.FALSE)) {
            return context.proceed();
        }
        InterceptedMethod interceptedMethod = InterceptedMethod.of(context, beanContext.getConversionService());
        try {
            switch (interceptedMethod.resultType()) {
                case PUBLISHER -> {
                    return interceptedMethod.handleResult(
                        fallbackForReactiveType(context, interceptedMethod.interceptResultAsPublisher())
                    );
                }
                case COMPLETION_STAGE -> {
                    if (context.isSuspend()) {
                        return interceptedMethod.handleResult(
                            fallbackForSuspend(context, interceptedMethod.interceptResultAsCompletionStage())
                        );
                    } else {
                        return interceptedMethod.handleResult(
                            fallbackForFuture(context, interceptedMethod.interceptResultAsCompletionStage())
                        );
                    }
                }
                case SYNCHRONOUS -> {
                    try {
                        return context.proceed();
                    } catch (RuntimeException e) {
                        return resolveFallback(context, e);
                    }
                }
                default -> {
                    return interceptedMethod.unsupported();
                }
            }
        } catch (Exception e) {
            return interceptedMethod.handleException(e);
        }
    }
    @SuppressWarnings("unchecked")
    private Publisher> fallbackForReactiveType(MethodInvocationContext context, Publisher> publisher) {
        return Flux.from(publisher).onErrorResume(throwable -> {
            Optional extends MethodExecutionHandle, Object>> fallbackMethod = findFallbackMethod(context);
            if (fallbackMethod.isPresent()) {
                MethodExecutionHandle, Object> fallbackHandle = fallbackMethod.get();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass(), fallbackHandle);
                }
                Object fallbackResult;
                try {
                    fallbackResult = fallbackHandle.invoke(context.getParameterValues());
                } catch (Exception e) {
                    return Flux.error(throwable);
                }
                if (fallbackResult == null) {
                    return Flux.error(new FallbackException("Fallback handler [" + fallbackHandle + "] returned null value"));
                } else {
                    return beanContext.getConversionService().convert(fallbackResult, Publisher.class)
                        .orElseThrow(() -> new FallbackException("Unsupported Reactive type: " + fallbackResult));
                }
            }
            return Flux.error(throwable);
        });
    }
    /**
     * Finds a fallback method for the given context.
     *
     * @param context The context
     * @return The fallback method if it is present
     */
    public Optional extends MethodExecutionHandle, Object>> findFallbackMethod(MethodInvocationContext context) {
        Class> declaringType = context.classValue(Recoverable.class, "api").orElseGet(context::getDeclaringType);
        BeanDefinition> beanDefinition = beanContext.findBeanDefinition(declaringType, Qualifiers.byStereotype(Fallback.class)).orElse(null);
        if (beanDefinition != null) {
            ExecutableMethod, Object> fallBackMethod =
                beanDefinition.findMethod(context.getMethodName(), context.getArgumentTypes()).orElse(null);
            if (fallBackMethod != null) {
                MethodExecutionHandle, Object> executionHandle = beanContext.createExecutionHandle(beanDefinition, (ExecutableMethod) fallBackMethod);
                return Optional.of(executionHandle);
            }
        }
        context.setAttribute(FALLBACK_NOT_FOUND, Boolean.TRUE);
        return Optional.empty();
    }
    @SuppressWarnings("unchecked")
    private CompletionStage> fallbackForFuture(MethodInvocationContext context, CompletionStage> result) {
        CompletableFuture newFuture = new CompletableFuture<>();
        result.whenComplete((o, throwable) -> {
            if (throwable == null) {
                newFuture.complete(o);
            } else {
                Optional extends MethodExecutionHandle, Object>> fallbackMethod = findFallbackMethod(context);
                if (fallbackMethod.isPresent()) {
                    MethodExecutionHandle, Object> fallbackHandle = fallbackMethod.get();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass(), fallbackHandle);
                    }
                    try {
                        CompletableFuture resultingFuture = (CompletableFuture) fallbackHandle.invoke(context.getParameterValues());
                        if (resultingFuture == null) {
                            newFuture.completeExceptionally(new FallbackException("Fallback handler [" + fallbackHandle + "] returned null value"));
                        } else {
                            resultingFuture.whenComplete((o1, throwable1) -> {
                                if (throwable1 == null) {
                                    newFuture.complete(o1);
                                } else {
                                    newFuture.completeExceptionally(throwable1);
                                }
                            });
                        }
                    } catch (Exception e) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error invoking Fallback [{}]: {}", fallbackHandle, e.getMessage(), e);
                        }
                        newFuture.completeExceptionally(throwable);
                    }
                } else {
                    newFuture.completeExceptionally(throwable);
                }
            }
        });
        return newFuture;
    }
    private CompletionStage> fallbackForSuspend(MethodInvocationContext context, CompletionStage> result) {
        CompletableFuture newFuture = new CompletableFuture<>();
        result.whenComplete((o, throwable) -> {
            if (throwable == null) {
                newFuture.complete(o);
            } else {
                Optional extends MethodExecutionHandle, Object>> fallbackMethod = findFallbackMethod(context);
                if (fallbackMethod.isPresent()) {
                    MethodExecutionHandle, Object> fallbackHandle = fallbackMethod.get();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass(), fallbackHandle);
                    }
                    try {
                        newFuture.complete(fallbackHandle.invoke(context.getParameterValues()));
                    } catch (Throwable t) {
                        newFuture.completeExceptionally(t);
                    }
                } else {
                    newFuture.completeExceptionally(throwable);
                }
            }
        });
        return newFuture;
    }
    /**
     * Resolves a fallback for the given execution context and exception.
     *
     * @param context The context
     * @param exception The exception
     * @return Returns the fallback value or throws the original exception
     */
    protected Object resolveFallback(MethodInvocationContext context, RuntimeException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Type [{}] executed with error: {}", context.getTarget().getClass().getName(), exception.getMessage(), exception);
        }
        Optional extends MethodExecutionHandle, Object>> fallback = findFallbackMethod(context);
        if (fallback.isPresent()) {
            MethodExecutionHandle, Object> fallbackMethod = fallback.get();
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass().getName(), fallbackMethod);
                }
                return fallbackMethod.invoke(context.getParameterValues());
            } catch (Exception e) {
                throw new FallbackException("Error invoking fallback for type [" + context.getTarget().getClass().getName() + "]: " + e.getMessage(), e);
            }
        } else {
            throw exception;
        }
    }
}