File size: 5,307 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""Exception handlers + request-id middleware that emit the canonical
error envelope on every non-2xx response."""
from __future__ import annotations

import logging
import uuid
from typing import Any

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.schemas.error import (
    ApiErrorEnvelope,
    ErrorCode,
    ErrorPayload,
    InternalErrorEnvelope,
    NotFoundEnvelope,
    ServiceUnavailableEnvelope,
    UnauthorizedEnvelope,
    ValidationErrorEnvelope,
)

log = logging.getLogger(__name__)


class ApiException(Exception):
    """Raise this from route handlers to emit a typed error envelope.

    Prefer this over ``HTTPException`` so the envelope carries an
    explicit ``ErrorCode`` and structured ``details``."""

    def __init__(self, status_code: int, code: ErrorCode, message: str,
                 details: dict[str, str] | None = None):
        super().__init__(message)
        self.status_code = status_code
        self.code = code
        self.message = message
        self.details = details or {}


_STATUS_TO_CODE: dict[int, ErrorCode] = {
    400: ErrorCode.bad_request,
    401: ErrorCode.unauthorized,
    404: ErrorCode.not_found,
    422: ErrorCode.validation_error,
    503: ErrorCode.service_unavailable,
}

# Maps status code → response model exposed in the OpenAPI spec.
COMMON_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = {
    400: {"model": ValidationErrorEnvelope,
          "description": "Request payload failed validation."},
    404: {"model": NotFoundEnvelope,
          "description": "Resource does not exist."},
    503: {"model": ServiceUnavailableEnvelope,
          "description": "Pipeline not ready or upstream unavailable."},
    500: {"model": InternalErrorEnvelope,
          "description": "Unexpected server error."},
}


def _request_id(request: Request) -> str:
    return getattr(request.state, "request_id", None) or str(uuid.uuid4())


def _envelope_json(code: ErrorCode, message: str,
                   details: dict[str, str], request_id: str) -> dict:
    return ApiErrorEnvelope(
        error=ErrorPayload(
            code=code, message=message, details=details, request_id=request_id,
        )
    ).model_dump(mode="json")


def _json_response(status_code: int, envelope: dict, request_id: str) -> JSONResponse:
    return JSONResponse(
        status_code=status_code,
        content=envelope,
        headers={"X-Request-ID": request_id},
    )


def install(app: FastAPI) -> None:
    """Wire middleware + handlers into the app."""

    @app.middleware("http")
    async def request_id_middleware(request: Request, call_next):
        rid = request.headers.get("x-request-id") or str(uuid.uuid4())
        request.state.request_id = rid
        try:
            response = await call_next(request)
        except Exception:
            # Fall through to the generic handler; ensure header is set
            # on whatever response that handler builds.
            raise
        response.headers["X-Request-ID"] = rid
        return response

    @app.exception_handler(ApiException)
    async def _api_exception_handler(request: Request, exc: ApiException):
        rid = _request_id(request)
        return _json_response(
            exc.status_code,
            _envelope_json(exc.code, exc.message, exc.details, rid),
            rid,
        )

    @app.exception_handler(StarletteHTTPException)
    async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
        rid = _request_id(request)
        code = _STATUS_TO_CODE.get(exc.status_code, ErrorCode.internal_server_error)
        detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
        return _json_response(
            exc.status_code,
            _envelope_json(code, detail, {}, rid),
            rid,
        )

    @app.exception_handler(RequestValidationError)
    async def _validation_handler(request: Request, exc: RequestValidationError):
        rid = _request_id(request)
        details: dict[str, str] = {}
        for err in exc.errors():
            loc = ".".join(str(p) for p in err.get("loc", [])[1:]) or "_"
            details[loc] = err.get("msg", "invalid")
        return _json_response(
            422,
            _envelope_json(
                ErrorCode.validation_error,
                "request validation failed",
                details, rid,
            ),
            rid,
        )

    @app.exception_handler(Exception)
    async def _unhandled_handler(request: Request, exc: Exception):
        rid = _request_id(request)
        log.exception("unhandled exception (request_id=%s): %s", rid, exc)
        return _json_response(
            500,
            _envelope_json(
                ErrorCode.internal_server_error,
                "internal server error",
                {}, rid,
            ),
            rid,
        )

    # Mark these as used so type checkers don't complain about the
    # closures being unused locals.
    _ = (
        request_id_middleware,
        _api_exception_handler,
        _http_exception_handler,
        _validation_handler,
        _unhandled_handler,
    )