| """Retry helpers for transient API/network failures.""" |
|
|
| from __future__ import annotations |
|
|
| import random |
| import time |
| from typing import Callable, Optional, TypeVar |
|
|
|
|
| T = TypeVar("T") |
|
|
|
|
| _TRANSIENT_NAME_HINTS = { |
| "timeout", |
| "timedout", |
| "ratelimit", |
| "apiconnection", |
| "serviceunavailable", |
| "internalserver", |
| "connectionerror", |
| } |
|
|
| _TRANSIENT_MSG_HINTS = ( |
| "timeout", |
| "timed out", |
| "rate limit", |
| "too many requests", |
| "temporarily unavailable", |
| "service unavailable", |
| "bad gateway", |
| "gateway timeout", |
| "connection reset", |
| "remote disconnected", |
| "try again", |
| "overloaded", |
| ) |
|
|
|
|
| def is_transient_api_error(exc: Exception) -> bool: |
| name = exc.__class__.__name__.lower() |
| msg = str(exc or "").lower() |
| status_code = getattr(exc, "status_code", None) |
| if isinstance(status_code, int) and (status_code == 408 or status_code == 409 or status_code == 429 or 500 <= status_code <= 599): |
| return True |
| if any(h in name for h in _TRANSIENT_NAME_HINTS): |
| return True |
| if any(h in msg for h in _TRANSIENT_MSG_HINTS): |
| return True |
| return False |
|
|
|
|
| def retry_call( |
| fn: Callable[[], T], |
| *, |
| max_attempts: int = 5, |
| base_delay_sec: float = 1.0, |
| max_delay_sec: float = 20.0, |
| jitter_sec: float = 0.25, |
| on_retry: Optional[Callable[[int, Exception, float], None]] = None, |
| retry_predicate: Optional[Callable[[Exception], bool]] = None, |
| ) -> T: |
| attempts = max(1, int(max_attempts)) |
| base = max(0.0, float(base_delay_sec)) |
| cap = max(base, float(max_delay_sec)) |
| jitter = max(0.0, float(jitter_sec)) |
|
|
| should_retry = retry_predicate or is_transient_api_error |
| attempt = 1 |
| while True: |
| try: |
| return fn() |
| except Exception as e: |
| if attempt >= attempts or not should_retry(e): |
| raise |
| backoff = min(cap, base * (2 ** (attempt - 1))) |
| delay = backoff + random.uniform(0.0, jitter) |
| if on_retry is not None: |
| on_retry(attempt, e, delay) |
| time.sleep(delay) |
| attempt += 1 |
|
|