from fastapi import Request from app.config import settings from app.core.errors import ApiException from app.schemas.error import ErrorCode from app.services.pipeline import CameraWorker from app.services.registry import Registry def get_registry(request: Request) -> Registry: return request.app.state.registry def verify_camera_in_catalog(camera_id: str, request: Request) -> str: """Lightweight check used by historical endpoints (/metrics/1min, /events?camera_id=) that work even when no worker is running. Raises 404 if camera_id isn't in cctv_streams.""" reg = get_registry(request) if reg.db is None: raise ApiException(503, ErrorCode.service_unavailable, "database not ready") rows = reg.db.fetchall( "SELECT 1 FROM cctv_streams WHERE id = %s LIMIT 1", (camera_id,), ) if not rows: raise ApiException( status_code=404, code=ErrorCode.not_found, message="camera_id not found", details={"camera_id": camera_id}, ) return camera_id def get_worker(camera_id: str, request: Request) -> CameraWorker: """Resolve the running CameraWorker, with a meaningful 503 / 404 when the camera isn't active. - **404 not_found** — camera_id doesn't exist in the `cctv_streams` catalog. - **503 not_activated** — exists in the catalog but no YOLO worker is running. Either the active pool (MAX_STREAMS) is full or this camera wasn't picked at boot. """ reg = get_registry(request) worker = reg.get_worker(camera_id) if worker is not None: return worker if reg.db is not None: try: rows = reg.db.fetchall( "SELECT 1 FROM cctv_streams WHERE id = %s LIMIT 1", (camera_id,), ) except Exception: # noqa: BLE001 rows = [] if rows: raise ApiException( status_code=503, code=ErrorCode.not_activated, message="camera exists in catalog but no worker is running", details={ "camera_id": camera_id, "active_workers": str(len(reg.workers)), "max_streams": str(settings.max_streams), }, ) raise ApiException( status_code=404, code=ErrorCode.not_found, message="camera_id not found", details={"camera_id": camera_id}, ) def _ws_base(request: Request) -> str: base = str(request.base_url).rstrip("/") if base.startswith("https://"): return "wss://" + base[len("https://"):] if base.startswith("http://"): return "ws://" + base[len("http://"):] return base def build_camera_links(request: Request, camera_id: str) -> dict: http_base = str(request.base_url).rstrip("/") ws_base = _ws_base(request) prefix = request.app.state.api_prefix return { "embed": { "hls": f"{http_base}{prefix}/cameras/{camera_id}/hls/playlist.m3u8", }, "metrics": { "websocket": f"{ws_base}{prefix}/cameras/{camera_id}/metrics/ws", }, }