|
| 1 | +"""Health check implementations for lifespan events.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +from dataclasses import dataclass |
| 6 | + |
| 7 | +import httpx |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class ServerHealthCheck: |
| 14 | + """Health check for upstream API.""" |
| 15 | + |
| 16 | + url: str |
| 17 | + max_retries: int = 5 |
| 18 | + retry_delay: float = 0.25 |
| 19 | + retry_delay_max: float = 10.0 |
| 20 | + timeout: float = 5.0 |
| 21 | + |
| 22 | + async def _check_health(self) -> bool: |
| 23 | + """Check if upstream API is responding.""" |
| 24 | + try: |
| 25 | + async with httpx.AsyncClient() as client: |
| 26 | + response = await client.get( |
| 27 | + self.url, timeout=self.timeout, follow_redirects=True |
| 28 | + ) |
| 29 | + response.raise_for_status() |
| 30 | + return True |
| 31 | + except Exception as e: |
| 32 | + logger.warning(f"Upstream health check failed: {e}") |
| 33 | + return False |
| 34 | + |
| 35 | + async def __call__(self) -> None: |
| 36 | + """Wait for upstream API to become available.""" |
| 37 | + for attempt in range(self.max_retries): |
| 38 | + if await self._check_health(): |
| 39 | + logger.info(f"Upstream API at {self.url} is healthy") |
| 40 | + return |
| 41 | + |
| 42 | + retry_in = min(self.retry_delay * (2**attempt), self.retry_delay_max) |
| 43 | + logger.warning( |
| 44 | + f"Upstream API not healthy, retrying in {retry_in:.1f}s " |
| 45 | + f"(attempt {attempt + 1}/{self.max_retries})" |
| 46 | + ) |
| 47 | + await asyncio.sleep(retry_in) |
| 48 | + |
| 49 | + raise RuntimeError( |
| 50 | + f"Upstream API at {self.url} failed to respond after {self.max_retries} attempts" |
| 51 | + ) |
0 commit comments