Spaces:
Sleeping
Sleeping
Download src/utils/retry_handler.py from yashpixl09/IP-Safe: direct link, hf CLI and curl.
- Browser
- Download file 2.4 kB
-
https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/utils/retry_handler.py
- Command line
-
hf download hf://spaces/yashpixl09/IP-Safe/src/utils/retry_handler.py
-
curl -L -o retry_handler.py https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/utils/retry_handler.py
2.4 kB
| """Retry logic with exponential backoff for API calls.""" | |
| from tenacity import ( | |
| retry, | |
| stop_after_attempt, | |
| wait_exponential, | |
| retry_if_exception_type, | |
| RetryError, | |
| ) | |
| from loguru import logger | |
| import asyncio | |
| # Define retryable exceptions (will be imported from provider modules) | |
| RETRYABLE_EXCEPTIONS = ( | |
| ConnectionError, | |
| TimeoutError, | |
| asyncio.TimeoutError, | |
| ) | |
| def create_retry_decorator( | |
| max_attempts: int = 3, min_wait: int = 2, max_wait: int = 10 | |
| ): | |
| """ | |
| Create a retry decorator with exponential backoff. | |
| Args: | |
| max_attempts: Maximum number of retry attempts | |
| min_wait: Minimum wait time in seconds | |
| max_wait: Maximum wait time in seconds | |
| Returns: | |
| Tenacity retry decorator | |
| """ | |
| return retry( | |
| stop=stop_after_attempt(max_attempts), | |
| wait=wait_exponential(multiplier=1, min=min_wait, max=max_wait), | |
| retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS), | |
| before_sleep=lambda retry_state: logger.warning( | |
| f"Retry attempt {retry_state.attempt_number}/{max_attempts} " | |
| f"after error: {retry_state.outcome.exception()}" | |
| ), | |
| ) | |
| async def call_with_retry(func, *args, max_attempts: int = 3, **kwargs): | |
| """ | |
| Call an async function with retry logic. | |
| Args: | |
| func: Async function to call | |
| *args: Positional arguments for func | |
| max_attempts: Maximum retry attempts | |
| **kwargs: Keyword arguments for func | |
| Returns: | |
| Result from func | |
| Raises: | |
| Exception: If all retry attempts fail | |
| """ | |
| decorator = create_retry_decorator(max_attempts=max_attempts) | |
| wrapped_func = decorator(func) | |
| try: | |
| return await wrapped_func(*args, **kwargs) | |
| except RetryError as e: | |
| logger.error(f"All retry attempts failed: {e}") | |
| raise e.last_attempt.exception() | |
| async def call_with_timeout(coro, timeout_seconds: int = 120): | |
| """ | |
| Call a coroutine with a timeout. | |
| Args: | |
| coro: Coroutine to execute | |
| timeout_seconds: Timeout in seconds | |
| Returns: | |
| Result from coroutine | |
| Raises: | |
| asyncio.TimeoutError: If operation times out | |
| """ | |
| try: | |
| return await asyncio.wait_for(coro, timeout=timeout_seconds) | |
| except asyncio.TimeoutError: | |
| logger.error(f"Operation timed out after {timeout_seconds} seconds") | |
| raise | |