# api_client.py import asyncio import logging from contextlib import asynccontextmanager from typing import Any, Optional from urllib.parse import urlparse import aiohttp from aiohttp import ClientError, ClientResponseError from aiolimiter import AsyncLimiter logger = logging.getLogger(__name__) class APIClientError(Exception): """Base exception for API client errors.""" class MaxRetriesExceededError(APIClientError): """Raised when max retries are exceeded.""" class APIClient: """ Async HTTP client with retry, rate limiting, and logging. Features: - Reusable TCP connections via persistent session - Token bucket rate limiting (aiolimiter) - Exponential backoff with full jitter - Retry for 5xx, 429, and network errors - Structured logging - URL validation """ # Retryable status codes RETRYABLE_STATUSES = {429, 500, 502, 503, 504} def __init__( self, base_url: str, max_retries: int = 3, rate_limit: int = 10, # requests per second base_delay: float = 1.0, # seconds max_delay: float = 60.0, # seconds timeout: float = 30.0, ): """ :param base_url: API base URL (e.g., 'https://api.example.com') :param max_retries: Maximum retry attempts :param rate_limit: Max requests per second :param base_delay: Initial delay for exponential backoff :param max_delay: Maximum delay cap :param timeout: Request timeout in seconds :raises ValueError: If base_url is invalid """ # Validate URL before using it parsed = urlparse(base_url) if parsed.scheme not in ("http", "https"): raise ValueError(f"Invalid URL scheme: {parsed.scheme}. Only http and https are allowed.") if not parsed.netloc: raise ValueError(f"Invalid URL: {base_url}. Must include a hostname.") self.base_url = base_url.rstrip("/") self.max_retries = max_retries self.base_delay = base_delay self.max_delay = max_delay self.timeout = aiohttp.ClientTimeout(total=timeout) # Rate limiter: token bucket algorithm (thread-safe) self._limiter = AsyncLimiter(rate_limit, 1.0) # Session will be created on first use self._session: Optional[aiohttp.ClientSession] = None async def _get_session(self) -> aiohttp.ClientSession: """Lazy-initialize and return session.""" if self._session is None or self._session.closed: self._session = aiohttp.ClientSession( timeout=self.timeout, raise_for_status=False, # We handle errors manually ) return self._session def _calculate_delay(self, attempt: int) -> float: """ Exponential backoff with full jitter. delay = base_delay * 2^attempt Then apply random jitter in [0, delay] """ delay = min(self.base_delay * (2 ** attempt), self.max_delay) import random return random.uniform(0, delay) def _should_retry(self, error: Exception, status: Optional[int]) -> bool: """Determine if request should be retried.""" if isinstance(error, (asyncio.TimeoutError, ClientError)): return True if status in self.RETRYABLE_STATUSES: return True return False async def _request( self, method: str, path: str, **kwargs: Any, ) -> Any: """ Make HTTP request with retry logic. :param method: HTTP method (GET, POST, etc.) :param path: Request path (will be joined with base_url) :param kwargs: Additional arguments for aiohttp :return: JSON response :raises MaxRetriesExceededError: If all retries fail """ last_error = None last_status = None for attempt in range(self.max_retries + 1): # Rate limiting: acquire token before request await self._limiter.acquire() session = await self._get_session() url = f"{self.base_url}{path}" try: logger.debug(f"Request: {method} {url} (attempt {attempt + 1})") async with session.request(method, url, **kwargs) as resp: last_status = resp.status # Success if 200 <= resp.status < 300: logger.info(f"Success: {method} {url} -> {resp.status}") return await resp.json() # Build error for retry decision error = ClientResponseError( request_info=resp.request_info, history=resp.history, status=resp.status, message=resp.reason or f"HTTP {resp.status}", ) # Check if retryable if self._should_retry(error, resp.status): last_error = error # Only retry if we haven't exhausted attempts if attempt < self.max_retries: delay = self._calculate_delay(attempt) logger.warning( f"Retryable error: {method} {url} -> {resp.status}. " f"Retry in {delay:.2f}s" ) await asyncio.sleep(delay) continue # Last attempt failed - will raise MaxRetriesExceededError below # Non-retryable error - raise immediately if not self._should_retry(error, resp.status): logger.error(f"Failed: {method} {url} -> {resp.status}") raise error except (asyncio.TimeoutError, ClientError) as e: last_error = e if attempt < self.max_retries and self._should_retry(e, None): delay = self._calculate_delay(attempt) logger.warning( f"Network error: {method} {url} -> {type(e).__name__}. " f"Retry in {delay:.2f}s" ) await asyncio.sleep(delay) continue raise # Should not reach here, but for type safety raise MaxRetriesExceededError( f"Max retries exceeded. Last error: {last_error}, status: {last_status}" ) async def get(self, path: str, **kwargs: Any) -> Any: """GET request.""" return await self._request("GET", path, **kwargs) async def post(self, path: str, **kwargs: Any) -> Any: """POST request.""" return await self._request("POST", path, **kwargs) async def put(self, path: str, **kwargs: Any) -> Any: """PUT request.""" return await self._request("PUT", path, **kwargs) async def delete(self, path: str, **kwargs: Any) -> Any: """DELETE request.""" return await self._request("DELETE", path, **kwargs) async def close(self) -> None: """Close the session. Call when done using the client.""" if self._session and not self._session.closed: await self._session.close() logger.debug("Client session closed") async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close()