Spaces:
Running on Zero
Running on Zero
File size: 2,648 Bytes
baa274b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | """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'
|