File size: 5,159 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
7a3215f
 
4598c11
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6437539
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4598c11
 
 
 
 
 
 
2756f0f
 
 
 
 
 
 
7a3215f
 
 
 
 
 
2756f0f
 
7a3215f
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One error envelope for every response: {"error": {"code", "message", "fields"?}}.

Services raise AppError subclasses; the handlers below turn them (and request validation errors) into JSON.
Messages are safe to show in the app.
"""

import logging

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import DBAPIError
from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
from starlette.exceptions import HTTPException as StarletteHTTPException

log = logging.getLogger(__name__)


class AppError(Exception):
    status_code = 500
    code = "INTERNAL"
    message = "Something went wrong. Please try again."

    def __init__(self, message: str | None = None, *, code: str | None = None, fields: dict[str, str] | None = None):
        self.message = message or self.message
        self.code = code or self.code
        self.fields = fields
        super().__init__(self.message)


class ValidationFailed(AppError):
    status_code, code, message = 400, "VALIDATION", "Some fields are not valid."


class Unauthenticated(AppError):
    status_code, code, message = 401, "UNAUTHENTICATED", "Please sign in again."


class PlanLimitReached(AppError):
    status_code, code, message = 402, "PLAN_LIMIT", "The free plan includes 20 analyses a week."


class Forbidden(AppError):
    status_code, code, message = 403, "FORBIDDEN", "You do not have access to this."


class NotFound(AppError):
    status_code, code, message = 404, "NOT_FOUND", "We couldn't find that."


class Conflict(AppError):
    status_code, code, message = 409, "CONFLICT", "This conflicts with existing data."


class TooLarge(AppError):
    status_code, code, message = 413, "TOO_LARGE", "The file is too large."


class Unprocessable(AppError):
    status_code, code, message = 422, "UNPROCESSABLE", "The request could not be processed."


class RateLimited(AppError):
    status_code, code, message = 429, "RATE_LIMITED", "Too many attempts. Please wait a minute and try again."


class ServiceUnavailable(AppError):
    status_code, code, message = 503, "UNAVAILABLE", "A service we depend on is unavailable. Please try again."


def _body(code: str, message: str, fields: dict[str, str] | None = None) -> dict:
    error: dict = {"code": code, "message": message}
    if fields:
        error["fields"] = fields
    return {"error": error}


def _field_path(loc: tuple) -> str:
    parts = [str(p) for p in loc if p not in ("body", "query", "path", "header")]
    path = ""
    for p in parts:
        path += f"[{p}]" if p.isdigit() else (f".{p}" if path else p)
    return path or "request"


def register_error_handlers(app: FastAPI) -> None:
    @app.exception_handler(AppError)
    async def _app_error(_: Request, exc: AppError) -> JSONResponse:
        return JSONResponse(_body(exc.code, exc.message, exc.fields), status_code=exc.status_code)

    @app.exception_handler(StarletteHTTPException)
    async def _http_error(_: Request, exc: StarletteHTTPException) -> JSONResponse:
        """Routing errors (unknown path, wrong method) use the same envelope as everything else."""
        codes = {404: ("NOT_FOUND", NotFound.message), 405: ("METHOD_NOT_ALLOWED", "This method is not allowed here.")}
        code, message = codes.get(exc.status_code, ("HTTP_ERROR", str(exc.detail)))
        return JSONResponse(_body(code, message), status_code=exc.status_code, headers=getattr(exc, "headers", None))

    @app.exception_handler(RequestValidationError)
    async def _validation_error(_: Request, exc: RequestValidationError) -> JSONResponse:
        fields: dict[str, str] = {}
        for err in exc.errors():
            fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value."))
        return JSONResponse(_body(ValidationFailed.code, ValidationFailed.message, fields), status_code=400)

    @app.exception_handler(SQLAlchemyTimeoutError)
    async def _pool_exhausted(_: Request, exc: SQLAlchemyTimeoutError) -> JSONResponse:
        log.warning("database pool exhausted: %s", exc)
        return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
                            headers={"Retry-After": "2"})

    @app.exception_handler(Exception)
    async def _unexpected(_: Request, exc: Exception) -> JSONResponse:
        return unexpected_error_response(exc)


DB_BUSY_MARKERS = ("max clients reached", "too many connections", "remaining connection slots")


def unexpected_error_response(exc: Exception) -> JSONResponse:
    """500 for bugs; 503 (retryable) when the database has no free connection."""
    if isinstance(exc, DBAPIError) and any(m in str(exc).lower() for m in DB_BUSY_MARKERS):
        log.warning("database has no free connection: %s", str(exc).splitlines()[0])
        return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
                            headers={"Retry-After": "2"})
    log.exception("unhandled error", exc_info=exc)
    return JSONResponse(_body(AppError.code, AppError.message), status_code=500)