rn-forge-web 0.3.0.dev0__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.
Potentially problematic release.
This version of rn-forge-web might be problematic. Click here for more details.
- rn_forge/web/__init__.py +367 -0
- rn_forge/web/asgi.py +147 -0
- rn_forge/web/auth.py +115 -0
- rn_forge/web/concurrency.py +251 -0
- rn_forge/web/conformance/__init__.py +33 -0
- rn_forge/web/conformance/cases.py +1890 -0
- rn_forge/web/conformance/types.py +134 -0
- rn_forge/web/deprecation.py +37 -0
- rn_forge/web/exceptions.py +386 -0
- rn_forge/web/health.py +239 -0
- rn_forge/web/idempotency.py +296 -0
- rn_forge/web/merge_patch.py +98 -0
- rn_forge/web/models.py +24 -0
- rn_forge/web/openapi.py +176 -0
- rn_forge/web/operations.py +54 -0
- rn_forge/web/pagination.py +253 -0
- rn_forge/web/problem.py +593 -0
- rn_forge/web/py.typed +0 -0
- rn_forge/web/read_mask.py +121 -0
- rn_forge/web/security.py +97 -0
- rn_forge/web/soft_delete.py +31 -0
- rn_forge/web/tracing.py +53 -0
- rn_forge/web/transfer.py +408 -0
- rn_forge_web-0.3.0.dev0.dist-info/METADATA +139 -0
- rn_forge_web-0.3.0.dev0.dist-info/RECORD +27 -0
- rn_forge_web-0.3.0.dev0.dist-info/WHEEL +4 -0
- rn_forge_web-0.3.0.dev0.dist-info/licenses/LICENSE +21 -0
rn_forge/web/health.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Run and aggregate readiness checks.
|
|
2
|
+
|
|
3
|
+
Exceptions and timeouts become failed checks. A failed required check makes
|
|
4
|
+
the service unavailable; optional failures only degrade the aggregate status.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import inspect
|
|
11
|
+
from collections.abc import Awaitable, Callable, Collection, Mapping
|
|
12
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
13
|
+
from typing import Any, Final, Literal
|
|
14
|
+
|
|
15
|
+
from pydantic import ConfigDict, Field
|
|
16
|
+
from rn_forge.web.exceptions import WebError
|
|
17
|
+
from rn_forge.web.models import WireModel
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"LEGACY_LIVENESS_PATH",
|
|
21
|
+
"LIVENESS_PATH",
|
|
22
|
+
"READINESS_PATH",
|
|
23
|
+
"Check",
|
|
24
|
+
"CheckResult",
|
|
25
|
+
"CheckStatus",
|
|
26
|
+
"HealthReport",
|
|
27
|
+
"liveness_body",
|
|
28
|
+
"run_checks",
|
|
29
|
+
"run_checks_sync",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
LIVENESS_PATH: Final = "/livez"
|
|
33
|
+
"""Default liveness path (kubernetes.io "Kubernetes API health endpoints")."""
|
|
34
|
+
|
|
35
|
+
READINESS_PATH: Final = "/readyz"
|
|
36
|
+
"""Default readiness path."""
|
|
37
|
+
|
|
38
|
+
LEGACY_LIVENESS_PATH: Final = "/healthz"
|
|
39
|
+
"""Deprecated alias of :data:`LIVENESS_PATH`, kept for hosts still probing it."""
|
|
40
|
+
|
|
41
|
+
type CheckStatus = Literal["pass", "warn", "fail", "skipped"]
|
|
42
|
+
"""The four outcomes a single check may report."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CheckResult(WireModel):
|
|
46
|
+
"""One dependency's verdict."""
|
|
47
|
+
|
|
48
|
+
model_config = ConfigDict(frozen=True)
|
|
49
|
+
|
|
50
|
+
status: CheckStatus
|
|
51
|
+
reason: str | None = None
|
|
52
|
+
remediation: str | None = None
|
|
53
|
+
details: dict[str, Any] = Field(default_factory=dict[str, Any])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
type Check = Callable[[], CheckResult | bool | Awaitable[CheckResult | bool]]
|
|
57
|
+
"""A named check: a zero-argument callable, sync or async, returning a result or a bool."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class HealthReport(WireModel):
|
|
61
|
+
"""The aggregate of one readiness run.
|
|
62
|
+
|
|
63
|
+
``http_status`` is the transport status to serve; it is not part of the body.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
model_config = ConfigDict(frozen=True)
|
|
67
|
+
|
|
68
|
+
status: CheckStatus
|
|
69
|
+
checks: dict[str, CheckResult]
|
|
70
|
+
http_status: int = Field(exclude=True)
|
|
71
|
+
|
|
72
|
+
def as_body(self) -> dict[str, Any]:
|
|
73
|
+
"""Return ``status`` and ``checks`` without the transport status."""
|
|
74
|
+
return self.model_dump()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def liveness_body() -> dict[str, str]:
|
|
78
|
+
"""Return the liveness body: ``{"status": "pass"}``, served with 200.
|
|
79
|
+
|
|
80
|
+
Liveness runs no checks: it answers whether the process can serve a
|
|
81
|
+
request at all.
|
|
82
|
+
"""
|
|
83
|
+
return {"status": "pass"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_OK: Final = 200
|
|
87
|
+
_UNAVAILABLE: Final = 503
|
|
88
|
+
|
|
89
|
+
# Worst-wins ordering for the aggregate status. `skipped` is deliberately the
|
|
90
|
+
# weakest: a skipped check is recorded and reported but never degrades the
|
|
91
|
+
# overall verdict, because "not configured" is not "broken".
|
|
92
|
+
_SEVERITY: Final[dict[CheckStatus, int]] = {
|
|
93
|
+
"skipped": 0,
|
|
94
|
+
"pass": 1,
|
|
95
|
+
"warn": 2,
|
|
96
|
+
"fail": 3,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _coerce(value: CheckResult | bool) -> CheckResult:
|
|
101
|
+
"""Turn a check's return value into a :class:`CheckResult`."""
|
|
102
|
+
if isinstance(value, CheckResult):
|
|
103
|
+
return value
|
|
104
|
+
return CheckResult(status="pass" if value else "fail")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _failed(exc: BaseException) -> CheckResult:
|
|
108
|
+
"""Turn a raising check into a ``fail`` carrying its message."""
|
|
109
|
+
return CheckResult(status="fail", reason=str(exc) or type(exc).__name__)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _aggregate(
|
|
113
|
+
results: Mapping[str, CheckResult], required: Collection[str]
|
|
114
|
+
) -> HealthReport:
|
|
115
|
+
"""Combine per-check results into a report, applying the *required* rule."""
|
|
116
|
+
overall: CheckStatus = "pass"
|
|
117
|
+
for result in results.values():
|
|
118
|
+
if _SEVERITY[result.status] > _SEVERITY[overall]:
|
|
119
|
+
overall = result.status
|
|
120
|
+
if not results:
|
|
121
|
+
overall = "pass"
|
|
122
|
+
unavailable = any(
|
|
123
|
+
results[name].status == "fail" for name in required if name in results
|
|
124
|
+
)
|
|
125
|
+
return HealthReport(
|
|
126
|
+
status=overall,
|
|
127
|
+
checks=dict(results),
|
|
128
|
+
http_status=_UNAVAILABLE if unavailable else _OK,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
async def _run_one(check: Check) -> CheckResult:
|
|
133
|
+
"""Run one check, awaiting an awaitable result and never propagating.
|
|
134
|
+
|
|
135
|
+
A synchronous check runs in a worker thread, so blocking I/O in it neither
|
|
136
|
+
stalls the event loop nor serialises the other checks.
|
|
137
|
+
"""
|
|
138
|
+
try:
|
|
139
|
+
if inspect.iscoroutinefunction(check):
|
|
140
|
+
outcome = check()
|
|
141
|
+
else:
|
|
142
|
+
outcome = await asyncio.to_thread(check)
|
|
143
|
+
if inspect.isawaitable(outcome):
|
|
144
|
+
outcome = await outcome
|
|
145
|
+
return _coerce(outcome)
|
|
146
|
+
except Exception as exc: # noqa: BLE001 - a check must never crash the run
|
|
147
|
+
return _failed(exc)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def _run_bounded(check: Check, limit: float | None) -> CheckResult:
|
|
151
|
+
"""Run one check, failing it if it is still running after *limit* seconds."""
|
|
152
|
+
try:
|
|
153
|
+
# A check's own TimeoutError is already folded into a failed result by
|
|
154
|
+
# _run_one, so only deadline expiry reaches the handler below.
|
|
155
|
+
async with asyncio.timeout(limit):
|
|
156
|
+
return await _run_one(check)
|
|
157
|
+
except TimeoutError:
|
|
158
|
+
return CheckResult(status="fail", reason=f"timed out after {limit:g}s")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def run_checks(
|
|
162
|
+
checks: Mapping[str, Check],
|
|
163
|
+
*,
|
|
164
|
+
required: Collection[str] = (),
|
|
165
|
+
timeout: float | None = None,
|
|
166
|
+
) -> HealthReport:
|
|
167
|
+
"""Run *checks* concurrently and aggregate them.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
checks: Name → check. Sync and async checks may be mixed freely.
|
|
171
|
+
required: Names whose failure makes the service unavailable (503).
|
|
172
|
+
A name not present in *checks* is ignored.
|
|
173
|
+
timeout: Seconds each check may run before it is reported as
|
|
174
|
+
``fail``. ``None`` (the default) waits indefinitely.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
The aggregate report, including the HTTP status to serve.
|
|
178
|
+
"""
|
|
179
|
+
names = list(checks)
|
|
180
|
+
results = await asyncio.gather(
|
|
181
|
+
*(_run_bounded(checks[name], timeout) for name in names)
|
|
182
|
+
)
|
|
183
|
+
return _aggregate(dict(zip(names, results, strict=True)), required)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _run_one_sync(check: Check) -> CheckResult:
|
|
187
|
+
"""Run one synchronous check, mirroring :func:`_run_one`'s error handling.
|
|
188
|
+
|
|
189
|
+
Raises:
|
|
190
|
+
WebError: The check returned an awaitable.
|
|
191
|
+
"""
|
|
192
|
+
try:
|
|
193
|
+
outcome = check()
|
|
194
|
+
except Exception as exc: # noqa: BLE001 - a check must never crash the run
|
|
195
|
+
return _failed(exc)
|
|
196
|
+
if inspect.isawaitable(outcome):
|
|
197
|
+
if inspect.iscoroutine(outcome):
|
|
198
|
+
# Close it, or the "coroutine was never awaited" warning lands on
|
|
199
|
+
# an unrelated line whenever the GC gets round to it.
|
|
200
|
+
outcome.close()
|
|
201
|
+
raise WebError("Health check is asynchronous; use run_checks() instead")
|
|
202
|
+
return _coerce(outcome)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def run_checks_sync(
|
|
206
|
+
checks: Mapping[str, Check],
|
|
207
|
+
*,
|
|
208
|
+
required: Collection[str] = (),
|
|
209
|
+
timeout: float | None = None,
|
|
210
|
+
) -> HealthReport:
|
|
211
|
+
"""Run *checks* concurrently in a thread pool and aggregate them.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
checks: Name → check. Every check must be synchronous.
|
|
215
|
+
required: Names whose failure makes the service unavailable (503).
|
|
216
|
+
timeout: Seconds each check may run before it is reported as
|
|
217
|
+
``fail``. ``None`` (the default) waits indefinitely.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
The aggregate report, including the HTTP status to serve.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
WebError: A check returned an awaitable. This is raised rather than
|
|
224
|
+
swallowed into a ``fail``, because it is a wiring mistake in the
|
|
225
|
+
caller's code, not a sick dependency — and reporting it as a
|
|
226
|
+
failing check would hide it behind a red dependency.
|
|
227
|
+
"""
|
|
228
|
+
names = list(checks)
|
|
229
|
+
results: dict[str, CheckResult] = {}
|
|
230
|
+
with ThreadPoolExecutor(max_workers=len(names) or 1) as executor:
|
|
231
|
+
futures = {name: executor.submit(_run_one_sync, checks[name]) for name in names}
|
|
232
|
+
for name in names:
|
|
233
|
+
try:
|
|
234
|
+
results[name] = futures[name].result(timeout=timeout)
|
|
235
|
+
except TimeoutError:
|
|
236
|
+
results[name] = CheckResult(
|
|
237
|
+
status="fail", reason=f"timed out after {timeout:g}s"
|
|
238
|
+
)
|
|
239
|
+
return _aggregate(results, required)
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""Idempotency store protocols, request hashing, and in-memory test doubles.
|
|
2
|
+
|
|
3
|
+
Stores must claim keys atomically. Reusing a key with a different request hash
|
|
4
|
+
is an error (422); a claim still in flight is a distinct error (409); a
|
|
5
|
+
completed key replays its stored response.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any, Final, Protocol, runtime_checkable
|
|
15
|
+
|
|
16
|
+
from rn_forge.commons.lang.dataclasses import DataclassMixin
|
|
17
|
+
from rn_forge.web.exceptions import (
|
|
18
|
+
IdempotencyKeyInFlight,
|
|
19
|
+
IdempotencyKeyRequired,
|
|
20
|
+
IdempotencyKeyReuse,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"IDEMPOTENCY_KEY_HEADER",
|
|
25
|
+
"SAFE_METHODS",
|
|
26
|
+
"AsyncIdempotencyStore",
|
|
27
|
+
"IdempotencyStore",
|
|
28
|
+
"InMemoryAsyncIdempotencyStore",
|
|
29
|
+
"InMemoryIdempotencyStore",
|
|
30
|
+
"StoredResponse",
|
|
31
|
+
"check_idempotency_key",
|
|
32
|
+
"request_hash",
|
|
33
|
+
"run_idempotent",
|
|
34
|
+
"run_idempotent_async",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
IDEMPOTENCY_KEY_HEADER: Final = "Idempotency-Key"
|
|
38
|
+
"""The request header carrying the key (draft-ietf-httpapi-idempotency-key-header)."""
|
|
39
|
+
|
|
40
|
+
SAFE_METHODS: Final = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
|
|
41
|
+
"""Methods :func:`run_idempotent` bypasses the store for."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def check_idempotency_key(
|
|
45
|
+
value: str | None, *, header: str = IDEMPOTENCY_KEY_HEADER
|
|
46
|
+
) -> str:
|
|
47
|
+
"""Return *value*, the request's idempotency key, raising when it is absent.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
value: The header's value, or ``None`` when absent.
|
|
51
|
+
header: The header's name, for the error detail.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
IdempotencyKeyRequired: *value* is ``None`` or empty (400).
|
|
55
|
+
"""
|
|
56
|
+
if not value:
|
|
57
|
+
raise IdempotencyKeyRequired("{} is required", header, error_code=400)
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def request_hash(body: Any) -> str:
|
|
62
|
+
"""Return a SHA-256 over a canonical JSON encoding of *body*.
|
|
63
|
+
|
|
64
|
+
Canonical means ``sort_keys=True`` with no whitespace, so two bodies that
|
|
65
|
+
differ only in key order or formatting hash identically — otherwise a
|
|
66
|
+
client library that reorders JSON keys turns every retry into a 409.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
body: Any JSON-serializable value. ``None`` is a valid body and hashes
|
|
70
|
+
like any other.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
The hash as a lowercase hex digest.
|
|
74
|
+
"""
|
|
75
|
+
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), default=str)
|
|
76
|
+
return hashlib.sha256(canonical.encode()).hexdigest()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class StoredResponse(DataclassMixin):
|
|
81
|
+
"""A response held against an idempotency key."""
|
|
82
|
+
|
|
83
|
+
status: int
|
|
84
|
+
body: Mapping[str, Any]
|
|
85
|
+
replayed: bool = False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@runtime_checkable
|
|
89
|
+
class IdempotencyStore(Protocol):
|
|
90
|
+
"""The synchronous idempotency-key contract.
|
|
91
|
+
|
|
92
|
+
The claim made by :meth:`record_or_replay` must be atomic.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def record_or_replay(
|
|
96
|
+
self, *, scope: str, key: str, request_body: Any
|
|
97
|
+
) -> StoredResponse | None:
|
|
98
|
+
"""Claim *key* within *scope*, or return the response already stored.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
scope: An opaque namespace. A tenant-scoped consumer passes the
|
|
102
|
+
tenant id; an endpoint-scoped one passes the route name. Keys
|
|
103
|
+
in different scopes never collide.
|
|
104
|
+
key: The client's ``Idempotency-Key``.
|
|
105
|
+
request_body: The request body, hashed for reuse detection.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
``None`` on first sight — the caller executes and then calls
|
|
109
|
+
:meth:`complete`. The stored response (with ``replayed=True``) when
|
|
110
|
+
this key has already completed.
|
|
111
|
+
|
|
112
|
+
Raises:
|
|
113
|
+
IdempotencyKeyReuse: *key* was seen with a different body.
|
|
114
|
+
IdempotencyKeyInFlight: *key* was claimed and its original request
|
|
115
|
+
has not completed.
|
|
116
|
+
"""
|
|
117
|
+
...
|
|
118
|
+
|
|
119
|
+
def complete(
|
|
120
|
+
self, *, scope: str, key: str, status: int, response_body: Mapping[str, Any]
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Store the response produced for a claimed key."""
|
|
123
|
+
...
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@runtime_checkable
|
|
127
|
+
class AsyncIdempotencyStore(Protocol):
|
|
128
|
+
"""The async counterpart of :class:`IdempotencyStore`, with identical semantics."""
|
|
129
|
+
|
|
130
|
+
async def record_or_replay(
|
|
131
|
+
self, *, scope: str, key: str, request_body: Any
|
|
132
|
+
) -> StoredResponse | None:
|
|
133
|
+
"""See :meth:`IdempotencyStore.record_or_replay`."""
|
|
134
|
+
...
|
|
135
|
+
|
|
136
|
+
async def complete(
|
|
137
|
+
self, *, scope: str, key: str, status: int, response_body: Mapping[str, Any]
|
|
138
|
+
) -> None:
|
|
139
|
+
"""See :meth:`IdempotencyStore.complete`."""
|
|
140
|
+
...
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass
|
|
144
|
+
class _Entry:
|
|
145
|
+
"""One claimed key: the body hash, and the response once it exists."""
|
|
146
|
+
|
|
147
|
+
body_hash: str
|
|
148
|
+
response: StoredResponse | None = None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class InMemoryIdempotencyStore:
|
|
152
|
+
"""A dict-backed :class:`IdempotencyStore` for tests.
|
|
153
|
+
|
|
154
|
+
It holds everything forever and is not shared between processes, so it is a
|
|
155
|
+
test double, not a production store.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
def __init__(self) -> None:
|
|
159
|
+
self._entries: dict[tuple[str, str], _Entry] = {}
|
|
160
|
+
|
|
161
|
+
def record_or_replay(
|
|
162
|
+
self, *, scope: str, key: str, request_body: Any
|
|
163
|
+
) -> StoredResponse | None:
|
|
164
|
+
"""See :meth:`IdempotencyStore.record_or_replay`."""
|
|
165
|
+
digest = request_hash(request_body)
|
|
166
|
+
entry = self._entries.get((scope, key))
|
|
167
|
+
if entry is None:
|
|
168
|
+
self._entries[(scope, key)] = _Entry(body_hash=digest)
|
|
169
|
+
return None
|
|
170
|
+
if entry.body_hash != digest:
|
|
171
|
+
raise IdempotencyKeyReuse(
|
|
172
|
+
"Idempotency key {} was replayed with a different request body",
|
|
173
|
+
key,
|
|
174
|
+
error_code=422,
|
|
175
|
+
)
|
|
176
|
+
if entry.response is None:
|
|
177
|
+
raise IdempotencyKeyInFlight(
|
|
178
|
+
"Idempotency key {} is still processing its original request",
|
|
179
|
+
key,
|
|
180
|
+
error_code=409,
|
|
181
|
+
)
|
|
182
|
+
return StoredResponse(
|
|
183
|
+
status=entry.response.status, body=entry.response.body, replayed=True
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def complete(
|
|
187
|
+
self, *, scope: str, key: str, status: int, response_body: Mapping[str, Any]
|
|
188
|
+
) -> None:
|
|
189
|
+
"""See :meth:`IdempotencyStore.complete`."""
|
|
190
|
+
entry = self._entries.get((scope, key))
|
|
191
|
+
if entry is None:
|
|
192
|
+
entry = _Entry(body_hash=request_hash(None))
|
|
193
|
+
self._entries[(scope, key)] = entry
|
|
194
|
+
entry.response = StoredResponse(status=status, body=dict(response_body))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class InMemoryAsyncIdempotencyStore:
|
|
198
|
+
"""An async wrapper around the in-memory test store."""
|
|
199
|
+
|
|
200
|
+
def __init__(self) -> None:
|
|
201
|
+
self._inner = InMemoryIdempotencyStore()
|
|
202
|
+
|
|
203
|
+
async def record_or_replay(
|
|
204
|
+
self, *, scope: str, key: str, request_body: Any
|
|
205
|
+
) -> StoredResponse | None:
|
|
206
|
+
"""See :meth:`AsyncIdempotencyStore.record_or_replay`."""
|
|
207
|
+
return self._inner.record_or_replay(
|
|
208
|
+
scope=scope, key=key, request_body=request_body
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
async def complete(
|
|
212
|
+
self, *, scope: str, key: str, status: int, response_body: Mapping[str, Any]
|
|
213
|
+
) -> None:
|
|
214
|
+
"""See :meth:`AsyncIdempotencyStore.complete`."""
|
|
215
|
+
self._inner.complete(
|
|
216
|
+
scope=scope, key=key, status=status, response_body=response_body
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def run_idempotent(
|
|
221
|
+
store: IdempotencyStore,
|
|
222
|
+
*,
|
|
223
|
+
scope: str,
|
|
224
|
+
key: str | None,
|
|
225
|
+
method: str,
|
|
226
|
+
body: Any,
|
|
227
|
+
execute: Callable[[], tuple[int, Mapping[str, Any]]],
|
|
228
|
+
header: str = IDEMPOTENCY_KEY_HEADER,
|
|
229
|
+
) -> StoredResponse:
|
|
230
|
+
"""Run *execute* under the idempotency-key protocol.
|
|
231
|
+
|
|
232
|
+
A safe method (:data:`SAFE_METHODS`) bypasses the store entirely and just
|
|
233
|
+
runs *execute*. An unsafe method requires *key*, claims it, replays a
|
|
234
|
+
completed key's stored response, and stores what *execute* returns on
|
|
235
|
+
first sight.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
store: The idempotency store.
|
|
239
|
+
scope: An opaque namespace for the key — see
|
|
240
|
+
:meth:`IdempotencyStore.record_or_replay`.
|
|
241
|
+
key: The client's ``Idempotency-Key`` header value, or ``None``.
|
|
242
|
+
method: The request's HTTP method, any case.
|
|
243
|
+
body: The request body, hashed for reuse detection.
|
|
244
|
+
execute: Runs the handler, returning ``(status, response_body)``.
|
|
245
|
+
header: The header's name, for :exc:`IdempotencyKeyRequired`'s detail.
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
The response to send. ``replayed`` is ``True`` only for a stored
|
|
249
|
+
replay.
|
|
250
|
+
|
|
251
|
+
Raises:
|
|
252
|
+
IdempotencyKeyRequired: An unsafe method and *key* is absent (400).
|
|
253
|
+
IdempotencyKeyReuse: *key* was seen with a different body (422).
|
|
254
|
+
IdempotencyKeyInFlight: *key* is claimed and still in flight (409).
|
|
255
|
+
"""
|
|
256
|
+
if method.upper() in SAFE_METHODS:
|
|
257
|
+
status, response_body = execute()
|
|
258
|
+
return StoredResponse(status=status, body=dict(response_body))
|
|
259
|
+
|
|
260
|
+
resolved_key = check_idempotency_key(key, header=header)
|
|
261
|
+
stored = store.record_or_replay(scope=scope, key=resolved_key, request_body=body)
|
|
262
|
+
if stored is not None:
|
|
263
|
+
return stored
|
|
264
|
+
status, response_body = execute()
|
|
265
|
+
store.complete(
|
|
266
|
+
scope=scope, key=resolved_key, status=status, response_body=response_body
|
|
267
|
+
)
|
|
268
|
+
return StoredResponse(status=status, body=dict(response_body))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
async def run_idempotent_async(
|
|
272
|
+
store: AsyncIdempotencyStore,
|
|
273
|
+
*,
|
|
274
|
+
scope: str,
|
|
275
|
+
key: str | None,
|
|
276
|
+
method: str,
|
|
277
|
+
body: Any,
|
|
278
|
+
execute: Callable[[], Awaitable[tuple[int, Mapping[str, Any]]]],
|
|
279
|
+
header: str = IDEMPOTENCY_KEY_HEADER,
|
|
280
|
+
) -> StoredResponse:
|
|
281
|
+
"""See :func:`run_idempotent`; identical semantics over the async store and *execute*."""
|
|
282
|
+
if method.upper() in SAFE_METHODS:
|
|
283
|
+
status, response_body = await execute()
|
|
284
|
+
return StoredResponse(status=status, body=dict(response_body))
|
|
285
|
+
|
|
286
|
+
resolved_key = check_idempotency_key(key, header=header)
|
|
287
|
+
stored = await store.record_or_replay(
|
|
288
|
+
scope=scope, key=resolved_key, request_body=body
|
|
289
|
+
)
|
|
290
|
+
if stored is not None:
|
|
291
|
+
return stored
|
|
292
|
+
status, response_body = await execute()
|
|
293
|
+
await store.complete(
|
|
294
|
+
scope=scope, key=resolved_key, status=status, response_body=response_body
|
|
295
|
+
)
|
|
296
|
+
return StoredResponse(status=status, body=dict(response_body))
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""RFC 7396 JSON Merge Patch.
|
|
2
|
+
|
|
3
|
+
Hand-rolled: no clearly maintained package implements RFC 7396, and the algorithm is a few lines.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
from rn_forge.web.exceptions import InvalidMergePatch
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"MERGE_PATCH_MEDIA_TYPE",
|
|
15
|
+
"JsonValue",
|
|
16
|
+
"apply_merge_patch",
|
|
17
|
+
"merge_representation",
|
|
18
|
+
"require_patch_object",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
MERGE_PATCH_MEDIA_TYPE: Final = "application/merge-patch+json"
|
|
22
|
+
"""The media type of a JSON Merge Patch body."""
|
|
23
|
+
|
|
24
|
+
type JsonValue = (
|
|
25
|
+
None | bool | int | float | str | list[JsonValue] | dict[str, JsonValue]
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def apply_merge_patch(target: JsonValue, patch: JsonValue) -> JsonValue:
|
|
30
|
+
"""Apply *patch* to *target* as RFC 7396 section 2 specifies.
|
|
31
|
+
|
|
32
|
+
A non-object *patch* replaces *target*. An object *patch* merges into *target*
|
|
33
|
+
(an empty object when *target* is not one): a ``null`` member removes the
|
|
34
|
+
member, any other member is merged recursively, and arrays are replaced whole.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
target: The document to patch. Not modified.
|
|
38
|
+
patch: The merge patch. Not modified.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
The patched document, sharing no mutable state with either argument.
|
|
42
|
+
"""
|
|
43
|
+
if not isinstance(patch, dict):
|
|
44
|
+
return _copy(patch)
|
|
45
|
+
result: dict[str, JsonValue] = (
|
|
46
|
+
{key: _copy(value) for key, value in target.items()}
|
|
47
|
+
if isinstance(target, dict)
|
|
48
|
+
else {}
|
|
49
|
+
)
|
|
50
|
+
for key, value in patch.items():
|
|
51
|
+
if value is None:
|
|
52
|
+
result.pop(key, None)
|
|
53
|
+
else:
|
|
54
|
+
result[key] = apply_merge_patch(result.get(key), value)
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def merge_representation(
|
|
59
|
+
current: Mapping[str, JsonValue], patch: Mapping[str, JsonValue]
|
|
60
|
+
) -> dict[str, JsonValue]:
|
|
61
|
+
"""Merge *patch* into the resource representation *current*.
|
|
62
|
+
|
|
63
|
+
At the top level a ``null`` member sets that field to ``None`` and keeps it.
|
|
64
|
+
Every other member, and everything below the top level, follows
|
|
65
|
+
:func:`apply_merge_patch`.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
current: The resource's current representation. Not modified.
|
|
69
|
+
patch: The merge patch object. Not modified.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
The merged representation.
|
|
73
|
+
"""
|
|
74
|
+
merged = {key: _copy(value) for key, value in current.items()}
|
|
75
|
+
for key, value in patch.items():
|
|
76
|
+
merged[key] = (
|
|
77
|
+
None if value is None else apply_merge_patch(merged.get(key), value)
|
|
78
|
+
)
|
|
79
|
+
return merged
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def require_patch_object(body: object) -> dict[str, JsonValue]:
|
|
83
|
+
"""Return *body* when it is a JSON object.
|
|
84
|
+
|
|
85
|
+
Raises:
|
|
86
|
+
InvalidMergePatch: *body* is not a JSON object.
|
|
87
|
+
"""
|
|
88
|
+
if not isinstance(body, dict):
|
|
89
|
+
raise InvalidMergePatch
|
|
90
|
+
return body # pyright: ignore[reportUnknownVariableType]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _copy(value: JsonValue) -> JsonValue:
|
|
94
|
+
if isinstance(value, dict):
|
|
95
|
+
return {key: _copy(item) for key, item in value.items()}
|
|
96
|
+
if isinstance(value, list):
|
|
97
|
+
return [_copy(item) for item in value]
|
|
98
|
+
return value
|
rn_forge/web/models.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""The pydantic base of every model that crosses the wire."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict
|
|
6
|
+
from pydantic.alias_generators import to_camel
|
|
7
|
+
|
|
8
|
+
__all__ = ["WireModel"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class WireModel(BaseModel):
|
|
12
|
+
"""Base for every model that crosses the wire: camelCase out, either spelling in.
|
|
13
|
+
|
|
14
|
+
Serialization uses aliases by default; validation accepts aliases and
|
|
15
|
+
Python field names.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(
|
|
19
|
+
alias_generator=to_camel,
|
|
20
|
+
validate_by_alias=True,
|
|
21
|
+
validate_by_name=True,
|
|
22
|
+
serialize_by_alias=True,
|
|
23
|
+
from_attributes=True,
|
|
24
|
+
)
|