"""Read Beam readiness without waking an idle Hugging Face Inference Endpoint.""" import asyncio import os import time import httpx class BeamStatus: def __init__(self, url: httpx.URL, token: str | None) -> None: self.url = url self.headers = {'Authorization': f'Bearer {token}'} if token else {} self.namespace = ( os.environ.get('BEAM_ENDPOINT_NAMESPACE') or os.environ.get('SPACE_ID', '').partition('/')[0] ) self.name: str | None = None self.state = 'unknown' self.expires = 0.0 self.lock = asyncio.Lock() async def read(self) -> str: """Share one recent readiness reading across all open browsers.""" async with self.lock: if time.monotonic() < self.expires: return self.state try: async with httpx.AsyncClient( headers=self.headers, timeout=5, trust_env=False ) as client: self.state = await self._read(client) except (httpx.HTTPError, ValueError, KeyError, TypeError): self.state = 'unknown' self.expires = time.monotonic() + 8 return self.state async def _read(self, client: httpx.AsyncClient) -> str: if not self.url.host.endswith('.endpoints.huggingface.cloud'): response = await client.get(self.url.join('v1/models')) return 'ready' if response.is_success else 'unavailable' if not self.namespace: return 'unknown' api = ( f'https://api.endpoints.huggingface.cloud/v2/endpoint/{self.namespace}' ) state = await self._deployment_state(client, api) return { 'running': 'ready', 'scaledToZero': 'idle', 'paused': 'paused', 'pending': 'starting', 'initializing': 'starting', 'updating': 'starting', 'failed': 'unavailable', 'updateFailed': 'unavailable', }.get(state, 'unknown') async def _deployment_state(self, client: httpx.AsyncClient, api: str) -> str: """Discover our deployment by URL once, then look it up by name.""" if self.name: response = await client.get(f'{api}/{self.name}') response.raise_for_status() return response.json()['status']['state'] cursor = None while True: response = await client.get( api, params={'cursor': cursor} if cursor else {} ) response.raise_for_status() page = response.json() for endpoint in page['items']: status = endpoint['status'] if (status.get('url') or '').rstrip('/') == str(self.url).rstrip('/'): self.name = endpoint['name'] return status['state'] cursor = page.get('nextCursor') if not cursor: return 'unknown'