Search in sources :

Example 1 with ExhaustedRetryException

use of cn.taketoday.retry.ExhaustedRetryException in project today-infrastructure by TAKETODAY.

the class StatefulRetryOperationsInterceptorTests method testRetryExceptionAfterTooManyAttemptsWithNoRecovery.

@Test
public void testRetryExceptionAfterTooManyAttemptsWithNoRecovery() throws Exception {
    ((Advised) service).addAdvice(interceptor);
    interceptor.setRetryOperations(retryTemplate);
    retryTemplate.setRetryPolicy(new NeverRetryPolicy());
    try {
        service.service("foo");
        fail("Expected Exception.");
    } catch (Exception e) {
        String message = e.getMessage();
        assertTrue("Wrong message: " + message, message.startsWith("Not enough calls"));
    }
    assertEquals(1, count);
    try {
        service.service("foo");
        fail("Expected ExhaustedRetryException");
    } catch (ExhaustedRetryException e) {
        // expected
        String message = e.getMessage();
        assertTrue("Wrong message: " + message, message.startsWith("Retry exhausted"));
    }
    assertEquals(1, count);
}
Also used : ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) Advised(cn.taketoday.aop.framework.Advised) NeverRetryPolicy(cn.taketoday.retry.policy.NeverRetryPolicy) ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) Test(org.junit.jupiter.api.Test)

Example 2 with ExhaustedRetryException

use of cn.taketoday.retry.ExhaustedRetryException in project today-infrastructure by TAKETODAY.

the class RetryTemplate method doExecute.

/**
 * Execute the callback once if the policy dictates that we can, otherwise execute the
 * recovery callback.
 *
 * @param recoveryCallback the {@link RecoveryCallback}
 * @param retryCallback the {@link RetryCallback}
 * @param state the {@link RetryState}
 * @param <T> the type of the return value
 * @param <E> the exception type to throw
 * @return T the retried value
 * @throws ExhaustedRetryException if the retry has been exhausted.
 * @throws E an exception if the retry operation fails
 * @see RetryOperations#execute(RetryCallback, RecoveryCallback, RetryState)
 */
protected <T, E extends Throwable> T doExecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) throws E, ExhaustedRetryException {
    RetryPolicy retryPolicy = this.retryPolicy;
    BackOffPolicy backOffPolicy = this.backOffPolicy;
    // Allow the retry policy to initialise itself...
    RetryContext context = open(retryPolicy, state);
    if (logger.isTraceEnabled()) {
        logger.trace("RetryContext retrieved: {}", context);
    }
    // Make sure the context is available globally for clients who need
    // it...
    RetrySynchronizationManager.register(context);
    Throwable lastException = null;
    boolean exhausted = false;
    try {
        // Give clients a chance to enhance the context...
        boolean running = doOpenInterceptors(retryCallback, context);
        if (!running) {
            throw new TerminatedRetryException("Retry terminated abnormally by interceptor before first attempt");
        }
        // Get or Start the backoff context...
        BackOffContext backOffContext = null;
        Object resource = context.getAttribute("backOffContext");
        if (resource instanceof BackOffContext) {
            backOffContext = (BackOffContext) resource;
        }
        if (backOffContext == null) {
            backOffContext = backOffPolicy.start(context);
            if (backOffContext != null) {
                context.setAttribute("backOffContext", backOffContext);
            }
        }
        /*
       * We allow the whole loop to be skipped if the policy or context already
       * forbid the first try. This is used in the case of external retry to allow a
       * recovery in handleRetryExhausted without the callback processing (which
       * would throw an exception).
       */
        while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Retry: count={}", context.getRetryCount());
                }
                // Reset the last exception, so if we are successful
                // the close interceptors will not think we failed...
                lastException = null;
                return retryCallback.doWithRetry(context);
            } catch (Throwable e) {
                lastException = e;
                try {
                    registerThrowable(retryPolicy, state, context, e);
                } catch (Exception ex) {
                    throw new TerminatedRetryException("Could not register throwable", ex);
                } finally {
                    doOnErrorInterceptors(retryCallback, context, e);
                }
                if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
                    try {
                        backOffPolicy.backOff(backOffContext);
                    } catch (BackOffInterruptedException ex) {
                        lastException = e;
                        // back off was prevented by another thread - fail the retry
                        if (logger.isDebugEnabled()) {
                            logger.debug("Abort retry because interrupted: count={}", context.getRetryCount());
                        }
                        throw ex;
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Checking for rethrow: count={}", context.getRetryCount());
                }
                if (shouldRethrow(retryPolicy, context, state)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rethrow in retry for policy: count={}", context.getRetryCount());
                    }
                    throw RetryTemplate.<E>wrapIfNecessary(e);
                }
            }
            /*
         * A stateful attempt that can retry may rethrow the exception before now,
         * but if we get this far in a stateful retry there's a reason for it,
         * like a circuit breaker or a rollback classifier.
         */
            if (state != null && context.hasAttribute(GLOBAL_STATE)) {
                break;
            }
        }
        if (state == null && logger.isDebugEnabled()) {
            logger.debug("Retry failed last attempt: count={}", context.getRetryCount());
        }
        exhausted = true;
        return handleRetryExhausted(recoveryCallback, context, state);
    } catch (Throwable e) {
        throw RetryTemplate.<E>wrapIfNecessary(e);
    } finally {
        close(retryPolicy, context, state, lastException == null || exhausted);
        doCloseInterceptors(retryCallback, context, lastException);
        RetrySynchronizationManager.clear();
    }
}
Also used : BackOffPolicy(cn.taketoday.retry.backoff.BackOffPolicy) NoBackOffPolicy(cn.taketoday.retry.backoff.NoBackOffPolicy) BackOffContext(cn.taketoday.retry.backoff.BackOffContext) RetryContext(cn.taketoday.retry.RetryContext) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryPolicy(cn.taketoday.retry.RetryPolicy) SimpleRetryPolicy(cn.taketoday.retry.policy.SimpleRetryPolicy) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException) ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryException(cn.taketoday.retry.RetryException) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException)

Example 3 with ExhaustedRetryException

use of cn.taketoday.retry.ExhaustedRetryException in project today-framework by TAKETODAY.

the class RetryTemplate method doExecute.

/**
 * Execute the callback once if the policy dictates that we can, otherwise execute the
 * recovery callback.
 *
 * @param recoveryCallback the {@link RecoveryCallback}
 * @param retryCallback the {@link RetryCallback}
 * @param state the {@link RetryState}
 * @param <T> the type of the return value
 * @param <E> the exception type to throw
 * @return T the retried value
 * @throws ExhaustedRetryException if the retry has been exhausted.
 * @throws E an exception if the retry operation fails
 * @see RetryOperations#execute(RetryCallback, RecoveryCallback, RetryState)
 */
protected <T, E extends Throwable> T doExecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) throws E, ExhaustedRetryException {
    RetryPolicy retryPolicy = this.retryPolicy;
    BackOffPolicy backOffPolicy = this.backOffPolicy;
    // Allow the retry policy to initialise itself...
    RetryContext context = open(retryPolicy, state);
    if (logger.isTraceEnabled()) {
        logger.trace("RetryContext retrieved: {}", context);
    }
    // Make sure the context is available globally for clients who need
    // it...
    RetrySynchronizationManager.register(context);
    Throwable lastException = null;
    boolean exhausted = false;
    try {
        // Give clients a chance to enhance the context...
        boolean running = doOpenInterceptors(retryCallback, context);
        if (!running) {
            throw new TerminatedRetryException("Retry terminated abnormally by interceptor before first attempt");
        }
        // Get or Start the backoff context...
        BackOffContext backOffContext = null;
        Object resource = context.getAttribute("backOffContext");
        if (resource instanceof BackOffContext) {
            backOffContext = (BackOffContext) resource;
        }
        if (backOffContext == null) {
            backOffContext = backOffPolicy.start(context);
            if (backOffContext != null) {
                context.setAttribute("backOffContext", backOffContext);
            }
        }
        /*
       * We allow the whole loop to be skipped if the policy or context already
       * forbid the first try. This is used in the case of external retry to allow a
       * recovery in handleRetryExhausted without the callback processing (which
       * would throw an exception).
       */
        while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Retry: count={}", context.getRetryCount());
                }
                // Reset the last exception, so if we are successful
                // the close interceptors will not think we failed...
                lastException = null;
                return retryCallback.doWithRetry(context);
            } catch (Throwable e) {
                lastException = e;
                try {
                    registerThrowable(retryPolicy, state, context, e);
                } catch (Exception ex) {
                    throw new TerminatedRetryException("Could not register throwable", ex);
                } finally {
                    doOnErrorInterceptors(retryCallback, context, e);
                }
                if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
                    try {
                        backOffPolicy.backOff(backOffContext);
                    } catch (BackOffInterruptedException ex) {
                        lastException = e;
                        // back off was prevented by another thread - fail the retry
                        if (logger.isDebugEnabled()) {
                            logger.debug("Abort retry because interrupted: count={}", context.getRetryCount());
                        }
                        throw ex;
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Checking for rethrow: count={}", context.getRetryCount());
                }
                if (shouldRethrow(retryPolicy, context, state)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rethrow in retry for policy: count={}", context.getRetryCount());
                    }
                    throw RetryTemplate.<E>wrapIfNecessary(e);
                }
            }
            /*
         * A stateful attempt that can retry may rethrow the exception before now,
         * but if we get this far in a stateful retry there's a reason for it,
         * like a circuit breaker or a rollback classifier.
         */
            if (state != null && context.hasAttribute(GLOBAL_STATE)) {
                break;
            }
        }
        if (state == null && logger.isDebugEnabled()) {
            logger.debug("Retry failed last attempt: count={}", context.getRetryCount());
        }
        exhausted = true;
        return handleRetryExhausted(recoveryCallback, context, state);
    } catch (Throwable e) {
        throw RetryTemplate.<E>wrapIfNecessary(e);
    } finally {
        close(retryPolicy, context, state, lastException == null || exhausted);
        doCloseInterceptors(retryCallback, context, lastException);
        RetrySynchronizationManager.clear();
    }
}
Also used : BackOffPolicy(cn.taketoday.retry.backoff.BackOffPolicy) NoBackOffPolicy(cn.taketoday.retry.backoff.NoBackOffPolicy) BackOffContext(cn.taketoday.retry.backoff.BackOffContext) RetryContext(cn.taketoday.retry.RetryContext) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryPolicy(cn.taketoday.retry.RetryPolicy) SimpleRetryPolicy(cn.taketoday.retry.policy.SimpleRetryPolicy) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException) ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryException(cn.taketoday.retry.RetryException) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException)

Example 4 with ExhaustedRetryException

use of cn.taketoday.retry.ExhaustedRetryException in project today-framework by TAKETODAY.

the class CircuitBreakerStatisticsTests method testFailedRecoveryCountsAsAbort.

@Test
public void testFailedRecoveryCountsAsAbort() throws Throwable {
    this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy()));
    this.recovery = new RecoveryCallback<Object>() {

        @Override
        public Object recover(RetryContext context) throws Exception {
            throw new ExhaustedRetryException("Planned exhausted");
        }
    };
    try {
        this.retryTemplate.execute(this.callback, this.recovery, this.state);
        fail("Expected ExhaustedRetryException");
    } catch (ExhaustedRetryException e) {
    // Fine
    }
    MutableRetryStatistics stats = (MutableRetryStatistics) repository.findOne("test");
    assertEquals(1, stats.getStartedCount());
    assertEquals(1, stats.getAbortCount());
    assertEquals(0, stats.getRecoveryCount());
}
Also used : ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) RetryContext(cn.taketoday.retry.RetryContext) CircuitBreakerRetryPolicy(cn.taketoday.retry.policy.CircuitBreakerRetryPolicy) NeverRetryPolicy(cn.taketoday.retry.policy.NeverRetryPolicy) ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) Test(org.junit.Test)

Example 5 with ExhaustedRetryException

use of cn.taketoday.retry.ExhaustedRetryException in project today-framework by TAKETODAY.

the class StatefulRetryIntegrationTests method testExternalRetryWithFailAndNoRetry.

@Test
public void testExternalRetryWithFailAndNoRetry() throws Throwable {
    MockRetryCallback callback = new MockRetryCallback();
    RetryState retryState = new DefaultRetryState("foo");
    RetryTemplate retryTemplate = new RetryTemplate();
    MapRetryContextCache cache = new MapRetryContextCache();
    retryTemplate.setRetryContextCache(cache);
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1));
    assertFalse(cache.containsKey("foo"));
    try {
        retryTemplate.execute(callback, retryState);
        // The first failed attempt we expect to retry...
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        assertEquals(null, e.getMessage());
    }
    assertTrue(cache.containsKey("foo"));
    try {
        retryTemplate.execute(callback, retryState);
        // We don't get a second attempt...
        fail("Expected ExhaustedRetryException");
    } catch (ExhaustedRetryException e) {
        // This is now the "exhausted" message:
        assertNotNull(e.getMessage());
    }
    assertFalse(cache.containsKey("foo"));
    // Callback is called once: the recovery path should be called in
    // handleRetryExhausted (so not in this test)...
    assertEquals(1, callback.attempts);
}
Also used : ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) RetryTemplate(cn.taketoday.retry.support.RetryTemplate) DefaultRetryState(cn.taketoday.retry.support.DefaultRetryState) RetryState(cn.taketoday.retry.RetryState) DefaultRetryState(cn.taketoday.retry.support.DefaultRetryState) Test(org.junit.Test)

Aggregations

ExhaustedRetryException (cn.taketoday.retry.ExhaustedRetryException)10 RetryContext (cn.taketoday.retry.RetryContext)6 NeverRetryPolicy (cn.taketoday.retry.policy.NeverRetryPolicy)6 Test (org.junit.Test)6 RetryException (cn.taketoday.retry.RetryException)4 RetryPolicy (cn.taketoday.retry.RetryPolicy)4 RetryState (cn.taketoday.retry.RetryState)4 SimpleRetryPolicy (cn.taketoday.retry.policy.SimpleRetryPolicy)4 Advised (cn.taketoday.aop.framework.Advised)2 DataAccessException (cn.taketoday.dao.DataAccessException)2 RetryCallback (cn.taketoday.retry.RetryCallback)2 TerminatedRetryException (cn.taketoday.retry.TerminatedRetryException)2 BackOffContext (cn.taketoday.retry.backoff.BackOffContext)2 BackOffInterruptedException (cn.taketoday.retry.backoff.BackOffInterruptedException)2 BackOffPolicy (cn.taketoday.retry.backoff.BackOffPolicy)2 NoBackOffPolicy (cn.taketoday.retry.backoff.NoBackOffPolicy)2 CircuitBreakerRetryPolicy (cn.taketoday.retry.policy.CircuitBreakerRetryPolicy)2 DefaultRetryState (cn.taketoday.retry.support.DefaultRetryState)2 RetryTemplate (cn.taketoday.retry.support.RetryTemplate)2 Test (org.junit.jupiter.api.Test)2