Spaces:
Runtime error
Runtime error
File size: 3,182 Bytes
40e0b51 | 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 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",
},
}
|