python Copy code
import logging
import random
import time
from copy import copy
from typing import Any, Callable, Optional, Tuple, Union
import requests # Example dependency; wrapper is general-purpose
logger = logging.getLogger(__name__)
class SafeDependencyWrapper:
"""
A robust wrapper for third-party dependencies (e.g., HTTP APIs, external services).
Features:
- **Timeouts**: Automatically injects a configurable timeout into the dependency function's kwargs.
- **Retries**: Exponential backoff retries on specified exceptions.
- **Jitter**: Full jitter (random.uniform(0, current_backoff)) to prevent thundering herd.
- **Fallbacks**: Optional fallback callable invoked after retries fail; if fallback fails, original exception is raised.
Safety guarantees:
- No infinite loops (fixed max_retries).
- Logs attempts, failures, sleeps, and fallbacks (requires logging configured).
- Copies kwargs to avoid mutating caller state.
- Handles any callable dependency function that accepts `timeout` kwarg (common in HTTP libs).
- Configurable retry exceptions (defaults to common network/HTTP errors).
Usage: Wrap any function like `requests.get` or custom API callers.
"""
def __init__(
self,
func: Callable[..., Any],
timeout: float = 5.0,
max_retries: int = 3,
backoff_factor: float = 0.25, # Initial backoff (e.g., 0.25s -> 0.25, 0.5, 1.0, 2.0...)
jitter: bool = True,
retry_exceptions: Tuple[type, ...] = (
requests.exceptions.RequestException,
ConnectionError,
TimeoutError,
), # Customize as needed
fallback: Optional[Callable[..., Any]] = None,
logger: Optional[logging.Logger] = None,
):
self.func = func
self.timeout = timeout
self.max_retries = max_retries
self.backoff_factor = backoff_factor
self.jitter = jitter
self.retry_exceptions = retry_exceptions
self.fallback = fallback
self.logger = logger or logging.getLogger(__name__)
def __call__(self, *args: Any, **kwargs: Any) -> Any:
current_backoff = self.backoff_factor
last_exc: Optional[Exception] = None
for attempt in range(self.max_retries + 1):
try:
# Prepare kwargs with timeout injected (non-destructive)
func_kwargs = copy(kwargs)
func_kwargs.setdefault("timeout", self.timeout)
# Call the wrapped dependency
return self.func(*args, **func_kwargs)
except self.retry_exceptions as exc:
last_exc = exc
self.logger.warning(
f"Attempt {attempt + 1}/{self.max_retries + 1} failed for {self.func.__name__}: {exc}",
exc_info=True,
)
if attempt == self.max_retries:
break
# Exponential backoff with optional full jitter
sleep_duration = (
random.uniform(0, current_backoff)
if self.jitter
else current_backoff
)
self.logger.debug(f"Sleeping {sleep_duration:.3f}s before retry")
time.sleep(sleep_duration)
# Double backoff for next attempt
current_backoff *= 2
# All retries exhausted
self.logger.error(
f"Max retries ({self.max_retries}) exhausted for {self.func.__name__}: {last_exc}",
exc_info=True,
)
# Try fallback if provided
if self.fallback:
try:
self.logger.info(f"Invoking fallback for {self.func.__name__}")
fallback_kwargs = copy(kwargs)
fallback_kwargs.setdefault("timeout", self.timeout)
return self.fallback(*args, **fallback_kwargs)
except Exception as fb_exc:
self.logger.error(
f"Fallback failed for {self.func.__name__}: {fb_exc} (original: {last_exc})",
exc_info=True,
)
# Propagate original exception (fallback failure shouldn't mask primary issue)
raise last_exc # type: ignore[unreachable]
raise last_exc # type: ignore[unreachable]
# Example usage
def example():
import requests
# Primary dependency: External API call
def fetch_weather(city: str) -> dict:
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"
response = requests.get(url) # Will use injected timeout
response.raise_for_status()
return response.json()
# Fallback: Static/default data
def weather_fallback(city: str) -> dict:
return {"city": city, "temp": "N/A (fallback)", "condition": "unknown"}
# Wrap it safely
safe_weather = SafeDependencyWrapper(
func=fetch_weather,
timeout=10.0, # 10s timeout
max_retries=5,
backoff_factor=0.1,
jitter=True,
fallback=weather_fallback,
)
# Usage: Handles timeouts, retries, jitter, fallbacks automatically
try:
result = safe_weather("London")
print(result)
except Exception as e:
print(f"Ultimate failure: {e}")
# For session reuse (better for multiple calls):
session = requests.Session()
def fetch_with_session(city: str, **kwargs) -> dict:
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"
kwargs.setdefault('timeout', 10) # Redundant but safe
resp = session.get(url, **kwargs)
resp.raise_for_status()
return resp.json()
safe_session_weather = SafeDependencyWrapper(func=fetch_with_session, max_retries=3)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
example()
This wrapper prevents third-party flakes from cascading—deploy confidently! If you need async, TypeScript, or extras (e.g., rate limiting), let me know.