rn-forge-fastapi 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rn_forge/fastapi/__init__.py +111 -0
- rn_forge/fastapi/app.py +210 -0
- rn_forge/fastapi/auth/__init__.py +69 -0
- rn_forge/fastapi/auth/authorization.py +62 -0
- rn_forge/fastapi/auth/csrf.py +243 -0
- rn_forge/fastapi/auth/dependencies.py +374 -0
- rn_forge/fastapi/auth/proxies.py +55 -0
- rn_forge/fastapi/auth/rate_limit.py +91 -0
- rn_forge/fastapi/auth/redis.py +88 -0
- rn_forge/fastapi/auth/routes.py +725 -0
- rn_forge/fastapi/auth/sessions.py +504 -0
- rn_forge/fastapi/cors.py +80 -0
- rn_forge/fastapi/dependencies.py +157 -0
- rn_forge/fastapi/deprecation.py +45 -0
- rn_forge/fastapi/health.py +71 -0
- rn_forge/fastapi/idempotency.py +82 -0
- rn_forge/fastapi/merge_patch.py +89 -0
- rn_forge/fastapi/openapi.py +91 -0
- rn_forge/fastapi/problem.py +155 -0
- rn_forge/fastapi/py.typed +0 -0
- rn_forge/fastapi/read_mask.py +86 -0
- rn_forge/fastapi/soft_delete.py +188 -0
- rn_forge/fastapi/transfer.py +936 -0
- rn_forge_fastapi-0.4.0.dist-info/METADATA +165 -0
- rn_forge_fastapi-0.4.0.dist-info/RECORD +27 -0
- rn_forge_fastapi-0.4.0.dist-info/WHEEL +4 -0
- rn_forge_fastapi-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""FastAPI dependencies for pagination and conditional request headers.
|
|
2
|
+
|
|
3
|
+
Factories keep endpoint-specific limits and header names in scope for FastAPI
|
|
4
|
+
without relying on closure variables in evaluated annotations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable, Collection
|
|
10
|
+
|
|
11
|
+
from fastapi import Header, Query, Request
|
|
12
|
+
from fastapi.responses import Response
|
|
13
|
+
from rn_forge.web import (
|
|
14
|
+
ANY_ETAG,
|
|
15
|
+
DEFAULT_PAGE_SIZE_PARAM,
|
|
16
|
+
DEFAULT_PAGE_TOKEN_PARAM,
|
|
17
|
+
IDEMPOTENCY_KEY_HEADER,
|
|
18
|
+
ORDER_BY_PARAM,
|
|
19
|
+
Cursor,
|
|
20
|
+
EntityVersionETagCodec,
|
|
21
|
+
ETagCodec,
|
|
22
|
+
OrderField,
|
|
23
|
+
check_idempotency_key,
|
|
24
|
+
check_precondition,
|
|
25
|
+
clamp_page_size,
|
|
26
|
+
decode_cursor,
|
|
27
|
+
is_not_modified,
|
|
28
|
+
parse_order_by,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"conditional_get",
|
|
33
|
+
"order_by_param",
|
|
34
|
+
"page_params",
|
|
35
|
+
"require_idempotency_key",
|
|
36
|
+
"require_if_match",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def page_params(*, cap: int, default: int) -> Callable[..., tuple[int, Cursor | None]]:
|
|
41
|
+
"""Return a dependency yielding ``(page_size, cursor)`` from ``pageSize``/``pageToken``.
|
|
42
|
+
|
|
43
|
+
The size is **clamped, never rejected** (AIP-158), so the parameter carries
|
|
44
|
+
no ``le=`` bound — that would be a 422 — and states the cap in its
|
|
45
|
+
description instead. The token is decoded eagerly, so a tampered one is a
|
|
46
|
+
400 before it reaches a query.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
cap: The largest page this endpoint serves.
|
|
50
|
+
default: The page size when the client asks for none.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def dependency(
|
|
54
|
+
page_size: int | None = Query(
|
|
55
|
+
default=None,
|
|
56
|
+
alias=DEFAULT_PAGE_SIZE_PARAM,
|
|
57
|
+
description=f"Requested page size. Above {cap} it is clamped to {cap}.",
|
|
58
|
+
),
|
|
59
|
+
page_token: str | None = Query(
|
|
60
|
+
default=None,
|
|
61
|
+
alias=DEFAULT_PAGE_TOKEN_PARAM,
|
|
62
|
+
description="The previous page's `nextPageToken`. Absent for the first page.",
|
|
63
|
+
),
|
|
64
|
+
) -> tuple[int, Cursor | None]:
|
|
65
|
+
size = clamp_page_size(page_size, default=default, cap=cap)
|
|
66
|
+
return size, decode_cursor(page_token) if page_token is not None else None
|
|
67
|
+
|
|
68
|
+
return dependency
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def order_by_param(
|
|
72
|
+
*, allowed: Collection[str]
|
|
73
|
+
) -> Callable[..., tuple[OrderField, ...]]:
|
|
74
|
+
"""Return a dependency yielding the parsed AIP-132 ``orderBy`` terms.
|
|
75
|
+
|
|
76
|
+
The value is a comma-separated list of terms. A term outside *allowed*, a malformed one, or a
|
|
77
|
+
repeated field is a 400 before it reaches a query. Pass the result and the decoded cursor to
|
|
78
|
+
:func:`rn_forge.web.check_cursor_order`, and the canonical order from
|
|
79
|
+
:func:`rn_forge.web.format_order_by` to :func:`rn_forge.web.encode_cursor`.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
allowed: The field names the endpoint can sort by, as they appear on the wire.
|
|
83
|
+
"""
|
|
84
|
+
names = sorted(allowed)
|
|
85
|
+
|
|
86
|
+
def dependency(
|
|
87
|
+
order_by: str | None = Query(
|
|
88
|
+
default=None,
|
|
89
|
+
alias=ORDER_BY_PARAM,
|
|
90
|
+
description=(
|
|
91
|
+
"Sort order: a comma-separated list of fields, each optionally "
|
|
92
|
+
"followed by `asc` or `desc`, e.g. `team, score desc`. "
|
|
93
|
+
f"Sortable fields: {', '.join(names)}."
|
|
94
|
+
),
|
|
95
|
+
),
|
|
96
|
+
) -> tuple[OrderField, ...]:
|
|
97
|
+
return parse_order_by(order_by, allowed=names)
|
|
98
|
+
|
|
99
|
+
return dependency
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def require_idempotency_key(
|
|
103
|
+
*, header: str = IDEMPOTENCY_KEY_HEADER
|
|
104
|
+
) -> Callable[..., str]:
|
|
105
|
+
"""Return a dependency yielding the idempotency key, or raising a 400 without one.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
header: The request header carrying the key.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
def dependency(key: str | None = Header(default=None, alias=header)) -> str:
|
|
112
|
+
return check_idempotency_key(key, header=header)
|
|
113
|
+
|
|
114
|
+
return dependency
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def conditional_get(request: Request, etag: str) -> Response | None:
|
|
118
|
+
"""Return the 304 to send for *request*'s ``If-None-Match``, or ``None``.
|
|
119
|
+
|
|
120
|
+
Call once the resource's current ETag is known. ``None`` means the caller
|
|
121
|
+
proceeds with its normal 200 response; a non-``None`` result is a
|
|
122
|
+
:class:`~fastapi.responses.Response` to return as-is — 304, no body, the
|
|
123
|
+
``ETag`` repeated (RFC 9110 §13.1.2, §15.4.5).
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
request: The inbound request.
|
|
127
|
+
etag: The resource's current ETag validator.
|
|
128
|
+
"""
|
|
129
|
+
if is_not_modified(request.headers.get("if-none-match"), etag):
|
|
130
|
+
return Response(status_code=304, headers={"ETag": etag})
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def require_if_match(*, codec: ETagCodec | None = None) -> Callable[..., str]:
|
|
135
|
+
"""Return a dependency yielding the raw ``If-Match`` value of a write.
|
|
136
|
+
|
|
137
|
+
Absent → 428, unparseable → 400, both before the route runs. The value is
|
|
138
|
+
returned verbatim for a later :func:`rn_forge.web.check_precondition` call.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
codec: The validator format. Defaults to
|
|
142
|
+
:class:`rn_forge.web.EntityVersionETagCodec`.
|
|
143
|
+
"""
|
|
144
|
+
parser = codec if codec is not None else EntityVersionETagCodec()
|
|
145
|
+
|
|
146
|
+
def dependency(
|
|
147
|
+
if_match: str | None = Header(default=None, alias="If-Match"),
|
|
148
|
+
) -> str:
|
|
149
|
+
if if_match is None:
|
|
150
|
+
# Web owns the 428 and its detail; with required=True this raises.
|
|
151
|
+
check_precondition(None, current_version=0, required=True)
|
|
152
|
+
assert if_match is not None # noqa: S101 # type narrowing, not validation
|
|
153
|
+
if if_match.strip() != ANY_ETAG:
|
|
154
|
+
parser.parse(if_match)
|
|
155
|
+
return if_match
|
|
156
|
+
|
|
157
|
+
return dependency
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""A FastAPI dependency stamping RFC 9745/RFC 8594 deprecation headers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
from fastapi import Response
|
|
9
|
+
from rn_forge.web import deprecation_headers
|
|
10
|
+
|
|
11
|
+
__all__ = ["deprecated"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def deprecated(
|
|
15
|
+
*,
|
|
16
|
+
deprecated_at: datetime,
|
|
17
|
+
sunset: datetime | None = None,
|
|
18
|
+
link: str | None = None,
|
|
19
|
+
) -> Callable[[Response], None]:
|
|
20
|
+
"""Return a dependency that stamps :func:`rn_forge.web.deprecation_headers` on the response.
|
|
21
|
+
|
|
22
|
+
Pair it with the route's own ``deprecated=True`` so the OpenAPI document
|
|
23
|
+
also marks the operation deprecated — this dependency only sets the wire
|
|
24
|
+
headers.
|
|
25
|
+
|
|
26
|
+
Example::
|
|
27
|
+
|
|
28
|
+
@app.get(
|
|
29
|
+
"/v1/orders",
|
|
30
|
+
deprecated=True,
|
|
31
|
+
dependencies=[Depends(deprecated(deprecated_at=SUNSET_ANNOUNCED))],
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
deprecated_at: When the endpoint became deprecated.
|
|
36
|
+
sunset: When the endpoint stops being served. Omitted when unscheduled.
|
|
37
|
+
link: A URI for the deprecation notice.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def dependency(response: Response) -> None:
|
|
41
|
+
response.headers.update(
|
|
42
|
+
deprecation_headers(deprecated_at=deprecated_at, sunset=sunset, link=link)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
return dependency
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Build liveness and readiness routes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Collection, Mapping
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter
|
|
8
|
+
from fastapi.responses import JSONResponse
|
|
9
|
+
from rn_forge.web import (
|
|
10
|
+
LEGACY_LIVENESS_PATH,
|
|
11
|
+
LIVENESS_PATH,
|
|
12
|
+
READINESS_PATH,
|
|
13
|
+
Check,
|
|
14
|
+
HealthReport,
|
|
15
|
+
liveness_body,
|
|
16
|
+
run_checks,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = ["health_router"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def health_router(
|
|
23
|
+
*,
|
|
24
|
+
checks: Mapping[str, Check],
|
|
25
|
+
required: Collection[str] = (),
|
|
26
|
+
prefix: str = "",
|
|
27
|
+
timeout: float | None = None,
|
|
28
|
+
liveness_path: str = LIVENESS_PATH,
|
|
29
|
+
readiness_path: str = READINESS_PATH,
|
|
30
|
+
legacy_liveness_path: str | None = LEGACY_LIVENESS_PATH,
|
|
31
|
+
) -> APIRouter:
|
|
32
|
+
"""Return a router serving the liveness and readiness paths.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
checks: Name → check, sync or async, returning a
|
|
36
|
+
:class:`rn_forge.web.CheckResult` or a ``bool``. A check that raises
|
|
37
|
+
is reported as ``fail``; it never fails the endpoint.
|
|
38
|
+
required: The names whose failure makes the service unavailable (503).
|
|
39
|
+
prefix: Mounted in front of every path.
|
|
40
|
+
timeout: Seconds each check may run before it is reported as ``fail``,
|
|
41
|
+
so a hung dependency cannot hang the readiness path. ``None``
|
|
42
|
+
waits indefinitely.
|
|
43
|
+
liveness_path: The liveness path.
|
|
44
|
+
readiness_path: The readiness path.
|
|
45
|
+
legacy_liveness_path: An alias of *liveness_path*, marked deprecated
|
|
46
|
+
in the OpenAPI document. ``None`` serves no alias.
|
|
47
|
+
"""
|
|
48
|
+
router = APIRouter(prefix=prefix, tags=["health"])
|
|
49
|
+
|
|
50
|
+
@router.get(liveness_path)
|
|
51
|
+
async def livez() -> dict[str, str]:
|
|
52
|
+
return liveness_body()
|
|
53
|
+
|
|
54
|
+
if legacy_liveness_path is not None:
|
|
55
|
+
|
|
56
|
+
@router.get(legacy_liveness_path, deprecated=True)
|
|
57
|
+
async def healthz() -> dict[str, str]:
|
|
58
|
+
return liveness_body()
|
|
59
|
+
|
|
60
|
+
@router.get(
|
|
61
|
+
readiness_path,
|
|
62
|
+
response_model=HealthReport,
|
|
63
|
+
responses={
|
|
64
|
+
503: {"model": HealthReport, "description": "A required check failed"}
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
async def readyz() -> JSONResponse:
|
|
68
|
+
report = await run_checks(checks, required=required, timeout=timeout)
|
|
69
|
+
return JSONResponse(report.as_body(), status_code=report.http_status)
|
|
70
|
+
|
|
71
|
+
return router
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""A route decorator over :func:`rn_forge.web.run_idempotent_async`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
+
from typing import Any, Concatenate
|
|
9
|
+
|
|
10
|
+
from fastapi import Request
|
|
11
|
+
from fastapi.responses import JSONResponse, Response
|
|
12
|
+
from rn_forge.web import (
|
|
13
|
+
IDEMPOTENCY_KEY_HEADER,
|
|
14
|
+
AsyncIdempotencyStore,
|
|
15
|
+
run_idempotent_async,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = ["idempotent"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def idempotent[**P](
|
|
22
|
+
store: AsyncIdempotencyStore,
|
|
23
|
+
*,
|
|
24
|
+
scope: str,
|
|
25
|
+
header: str = IDEMPOTENCY_KEY_HEADER,
|
|
26
|
+
) -> Callable[
|
|
27
|
+
[Callable[Concatenate[Request, P], Awaitable[Response]]],
|
|
28
|
+
Callable[Concatenate[Request, P], Awaitable[Response]],
|
|
29
|
+
]:
|
|
30
|
+
"""Decorate an async route so an unsafe request executes once per key.
|
|
31
|
+
|
|
32
|
+
The decorated route must declare ``request: Request`` as a parameter —
|
|
33
|
+
FastAPI injects it like any other dependency — and must return a
|
|
34
|
+
:class:`~fastapi.responses.Response` whose body is JSON. Safe methods
|
|
35
|
+
bypass the store. A missing key on an unsafe method raises
|
|
36
|
+
:class:`rn_forge.web.IdempotencyKeyRequired` (400); a replay returns the
|
|
37
|
+
stored status and body verbatim; the same key with a different body
|
|
38
|
+
raises :class:`rn_forge.web.IdempotencyKeyReuse` (422); a duplicate while
|
|
39
|
+
the original is still in flight raises
|
|
40
|
+
:class:`rn_forge.web.IdempotencyKeyInFlight` (409).
|
|
41
|
+
|
|
42
|
+
Example::
|
|
43
|
+
|
|
44
|
+
@app.post("/charges", status_code=201)
|
|
45
|
+
@idempotent(store, scope="charges")
|
|
46
|
+
async def create_charge(request: Request, body: Charge) -> JSONResponse:
|
|
47
|
+
...
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def decorate(
|
|
51
|
+
handler: Callable[Concatenate[Request, P], Awaitable[Response]],
|
|
52
|
+
) -> Callable[Concatenate[Request, P], Awaitable[Response]]:
|
|
53
|
+
@functools.wraps(handler)
|
|
54
|
+
async def wrapper(
|
|
55
|
+
request: Request, *args: P.args, **kwargs: P.kwargs
|
|
56
|
+
) -> Response:
|
|
57
|
+
# The runner returns (status, body); the original Response object
|
|
58
|
+
# — headers included — is kept here for the non-replayed case.
|
|
59
|
+
executed: list[Response] = []
|
|
60
|
+
|
|
61
|
+
async def execute() -> tuple[int, Mapping[str, Any]]:
|
|
62
|
+
response = await handler(request, *args, **kwargs)
|
|
63
|
+
executed.append(response)
|
|
64
|
+
return response.status_code, json.loads(bytes(response.body))
|
|
65
|
+
|
|
66
|
+
raw_body = await request.body()
|
|
67
|
+
result = await run_idempotent_async(
|
|
68
|
+
store,
|
|
69
|
+
scope=scope,
|
|
70
|
+
key=request.headers.get(header),
|
|
71
|
+
method=request.method,
|
|
72
|
+
body=json.loads(raw_body) if raw_body else None,
|
|
73
|
+
execute=execute,
|
|
74
|
+
header=header,
|
|
75
|
+
)
|
|
76
|
+
if result.replayed:
|
|
77
|
+
return JSONResponse(dict(result.body), status_code=result.status)
|
|
78
|
+
return executed[0]
|
|
79
|
+
|
|
80
|
+
return wrapper
|
|
81
|
+
|
|
82
|
+
return decorate
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""FastAPI binding for JSON Merge Patch (RFC 7396).
|
|
2
|
+
|
|
3
|
+
On a ``PATCH`` route, declare :func:`merge_patch_body` before ``require_if_match``, call
|
|
4
|
+
:func:`rn_forge.web.check_precondition` in the route, then merge the body into the stored
|
|
5
|
+
resource with :func:`merge_into`. Add :func:`merge_patch_openapi` as the route's
|
|
6
|
+
``openapi_extra``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from fastapi import Request
|
|
16
|
+
from fastapi.exceptions import RequestValidationError
|
|
17
|
+
from pydantic import BaseModel, ValidationError
|
|
18
|
+
from rn_forge.web import (
|
|
19
|
+
MERGE_PATCH_MEDIA_TYPE,
|
|
20
|
+
InvalidMergePatch,
|
|
21
|
+
UnsupportedMediaType,
|
|
22
|
+
merge_representation,
|
|
23
|
+
require_patch_object,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = ["merge_into", "merge_patch_body", "merge_patch_openapi"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def merge_patch_body() -> Callable[..., Any]:
|
|
30
|
+
"""Return a dependency yielding the raw request body.
|
|
31
|
+
|
|
32
|
+
The dependency raises :class:`rn_forge.web.UnsupportedMediaType` (415, with
|
|
33
|
+
``Accept-Patch``) unless the request's media type, ignoring parameters, is
|
|
34
|
+
``application/merge-patch+json``. The body is returned as bytes, unparsed; pass it to
|
|
35
|
+
:func:`merge_into`.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
async def dependency(request: Request) -> bytes:
|
|
39
|
+
media_type = request.headers.get("content-type", "").split(";")[0].strip()
|
|
40
|
+
if media_type.lower() != MERGE_PATCH_MEDIA_TYPE:
|
|
41
|
+
raise UnsupportedMediaType()
|
|
42
|
+
return await request.body()
|
|
43
|
+
|
|
44
|
+
return dependency
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def merge_into[M: BaseModel](model: type[M], current: object, body: bytes) -> M:
|
|
48
|
+
"""Merge the merge-patch *body* into *current* and return the validated *model*.
|
|
49
|
+
|
|
50
|
+
*body* is parsed as JSON and must be an object. *current* is dumped through *model* by alias, merged with
|
|
51
|
+
:func:`rn_forge.web.merge_representation`, and the result validated as a full document.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
model: The pydantic model of the resource.
|
|
55
|
+
current: The stored resource: a mapping or an object with matching attributes.
|
|
56
|
+
body: The raw request body from :func:`merge_patch_body`.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
rn_forge.web.InvalidMergePatch: *body* is not valid JSON or not a JSON object.
|
|
60
|
+
fastapi.exceptions.RequestValidationError: The merged document is invalid. Each error's
|
|
61
|
+
location is prefixed with ``"body"``.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
patch = require_patch_object(json.loads(body))
|
|
65
|
+
except ValueError:
|
|
66
|
+
raise InvalidMergePatch() from None
|
|
67
|
+
representation = model.model_validate(current, from_attributes=True).model_dump(
|
|
68
|
+
by_alias=True, mode="json"
|
|
69
|
+
)
|
|
70
|
+
merged = merge_representation(representation, patch)
|
|
71
|
+
try:
|
|
72
|
+
return model.model_validate(merged)
|
|
73
|
+
except ValidationError as exc:
|
|
74
|
+
raise RequestValidationError(
|
|
75
|
+
[
|
|
76
|
+
{**error, "loc": ("body", *error["loc"])}
|
|
77
|
+
for error in exc.errors(include_url=False, include_context=False)
|
|
78
|
+
]
|
|
79
|
+
) from exc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def merge_patch_openapi() -> dict[str, Any]:
|
|
83
|
+
"""Return the ``openapi_extra`` declaring a merge-patch request body."""
|
|
84
|
+
return {
|
|
85
|
+
"requestBody": {
|
|
86
|
+
"required": True,
|
|
87
|
+
"content": {MERGE_PATCH_MEDIA_TYPE: {"schema": {"type": "object"}}},
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Repair FastAPI OpenAPI documents to match the shared wire contract.
|
|
2
|
+
|
|
3
|
+
Accuracy only: the repair adds the ``ProblemDetail`` component and declares
|
|
4
|
+
the problem+json responses the app can actually produce, and removes
|
|
5
|
+
FastAPI's replaced validation schema. It does not rename components or pin an
|
|
6
|
+
OpenAPI version.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import Any, Final
|
|
13
|
+
|
|
14
|
+
from fastapi.routing import APIRoute
|
|
15
|
+
from rn_forge.web import (
|
|
16
|
+
VALIDATION_ERROR,
|
|
17
|
+
ProblemDetail,
|
|
18
|
+
ProblemRegistry,
|
|
19
|
+
default_registry,
|
|
20
|
+
)
|
|
21
|
+
from rn_forge.web.openapi import (
|
|
22
|
+
add_problem_responses,
|
|
23
|
+
problem_response,
|
|
24
|
+
)
|
|
25
|
+
from rn_forge.web.openapi import operation_id as wire_operation_id
|
|
26
|
+
|
|
27
|
+
__all__ = ["operation_id"]
|
|
28
|
+
|
|
29
|
+
_SCHEMA_REF_PREFIX: Final = "#/components/schemas/"
|
|
30
|
+
_FASTAPI_VALIDATION_SCHEMAS: Final = ("HTTPValidationError", "ValidationError")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def operation_id(route: APIRoute) -> str:
|
|
34
|
+
"""Return the ``operationId`` for *route*, per :func:`rn_forge.web.operation_id`.
|
|
35
|
+
|
|
36
|
+
Pass it as ``FastAPI(generate_unique_id_function=operation_id)``. Use an
|
|
37
|
+
explicit ``operation_id=`` for routes that cannot follow the shared rule.
|
|
38
|
+
"""
|
|
39
|
+
method = min(route.methods) if route.methods else "GET"
|
|
40
|
+
return wire_operation_id(route.path_format, method)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def repair_problem_schema(
|
|
44
|
+
schema: dict[str, Any], *, registry: ProblemRegistry | None = None
|
|
45
|
+
) -> dict[str, Any]:
|
|
46
|
+
"""Repair *schema* in place: declare the problem responses, and nothing else.
|
|
47
|
+
|
|
48
|
+
Called once by :meth:`rn_forge.fastapi.app.FastApiApp.openapi` against the
|
|
49
|
+
document it caches, so the repair never re-runs. It keeps the
|
|
50
|
+
``ProblemDetail`` component, adds an ``application/problem+json`` response
|
|
51
|
+
for each of *registry*'s statuses (plus 500) to every operation that does
|
|
52
|
+
not already declare one, and replaces FastAPI's own 422 — the validation
|
|
53
|
+
handlers have replaced the body it describes.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
schema: The document FastAPI built, as returned by its own
|
|
57
|
+
``openapi()``.
|
|
58
|
+
registry: The rows the app's problem handlers render with. Defaults to
|
|
59
|
+
:func:`rn_forge.web.default_registry`.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
*schema*, for chaining.
|
|
63
|
+
"""
|
|
64
|
+
rows = registry if registry is not None else default_registry()
|
|
65
|
+
components: dict[str, Any] = schema.setdefault("components", {}).setdefault(
|
|
66
|
+
"schemas", {}
|
|
67
|
+
)
|
|
68
|
+
components.setdefault(
|
|
69
|
+
"ProblemDetail", ProblemDetail.model_json_schema(mode="serialization")
|
|
70
|
+
)
|
|
71
|
+
paths: dict[str, dict[str, Any]] = schema.get("paths", {})
|
|
72
|
+
status = str(VALIDATION_ERROR.status)
|
|
73
|
+
for path_item in paths.values():
|
|
74
|
+
for operation in path_item.values():
|
|
75
|
+
responses: dict[str, Any] = operation.setdefault("responses", {})
|
|
76
|
+
if _is_fastapi_validation_response(responses.get(status)):
|
|
77
|
+
responses[status] = problem_response(VALIDATION_ERROR.status)
|
|
78
|
+
add_problem_responses(schema, rows)
|
|
79
|
+
if not any(
|
|
80
|
+
f"{_SCHEMA_REF_PREFIX}{name}" in json.dumps(paths)
|
|
81
|
+
for name in _FASTAPI_VALIDATION_SCHEMAS
|
|
82
|
+
):
|
|
83
|
+
for name in _FASTAPI_VALIDATION_SCHEMAS:
|
|
84
|
+
components.pop(name, None)
|
|
85
|
+
return schema
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _is_fastapi_validation_response(response: Any) -> bool:
|
|
89
|
+
return isinstance(
|
|
90
|
+
response, dict
|
|
91
|
+
) and '"#/components/schemas/HTTPValidationError"' in json.dumps(response)
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Render FastAPI and Starlette failures as RFC 9457 problem responses.
|
|
2
|
+
|
|
3
|
+
Register application exception mappings before installing the handlers so
|
|
4
|
+
Starlette dispatches them through its typed exception middleware. The fallback
|
|
5
|
+
handler also logs the current trace id.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
|
|
13
|
+
from fastapi import FastAPI, Request
|
|
14
|
+
from fastapi.exceptions import RequestValidationError
|
|
15
|
+
from fastapi.responses import JSONResponse
|
|
16
|
+
from rn_forge.web import (
|
|
17
|
+
NULL_FIELD_DETAIL,
|
|
18
|
+
PROBLEM_MEDIA_TYPE,
|
|
19
|
+
REQUIRED_FIELD_DETAIL,
|
|
20
|
+
VALIDATION_ERROR,
|
|
21
|
+
ProblemRegistry,
|
|
22
|
+
ProblemType,
|
|
23
|
+
current_trace_id,
|
|
24
|
+
default_registry,
|
|
25
|
+
field_error,
|
|
26
|
+
render_problem,
|
|
27
|
+
)
|
|
28
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
29
|
+
|
|
30
|
+
__all__ = ["Log", "register_problem_handlers"]
|
|
31
|
+
|
|
32
|
+
type Log = Callable[[str, Mapping[str, Any]], None]
|
|
33
|
+
"""The injected logging sink, called as ``log(event, context)``."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def register_problem_handlers(
|
|
37
|
+
app: FastAPI,
|
|
38
|
+
*,
|
|
39
|
+
registry: ProblemRegistry | None = None,
|
|
40
|
+
realm: str | None = None,
|
|
41
|
+
log: Log | None = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Render every error *app* produces as ``application/problem+json``.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
app: The application. Call this once while building it; nothing is
|
|
47
|
+
registered on import.
|
|
48
|
+
registry: The rows to render with. Defaults to a fresh
|
|
49
|
+
:func:`rn_forge.web.default_registry`. ``RequestValidationError`` is
|
|
50
|
+
registered on it against ``validation-error``/422 unless it already
|
|
51
|
+
has a row.
|
|
52
|
+
realm: The ``realm`` of the ``WWW-Authenticate`` challenge a 401
|
|
53
|
+
carries when the exception brought none of its own. A 403 never
|
|
54
|
+
carries one.
|
|
55
|
+
log: Called as ``log("problem.server_error", context)`` for every 5xx,
|
|
56
|
+
with the exception under ``"exc"``. The body carries no detail, so
|
|
57
|
+
this is the only place the cause goes.
|
|
58
|
+
"""
|
|
59
|
+
rows = registry if registry is not None else default_registry()
|
|
60
|
+
if RequestValidationError not in rows.rows():
|
|
61
|
+
rows.register(RequestValidationError, VALIDATION_ERROR)
|
|
62
|
+
|
|
63
|
+
def respond(
|
|
64
|
+
request: Request,
|
|
65
|
+
exc: Exception,
|
|
66
|
+
*,
|
|
67
|
+
problem: ProblemType | None = None,
|
|
68
|
+
detail: str | None = None,
|
|
69
|
+
extensions: Mapping[str, Any] | None = None,
|
|
70
|
+
headers: Mapping[str, str] | None = None,
|
|
71
|
+
) -> JSONResponse:
|
|
72
|
+
rendered = render_problem(
|
|
73
|
+
rows,
|
|
74
|
+
exc,
|
|
75
|
+
instance=request.url.path,
|
|
76
|
+
problem=problem,
|
|
77
|
+
detail=detail,
|
|
78
|
+
extensions=extensions,
|
|
79
|
+
headers=headers,
|
|
80
|
+
realm=realm,
|
|
81
|
+
)
|
|
82
|
+
if rendered.status >= 500 and log is not None:
|
|
83
|
+
log(
|
|
84
|
+
"problem.server_error",
|
|
85
|
+
{
|
|
86
|
+
"exc": exc,
|
|
87
|
+
"status": rendered.status,
|
|
88
|
+
"instance": rendered.problem.instance,
|
|
89
|
+
"trace_id": current_trace_id(),
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
return JSONResponse(
|
|
93
|
+
rendered.body,
|
|
94
|
+
status_code=rendered.status,
|
|
95
|
+
media_type=PROBLEM_MEDIA_TYPE,
|
|
96
|
+
headers=dict(rendered.headers),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
async def on_exception(request: Request, exc: Exception) -> JSONResponse:
|
|
100
|
+
return respond(request, exc)
|
|
101
|
+
|
|
102
|
+
async def on_http_exception(request: Request, exc: Exception) -> JSONResponse:
|
|
103
|
+
http = cast("StarletteHTTPException", exc)
|
|
104
|
+
row = rows.problem_for_status(http.status_code)
|
|
105
|
+
return respond(
|
|
106
|
+
request,
|
|
107
|
+
exc,
|
|
108
|
+
problem=row,
|
|
109
|
+
detail=http.detail if row.status < 500 else None,
|
|
110
|
+
headers=http.headers,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
async def on_validation_error(request: Request, exc: Exception) -> JSONResponse:
|
|
114
|
+
errors = cast("RequestValidationError", exc).errors()
|
|
115
|
+
return respond(
|
|
116
|
+
request,
|
|
117
|
+
exc,
|
|
118
|
+
detail=rows.problem_for(exc).title,
|
|
119
|
+
extensions={"errors": _validation_errors(errors)},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
for exc_type in rows.rows():
|
|
123
|
+
if issubclass(exc_type, Exception):
|
|
124
|
+
app.add_exception_handler(exc_type, on_exception)
|
|
125
|
+
app.add_exception_handler(StarletteHTTPException, on_http_exception)
|
|
126
|
+
app.add_exception_handler(RequestValidationError, on_validation_error)
|
|
127
|
+
app.add_exception_handler(Exception, on_exception)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _validation_errors(raw: Iterable[Mapping[str, Any]]) -> list[dict[str, str]]:
|
|
131
|
+
"""Map pydantic's ``errors()`` list to :func:`rn_forge.web.field_error` entries.
|
|
132
|
+
|
|
133
|
+
FastAPI's leading ``"body"`` location is dropped, and a missing field reads
|
|
134
|
+
:data:`rn_forge.web.REQUIRED_FIELD_DETAIL` as it does on DRF. An entry whose input is
|
|
135
|
+
``None`` reads :data:`rn_forge.web.NULL_FIELD_DETAIL`.
|
|
136
|
+
"""
|
|
137
|
+
return [
|
|
138
|
+
field_error(
|
|
139
|
+
_body_relative(entry.get("loc") or ()),
|
|
140
|
+
_detail(entry),
|
|
141
|
+
)
|
|
142
|
+
for entry in raw
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _detail(entry: Mapping[str, Any]) -> str:
|
|
147
|
+
if entry.get("type") == "missing":
|
|
148
|
+
return REQUIRED_FIELD_DETAIL
|
|
149
|
+
if "input" in entry and entry["input"] is None:
|
|
150
|
+
return NULL_FIELD_DETAIL
|
|
151
|
+
return str(entry.get("msg", ""))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _body_relative(loc: Sequence[Any]) -> Sequence[Any]:
|
|
155
|
+
return loc[1:] if loc and loc[0] == "body" else loc
|
|
File without changes
|