| 1 | import asyncio |
| 2 | from typing import Callable, TypeVar |
| 3 | |
| 4 | from utils.logger import setup_logger |
| 5 | |
| 6 | logger = setup_logger("RetryHandler") |
| 7 | |
| 8 | T = TypeVar("T") |
| 9 | |
| 10 | |
| 11 | class RetryHandler: |
| 12 | def __init__(self, max_retries: int = 3): |
| 13 | # max_retries = number of retries AFTER the initial attempt; |
| 14 | # total attempts = max_retries + 1. |
| 15 | self.max_retries = max_retries |
| 16 | self.retry_delays = [1, 2, 5] |
| 17 | |
| 18 | async def execute_with_retry(self, func: Callable[..., T], *args, **kwargs) -> T: |
| 19 | last_error = None |
| 20 | total_attempts = self.max_retries + 1 |
| 21 | |
| 22 | for attempt in range(total_attempts): |
| 23 | try: |
| 24 | return await func(*args, **kwargs) |
| 25 | except Exception as e: |
| 26 | last_error = e |
| 27 | if attempt < self.max_retries: |
| 28 | delay = self.retry_delays[min(attempt, len(self.retry_delays) - 1)] |
| 29 | logger.warning( |
| 30 | "Attempt %d failed: %s, retrying in %ds...", attempt + 1, e, delay |
| 31 | ) |
| 32 | await asyncio.sleep(delay) |
| 33 | |
| 34 | logger.error("All %d attempts failed: %s", total_attempts, last_error) |
| 35 | raise last_error |
| 36 |