"""OpenAPI customisation. FastAPI auto-injects a 422 response on every route whose payload references its own `HTTPValidationError` model. We replace it with our canonical `ValidationErrorEnvelope` so the generated spec stays consistent with the runtime envelope returned by `app.core.errors`. We also surface the WebSocket route, which FastAPI does not emit into OpenAPI by default.""" from __future__ import annotations from typing import Any from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from app.config import settings from app.schemas.error import ValidationErrorEnvelope _VALIDATION_REF = "#/components/schemas/ValidationErrorEnvelope" _LEGACY_SCHEMAS = ("HTTPValidationError", "ValidationError") def _rewrite_422(responses: dict[str, Any]) -> None: r422 = responses.get("422") if not r422: return r422["description"] = "Request payload failed validation." content = r422.setdefault("content", {}) content["application/json"] = {"schema": {"$ref": _VALIDATION_REF}} def _websocket_path_item() -> dict[str, Any]: """Hand-authored OpenAPI path for the WS metrics endpoint.""" return { "get": { "tags": ["Metrics (WebSocket)"], "summary": "Realtime metrics over WebSocket.", "description": ( "Upgrade this request to a WebSocket. Server pushes a " "metrics JSON snapshot every `METRICS_WS_INTERVAL` " "seconds (default 1.0s). Same payload shape as the " "`current` field of the REST `/metrics` response.\n\n" "**Close codes**\n" "- `1008` — camera_id not found\n" "- `1011` — internal server error" ), "parameters": [{ "name": "camera_id", "in": "path", "required": True, "schema": {"type": "string"}, }], "responses": { "101": {"description": "Switching Protocols — WebSocket established."}, }, }, } def custom_openapi(app: FastAPI): def _build() -> dict[str, Any]: if app.openapi_schema: return app.openapi_schema schema = get_openapi( title=app.title, version=app.version, summary=getattr(app, "summary", None), description=app.description, routes=app.routes, contact=app.contact, license_info=app.license_info, ) # Register the envelope as a top-level schema if FastAPI hasn't # already (happens when no response_model references it). comps = schema.setdefault("components", {}).setdefault("schemas", {}) if "ValidationErrorEnvelope" not in comps: comps["ValidationErrorEnvelope"] = ValidationErrorEnvelope.model_json_schema( ref_template="#/components/schemas/{model}" ) for path_item in schema.get("paths", {}).values(): for method, op in path_item.items(): if method not in {"get", "post", "put", "delete", "patch"}: continue _rewrite_422(op.setdefault("responses", {})) # Drop the now-unreferenced FastAPI default schemas. for name in _LEGACY_SCHEMAS: comps.pop(name, None) # Add the WebSocket endpoint (documented but not callable via # plain GET; clients must perform the WS upgrade). ws_path = f"{settings.api_prefix}/cameras/{{camera_id}}/metrics/ws" schema["paths"][ws_path] = _websocket_path_item() # Tag ordering. schema["tags"] = [ {"name": "Meta", "description": "Service metadata."}, {"name": "Cameras", "description": "Catalog + connect/disconnect actions. Each " "active camera exposes an annotated HLS stream " "and a realtime WebSocket."}, {"name": "Stream", "description": "HLS playlist + .ts segments with YOLO bboxes " "baked into the encoded video. Plug-and-play " "embeds: `