File size: 4,581 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""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: `<video src=playlist.m3u8>`."},
            {"name": "Metrics (WebSocket)",
             "description": "Realtime push of analytics, session aggregates, "
                            "and geo-tagged detections. Live-only — nothing "
                            "in DB beyond the per-camera session row."},
        ]

        app.openapi_schema = schema
        return schema

    return _build