|
| 1 | +package io.ksilisk.telegrambot.core.executor.retry; |
| 2 | + |
| 3 | +import com.pengrad.telegrambot.request.BaseRequest; |
| 4 | +import com.pengrad.telegrambot.response.BaseResponse; |
| 5 | +import io.ksilisk.telegrambot.core.exception.request.TelegramRequestException; |
| 6 | +import io.ksilisk.telegrambot.core.executor.TelegramBotExecutor; |
| 7 | +import io.ksilisk.telegrambot.core.executor.retry.impl.CompositeRetryRule; |
| 8 | + |
| 9 | +import java.time.Duration; |
| 10 | + |
| 11 | +/** |
| 12 | + * {@link TelegramBotExecutor} decorator that retries failed Telegram Bot API |
| 13 | + * requests according to the configured {@link RetryRule} and |
| 14 | + * {@link RetryDelayStrategy}. |
| 15 | + * |
| 16 | + * <p>This executor delegates request execution to another |
| 17 | + * {@link TelegramBotExecutor}. When execution fails, it evaluates the retry |
| 18 | + * rule and, if retry is allowed, waits for the configured delay before |
| 19 | + * performing the next attempt. |
| 20 | + * |
| 21 | + * <p>This decorator does not define retry policy by itself. Retry decisions |
| 22 | + * are fully delegated to the provided {@link RetryRule} implementation. |
| 23 | + */ |
| 24 | +public class RetryingTelegramBotExecutor implements TelegramBotExecutor { |
| 25 | + private final TelegramBotExecutor delegate; |
| 26 | + private final CompositeRetryRule retryRule; |
| 27 | + private final RetryDelayStrategy retryDelayStrategy; |
| 28 | + |
| 29 | + public RetryingTelegramBotExecutor(TelegramBotExecutor delegate, |
| 30 | + CompositeRetryRule retryRule, |
| 31 | + RetryDelayStrategy retryDelayStrategy) { |
| 32 | + this.delegate = delegate; |
| 33 | + this.retryRule = retryRule; |
| 34 | + this.retryDelayStrategy = retryDelayStrategy; |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) |
| 39 | + throws TelegramRequestException { |
| 40 | + int attempt = 1; |
| 41 | + |
| 42 | + while (true) { |
| 43 | + try { |
| 44 | + return delegate.execute(request); |
| 45 | + } catch (Exception ex) { |
| 46 | + if (!retryRule.shouldRetry(request, ex, attempt)) { |
| 47 | + throw ex; |
| 48 | + } |
| 49 | + |
| 50 | + Duration delay = retryDelayStrategy.nextDelay(request, ex, attempt); |
| 51 | + sleep(delay); |
| 52 | + attempt++; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private void sleep(Duration delay) { |
| 58 | + try { |
| 59 | + Thread.sleep(delay.toMillis()); |
| 60 | + } catch (InterruptedException ex) { |
| 61 | + Thread.currentThread().interrupt(); |
| 62 | + throw new IllegalStateException("Retry sleep was interrupted", ex); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments