python-wrap 0.2.1__py3-none-any.whl → 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.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/web.py ADDED
@@ -0,0 +1,723 @@
1
+ """Server-side web helpers: Idempotency-Key middleware and rate-limit responses.
2
+
3
+ * `IdempotencyMiddleware` (ASGI) and `WsgiIdempotencyMiddleware` (WSGI) make unsafe
4
+ requests such as POST safe to retry, following the Stripe convention and the
5
+ IETF ``Idempotency-Key`` header draft. Neither imports a web framework.
6
+ * `ratelimit_headers`, `too_many_requests` and `problem_response` build
7
+ ``RateLimit-*`` / ``Retry-After`` headers and RFC 9457 ``application/problem+json``
8
+ bodies from this package's exceptions; small lazy glue functions plug them into
9
+ FastAPI/Starlette, Flask and Django.
10
+
11
+ Idempotency keys MUST be scoped by authenticated identity (see the ``scope`` argument);
12
+ otherwise two users who happen to send the same key would share responses.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import hashlib
19
+ import io
20
+ import json
21
+ import math
22
+ import uuid
23
+ from collections.abc import Awaitable, Callable, Iterable
24
+ from typing import Any
25
+
26
+ from python_wrap._runtime import seconds
27
+ from python_wrap.coordination import LocalLease
28
+ from python_wrap.errors import BulkheadFull, CircuitOpenError, RateLimitExceeded
29
+ from python_wrap.idempotency import MemoryResultStore
30
+
31
+ __all__ = [
32
+ "IdempotencyMiddleware",
33
+ "WsgiIdempotencyMiddleware",
34
+ "django_response",
35
+ "fastapi_exception_handlers",
36
+ "flask_register_error_handlers",
37
+ "problem_response",
38
+ "ratelimit_headers",
39
+ "too_many_requests",
40
+ ]
41
+
42
+ _PROBLEM = "application/problem+json"
43
+ _MAX_KEY_LENGTH = 255
44
+ _PREFIX = "python-wrap:http-idem:"
45
+ # Response headers that are never stored for replay: cookies belong to the client that
46
+ # triggered the first execution (replaying them could hand one client's session to
47
+ # another), and hop-by-hop headers describe a single connection, not the response.
48
+ _UNSTORED_HEADERS = frozenset(
49
+ {
50
+ "set-cookie",
51
+ "set-cookie2",
52
+ "connection",
53
+ "keep-alive",
54
+ "proxy-authenticate",
55
+ "proxy-connection",
56
+ "te",
57
+ "trailer",
58
+ "transfer-encoding",
59
+ "upgrade",
60
+ "idempotent-replayed",
61
+ }
62
+ )
63
+ _READ_CHUNK = 65_536
64
+
65
+
66
+ def _credentials_digest(source: Any) -> str:
67
+ """Default key partition: a digest of the request's Authorization and Cookie headers.
68
+
69
+ Without an explicit ``scope=`` two clients that happen to send the same
70
+ Idempotency-Key must never receive each other's stored response, so keys are
71
+ partitioned by the credentials the request carried (anonymous requests share one
72
+ partition). Pass ``scope=`` to partition by an authenticated tenant/user id instead,
73
+ which also keeps a key stable across token refreshes.
74
+ """
75
+ values: list[str] = []
76
+ if isinstance(source, dict) and "headers" in source and "type" in source: # ASGI scope
77
+ found = {
78
+ bytes(name).lower(): bytes(value)
79
+ for name, value in source.get("headers") or ()
80
+ if bytes(name).lower() in (b"authorization", b"cookie")
81
+ }
82
+ values = [found.get(b"authorization", b"").decode("latin-1"),
83
+ found.get(b"cookie", b"").decode("latin-1")] # fmt: skip
84
+ elif isinstance(source, dict): # WSGI environ
85
+ values = [str(source.get("HTTP_AUTHORIZATION", "")), str(source.get("HTTP_COOKIE", ""))]
86
+ if not any(values):
87
+ return ""
88
+ return hashlib.sha256("\0".join(values).encode("utf-8", "replace")).hexdigest()
89
+
90
+
91
+ # --------------------------------------------------------------------------- problems
92
+
93
+
94
+ def _problem_body(status: int, title: str, detail: str | None, type_: str = "about:blank") -> bytes:
95
+ doc: dict[str, Any] = {"type": type_, "title": title, "status": status}
96
+ if detail:
97
+ doc["detail"] = detail
98
+ return json.dumps(doc).encode("utf-8")
99
+
100
+
101
+ def _problem(
102
+ status: int, title: str, detail: str | None = None, extra: dict[str, str] | None = None
103
+ ) -> tuple[int, list[tuple[str, str]], bytes]:
104
+ body = _problem_body(status, title, detail)
105
+ headers = [("Content-Type", _PROBLEM), ("Content-Length", str(len(body)))]
106
+ headers.extend((extra or {}).items())
107
+ return status, headers, body
108
+
109
+
110
+ # --------------------------------------------------------------------------- shared core
111
+
112
+
113
+ class _Core:
114
+ """Request-independent idempotency logic shared by the ASGI and WSGI wrappers."""
115
+
116
+ def __init__(
117
+ self,
118
+ *,
119
+ store: Any,
120
+ backend: Any,
121
+ ttl: float | str,
122
+ lease_ttl: float | str,
123
+ methods: Iterable[str],
124
+ header: str,
125
+ required: bool,
126
+ scope: Callable[[Any], str] | None,
127
+ max_body: int,
128
+ ) -> None:
129
+ self.ttl, self.lease_ttl = seconds(ttl), seconds(lease_ttl)
130
+ if isinstance(max_body, bool) or not isinstance(max_body, int) or max_body < 0:
131
+ raise ValueError("max_body must be a non-negative integer")
132
+ if getattr(store, "fail_open", False):
133
+ raise ValueError("idempotency requires a result store with fail_open=False")
134
+ self.store = MemoryResultStore() if store is None else store
135
+ self.backend = LocalLease() if backend is None else backend
136
+ self.methods = frozenset(m.upper() for m in methods)
137
+ self.header, self.required = header, required
138
+ self.scope, self.max_body = scope, max_body
139
+
140
+ def storage_key(self, source: Any, method: str, path: str, key: str) -> str:
141
+ who = self.scope(source) if self.scope is not None else _credentials_digest(source)
142
+ raw = "\0".join((str(who), method, path, key))
143
+ return _PREFIX + hashlib.sha256(raw.encode("utf-8")).hexdigest()
144
+
145
+ @staticmethod
146
+ def fingerprint(body: bytes, query: str = "") -> str:
147
+ """Digest of everything that makes two requests "the same" besides the key.
148
+
149
+ The query string is part of it, so the same key and body sent to
150
+ ``/pay?amount=1`` and ``/pay?amount=1000`` is a mismatch (422), not a replay.
151
+ """
152
+ digest = hashlib.sha256()
153
+ digest.update(len(query).to_bytes(8, "big"))
154
+ digest.update(query.encode("latin-1", "replace"))
155
+ digest.update(body)
156
+ return digest.hexdigest()
157
+
158
+ def check_key(self, key: str | None) -> tuple[int, list[tuple[str, str]], bytes] | None:
159
+ if key is None:
160
+ if self.required:
161
+ return _problem(400, "Idempotency-Key header is required")
162
+ return None
163
+ if not key.strip() or len(key) > _MAX_KEY_LENGTH:
164
+ return _problem(400, "Invalid Idempotency-Key header")
165
+ return None
166
+
167
+ @staticmethod
168
+ def too_large() -> tuple[int, list[tuple[str, str]], bytes]:
169
+ return _problem(413, "Request body too large")
170
+
171
+ def lookup(
172
+ self, skey: str, fp: str
173
+ ) -> tuple[int, list[tuple[str, str]], bytes] | dict[str, Any] | None:
174
+ """Return a stored record to replay, a 422 problem, or None when unseen."""
175
+ found = self.store.get(skey)
176
+ if found is None:
177
+ return None
178
+ if found.get("fp") != fp:
179
+ return _problem(
180
+ 422,
181
+ "Idempotency-Key reused with a different request",
182
+ "this key was already used with a different request body",
183
+ )
184
+ return found # type: ignore[no-any-return]
185
+
186
+ @staticmethod
187
+ def conflict() -> tuple[int, list[tuple[str, str]], bytes]:
188
+ return _problem(
189
+ 409,
190
+ "A request with this Idempotency-Key is already in progress",
191
+ None,
192
+ {"Retry-After": "1"},
193
+ )
194
+
195
+ def record(self, fp: str, status: int, headers: list[tuple[str, str]], body: bytes) -> Any:
196
+ return {
197
+ "fp": fp,
198
+ "status": status,
199
+ "headers": [[k, v] for k, v in headers if k.lower() not in _UNSTORED_HEADERS],
200
+ "body": body.decode("latin-1"),
201
+ }
202
+
203
+ def should_store(self, status: int, size: int) -> bool:
204
+ return status < 500 and size <= self.max_body
205
+
206
+ def save(self, skey: str, value: Any) -> None:
207
+ self.store.set(skey, value, self.ttl)
208
+
209
+ @staticmethod
210
+ def replay_parts(found: dict[str, Any]) -> tuple[int, list[tuple[str, str]], bytes]:
211
+ headers = [
212
+ (str(k), str(v)) for k, v in found["headers"] if str(k).lower() not in _UNSTORED_HEADERS
213
+ ]
214
+ headers.append(("Idempotent-Replayed", "true"))
215
+ return int(found["status"]), headers, str(found["body"]).encode("latin-1")
216
+
217
+
218
+ # --------------------------------------------------------------------------- ASGI
219
+
220
+
221
+ class IdempotencyMiddleware:
222
+ """Pure ASGI middleware giving unsafe HTTP methods Idempotency-Key semantics.
223
+
224
+ For a request with the header and a matching method the response of the first
225
+ execution is stored and replayed (with ``Idempotent-Replayed: true``) for later
226
+ requests with the same key, the same query string and the same body. The same key
227
+ with a different body or query gets 422; a concurrent in-flight duplicate gets 409
228
+ with ``Retry-After: 1``. Responses with status >= 500 are not stored so clients can
229
+ retry. ``Set-Cookie`` and hop-by-hop headers are never stored or replayed. Requests
230
+ without the header stream through untouched.
231
+
232
+ Args:
233
+ app: The wrapped ASGI application.
234
+ store: Result store with ``get/set(key, value, ttl)/delete``; values are plain
235
+ JSON-compatible dicts. Defaults to an in-process `MemoryResultStore`.
236
+ backend: Lease backend (``acquire/release``); defaults to a `LocalLease`. Use a
237
+ shared one (for example `RedisLock`) together with a shared store when
238
+ running several processes.
239
+ ttl: How long responses are retained.
240
+ lease_ttl: In-flight lease lifetime; must exceed the slowest handler.
241
+ methods: HTTP methods the header applies to.
242
+ header: Request header carrying the key.
243
+ required: Reject matching requests without the header with 400.
244
+ scope: ``callable(asgi_scope) -> str`` partitioning keys, e.g. by tenant/user.
245
+ By default keys are partitioned by a digest of the request's
246
+ ``Authorization`` and ``Cookie`` headers, so clients never share entries.
247
+ Keys must be scoped by authenticated identity.
248
+ max_body: Largest request body buffered for fingerprinting; larger gets 413.
249
+
250
+ Example:
251
+ >>> async def app(scope, receive, send): ...
252
+ >>> wrapped = IdempotencyMiddleware(app, ttl="1h")
253
+ """
254
+
255
+ def __init__(
256
+ self,
257
+ app: Any,
258
+ *,
259
+ store: Any = None,
260
+ backend: Any = None,
261
+ ttl: float | str = "1d",
262
+ lease_ttl: float | str = 60,
263
+ methods: Iterable[str] = ("POST", "PATCH"),
264
+ header: str = "Idempotency-Key",
265
+ required: bool = False,
266
+ scope: Callable[[Any], str] | None = None,
267
+ max_body: int = 1_000_000,
268
+ ) -> None:
269
+ self.app = app
270
+ self._core = _Core(
271
+ store=store,
272
+ backend=backend,
273
+ ttl=ttl,
274
+ lease_ttl=lease_ttl,
275
+ methods=methods,
276
+ header=header,
277
+ required=required,
278
+ scope=scope,
279
+ max_body=max_body,
280
+ )
281
+ self._header = header.lower().encode("latin-1")
282
+
283
+ async def _respond(
284
+ self,
285
+ send: Callable[[dict[str, Any]], Awaitable[None]],
286
+ parts: tuple[int, list[tuple[str, str]], bytes],
287
+ ) -> None:
288
+ status, headers, body = parts
289
+ out = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers]
290
+ out = [(k, v) for k, v in out if k != b"content-length"]
291
+ out.append((b"content-length", str(len(body)).encode()))
292
+ await send({"type": "http.response.start", "status": status, "headers": out})
293
+ await send({"type": "http.response.body", "body": body})
294
+
295
+ async def __call__(
296
+ self,
297
+ scope: dict[str, Any],
298
+ receive: Callable[[], Awaitable[dict[str, Any]]],
299
+ send: Callable[[dict[str, Any]], Awaitable[None]],
300
+ ) -> None:
301
+ core = self._core
302
+ method = str(scope.get("method", "")).upper()
303
+ if scope.get("type") != "http" or method not in core.methods:
304
+ await self.app(scope, receive, send)
305
+ return
306
+ raw_headers = scope.get("headers", [])
307
+ key: str | None = None
308
+ length: int | None = None
309
+ for name, value in raw_headers:
310
+ if name.lower() == self._header:
311
+ key = value.decode("latin-1")
312
+ elif name.lower() == b"content-length":
313
+ try:
314
+ length = int(value)
315
+ except ValueError:
316
+ length = None
317
+ problem = core.check_key(key)
318
+ if problem is not None:
319
+ await self._respond(send, problem)
320
+ return
321
+ if key is None:
322
+ await self.app(scope, receive, send)
323
+ return
324
+ if length is not None and length > core.max_body:
325
+ await self._respond(send, core.too_large())
326
+ return
327
+
328
+ chunks: list[bytes] = []
329
+ size = 0
330
+ more = True
331
+ while more:
332
+ message = await receive()
333
+ if message["type"] == "http.disconnect":
334
+ return
335
+ part = message.get("body", b"")
336
+ size += len(part)
337
+ if size > core.max_body:
338
+ await self._respond(send, core.too_large())
339
+ return
340
+ chunks.append(part)
341
+ more = bool(message.get("more_body", False))
342
+ body = b"".join(chunks)
343
+ query = bytes(scope.get("query_string", b"")).decode("latin-1")
344
+ fp = core.fingerprint(body, query)
345
+ skey = core.storage_key(scope, method, str(scope.get("path", "")), key)
346
+
347
+ async def run(fn: Callable[..., Any], *args: Any) -> Any:
348
+ return await asyncio.to_thread(fn, *args)
349
+
350
+ seen = await run(core.lookup, skey, fp)
351
+ if seen is not None:
352
+ parts = seen if isinstance(seen, tuple) else core.replay_parts(seen)
353
+ await self._respond(send, parts)
354
+ return
355
+ token = uuid.uuid4().hex
356
+ if not await run(core.backend.acquire, skey, token, core.lease_ttl):
357
+ await self._respond(send, core.conflict())
358
+ return
359
+ try:
360
+ seen = await run(core.lookup, skey, fp)
361
+ if seen is not None:
362
+ parts = seen if isinstance(seen, tuple) else core.replay_parts(seen)
363
+ await self._respond(send, parts)
364
+ return
365
+ replayed = False
366
+
367
+ async def replay_receive() -> dict[str, Any]:
368
+ nonlocal replayed
369
+ if not replayed:
370
+ replayed = True
371
+ return {"type": "http.request", "body": body, "more_body": False}
372
+ return await receive()
373
+
374
+ status = 0
375
+ headers: list[tuple[str, str]] = []
376
+ captured: list[bytes] = []
377
+ captured_size = 0
378
+
379
+ async def capture_send(message: dict[str, Any]) -> None:
380
+ nonlocal status, headers, captured_size
381
+ if message["type"] == "http.response.start":
382
+ status = int(message["status"])
383
+ headers = [
384
+ (k.decode("latin-1"), v.decode("latin-1"))
385
+ for k, v in message.get("headers", [])
386
+ ]
387
+ elif message["type"] == "http.response.body":
388
+ part = bytes(message.get("body", b""))
389
+ captured_size += len(part)
390
+ if captured_size <= core.max_body:
391
+ captured.append(part)
392
+ await send(message)
393
+
394
+ await self.app(scope, replay_receive, capture_send)
395
+ if status and core.should_store(status, captured_size):
396
+ value = core.record(fp, status, headers, b"".join(captured))
397
+ await run(core.save, skey, value)
398
+ finally:
399
+ await asyncio.shield(run(core.backend.release, skey, token))
400
+
401
+
402
+ # --------------------------------------------------------------------------- WSGI
403
+
404
+
405
+ class WsgiIdempotencyMiddleware:
406
+ """WSGI counterpart of `IdempotencyMiddleware` with identical semantics.
407
+
408
+ Works with Flask and Django's WSGI entry point. Responses of idempotent requests are
409
+ buffered (they are stored anyway); requests without the header are untouched. A
410
+ chunked request body (no ``Content-Length``) is read, up to ``max_body``, when the
411
+ server marks the input as terminated (``wsgi.input_terminated``) or the request
412
+ declares ``Transfer-Encoding: chunked``.
413
+
414
+ Args:
415
+ app: The wrapped WSGI application.
416
+ store: Result store; defaults to an in-process `MemoryResultStore`.
417
+ backend: Lease backend; defaults to a `LocalLease`.
418
+ ttl: How long responses are retained.
419
+ lease_ttl: In-flight lease lifetime; must exceed the slowest handler.
420
+ methods: HTTP methods the header applies to.
421
+ header: Request header carrying the key.
422
+ required: Reject matching requests without the header with 400.
423
+ scope: ``callable(environ) -> str`` partitioning keys by tenant/user. By
424
+ default keys are partitioned by the ``Authorization``/``Cookie`` headers.
425
+ max_body: Largest request body buffered; larger gets 413.
426
+
427
+ Example:
428
+ >>> def app(environ, start_response): ...
429
+ >>> wrapped = WsgiIdempotencyMiddleware(app)
430
+ """
431
+
432
+ def __init__(
433
+ self,
434
+ app: Any,
435
+ *,
436
+ store: Any = None,
437
+ backend: Any = None,
438
+ ttl: float | str = "1d",
439
+ lease_ttl: float | str = 60,
440
+ methods: Iterable[str] = ("POST", "PATCH"),
441
+ header: str = "Idempotency-Key",
442
+ required: bool = False,
443
+ scope: Callable[[Any], str] | None = None,
444
+ max_body: int = 1_000_000,
445
+ ) -> None:
446
+ self.app = app
447
+ self._core = _Core(
448
+ store=store,
449
+ backend=backend,
450
+ ttl=ttl,
451
+ lease_ttl=lease_ttl,
452
+ methods=methods,
453
+ header=header,
454
+ required=required,
455
+ scope=scope,
456
+ max_body=max_body,
457
+ )
458
+ self._environ_key = "HTTP_" + header.upper().replace("-", "_")
459
+
460
+ @staticmethod
461
+ def _respond(
462
+ start_response: Callable[..., Any], parts: tuple[int, list[tuple[str, str]], bytes]
463
+ ) -> list[bytes]:
464
+ status, headers, body = parts
465
+ from http import HTTPStatus
466
+
467
+ try:
468
+ phrase = HTTPStatus(status).phrase
469
+ except ValueError:
470
+ phrase = "Unknown"
471
+ out = [(k, v) for k, v in headers if k.lower() != "content-length"]
472
+ out.append(("Content-Length", str(len(body))))
473
+ start_response(f"{status} {phrase}", out)
474
+ return [body]
475
+
476
+ @staticmethod
477
+ def _read_body(environ: dict[str, Any], limit: int) -> bytes | None:
478
+ """Read the request body, never more than ``limit`` bytes; None when larger.
479
+
480
+ A body without ``Content-Length`` (chunked transfer encoding) is read to its end
481
+ when the server marks the input as terminated (``wsgi.input_terminated``, as
482
+ Gunicorn, Werkzeug and mod_wsgi do) or the request is chunked. Otherwise reading
483
+ past ``Content-Length`` could block, so the body is taken as empty, as WSGI
484
+ requires.
485
+ """
486
+ stream = environ.get("wsgi.input")
487
+ raw_length = str(environ.get("CONTENT_LENGTH") or "").strip()
488
+ if raw_length:
489
+ try:
490
+ length = int(raw_length)
491
+ except ValueError:
492
+ length = -1
493
+ if length < 0:
494
+ length = 0
495
+ if length > limit:
496
+ return None
497
+ return bytes(stream.read(length)) if stream is not None and length > 0 else b""
498
+ chunked = "chunked" in str(environ.get("HTTP_TRANSFER_ENCODING", "")).lower()
499
+ if stream is None or not (environ.get("wsgi.input_terminated") or chunked):
500
+ return b""
501
+ parts: list[bytes] = []
502
+ size = 0
503
+ while True:
504
+ part = bytes(stream.read(min(_READ_CHUNK, limit + 1 - size)))
505
+ if not part:
506
+ return b"".join(parts)
507
+ size += len(part)
508
+ if size > limit:
509
+ return None
510
+ parts.append(part)
511
+
512
+ def __call__(
513
+ self, environ: dict[str, Any], start_response: Callable[..., Any]
514
+ ) -> Iterable[bytes]:
515
+ core = self._core
516
+ method = str(environ.get("REQUEST_METHOD", "")).upper()
517
+ if method not in core.methods:
518
+ return self.app(environ, start_response) # type: ignore[no-any-return]
519
+ key = environ.get(self._environ_key)
520
+ key = None if key is None else str(key)
521
+ problem = core.check_key(key)
522
+ if problem is not None:
523
+ return self._respond(start_response, problem)
524
+ if key is None:
525
+ return self.app(environ, start_response) # type: ignore[no-any-return]
526
+ body = self._read_body(environ, core.max_body)
527
+ if body is None:
528
+ return self._respond(start_response, core.too_large())
529
+ fp = core.fingerprint(body, str(environ.get("QUERY_STRING", "")))
530
+ path = str(environ.get("SCRIPT_NAME", "")) + str(environ.get("PATH_INFO", ""))
531
+ skey = core.storage_key(environ, method, path, key)
532
+
533
+ seen = core.lookup(skey, fp)
534
+ if seen is not None:
535
+ parts = seen if isinstance(seen, tuple) else core.replay_parts(seen)
536
+ return self._respond(start_response, parts)
537
+ token = uuid.uuid4().hex
538
+ if not core.backend.acquire(skey, token, core.lease_ttl):
539
+ return self._respond(start_response, core.conflict())
540
+ try:
541
+ seen = core.lookup(skey, fp)
542
+ if seen is not None:
543
+ parts = seen if isinstance(seen, tuple) else core.replay_parts(seen)
544
+ return self._respond(start_response, parts)
545
+ environ["wsgi.input"] = io.BytesIO(body)
546
+ environ["CONTENT_LENGTH"] = str(len(body))
547
+ state: dict[str, Any] = {"status": "", "headers": []}
548
+ written: list[bytes] = []
549
+
550
+ def capture_start(
551
+ status: str, headers: list[tuple[str, str]], exc_info: Any = None
552
+ ) -> Callable[[bytes], None]:
553
+ state["status"], state["headers"] = status, list(headers)
554
+ return written.append
555
+
556
+ result = self.app(environ, capture_start)
557
+ chunks = list(written)
558
+ try:
559
+ chunks.extend(result)
560
+ finally:
561
+ close = getattr(result, "close", None)
562
+ if close is not None:
563
+ close()
564
+ payload = b"".join(chunks)
565
+ code = int(str(state["status"]).split(" ", 1)[0])
566
+ if core.should_store(code, len(payload)):
567
+ core.save(skey, core.record(fp, code, state["headers"], payload))
568
+ start_response(state["status"], state["headers"])
569
+ return [payload]
570
+ finally:
571
+ core.backend.release(skey, token)
572
+
573
+
574
+ # --------------------------------------------------------------------------- rate limits
575
+
576
+
577
+ def ratelimit_headers(
578
+ *, limit: int, remaining: int, reset: float, policy: str | None = None
579
+ ) -> dict[str, str]:
580
+ """Build IETF ``RateLimit-*`` response headers.
581
+
582
+ Args:
583
+ limit: Requests allowed in the window.
584
+ remaining: Requests left (clamped to >= 0).
585
+ reset: Seconds until the window resets (rounded up, clamped to >= 0).
586
+ policy: Optional ``RateLimit-Policy`` value such as ``"100;w=60"``.
587
+
588
+ Returns:
589
+ A header dict.
590
+
591
+ Example:
592
+ >>> ratelimit_headers(limit=100, remaining=7, reset=1.2)["RateLimit-Reset"]
593
+ '2'
594
+ """
595
+ headers = {
596
+ "RateLimit-Limit": str(int(limit)),
597
+ "RateLimit-Remaining": str(max(0, int(remaining))),
598
+ "RateLimit-Reset": str(max(0, math.ceil(reset))),
599
+ }
600
+ if policy is not None:
601
+ headers["RateLimit-Policy"] = policy
602
+ return headers
603
+
604
+
605
+ def _retry_seconds(value: float) -> int:
606
+ return max(1, math.ceil(value))
607
+
608
+
609
+ def too_many_requests(
610
+ exc_or_retry_after: RateLimitExceeded | float,
611
+ *,
612
+ limit: int | None = None,
613
+ detail: str | None = None,
614
+ ) -> tuple[int, dict[str, str], bytes]:
615
+ """Build a 429 response: ``Retry-After``, optional ``RateLimit-*`` and problem+json.
616
+
617
+ Args:
618
+ exc_or_retry_after: A `RateLimitExceeded` or a retry delay in seconds.
619
+ limit: When given, ``RateLimit-Limit/Remaining/Reset`` headers are included.
620
+ detail: Problem detail text; defaults to the exception message.
621
+
622
+ Returns:
623
+ ``(status, headers, body)``.
624
+
625
+ Example:
626
+ >>> too_many_requests(2.5)[0]
627
+ 429
628
+ """
629
+ retry = float(
630
+ exc_or_retry_after.retry_after
631
+ if isinstance(exc_or_retry_after, RateLimitExceeded)
632
+ else exc_or_retry_after
633
+ )
634
+ if detail is None and isinstance(exc_or_retry_after, Exception):
635
+ detail = str(exc_or_retry_after) or None
636
+ wait = _retry_seconds(retry)
637
+ headers = {"Content-Type": _PROBLEM, "Retry-After": str(wait)}
638
+ if limit is not None:
639
+ headers.update(ratelimit_headers(limit=limit, remaining=0, reset=retry))
640
+ return 429, headers, _problem_body(429, "Too Many Requests", detail)
641
+
642
+
643
+ def problem_response(exc: BaseException) -> tuple[int, dict[str, str], bytes]:
644
+ """Map a resilience exception to ``(status, headers, problem+json body)``.
645
+
646
+ `RateLimitExceeded` gives 429, `CircuitOpenError` 503 with ``Retry-After`` from the
647
+ breaker, and `BulkheadFull` 503 with ``Retry-After: 1``.
648
+
649
+ Raises:
650
+ TypeError: For any other exception type.
651
+
652
+ Example:
653
+ >>> problem_response(BulkheadFull("full", name=None, max_concurrent=1))[0]
654
+ 503
655
+ """
656
+ if isinstance(exc, RateLimitExceeded):
657
+ return too_many_requests(exc)
658
+ if isinstance(exc, CircuitOpenError):
659
+ wait = _retry_seconds(exc.retry_after)
660
+ elif isinstance(exc, BulkheadFull):
661
+ wait = 1
662
+ else:
663
+ raise TypeError(f"no problem response for {type(exc).__name__}")
664
+ headers = {"Content-Type": _PROBLEM, "Retry-After": str(wait)}
665
+ # The exception message names internal breakers/bulkheads; clients get a fixed text.
666
+ return 503, headers, _problem_body(503, "Service Unavailable", _UNAVAILABLE_DETAIL)
667
+
668
+
669
+ _UNAVAILABLE_DETAIL = "the service is temporarily unavailable; retry later"
670
+
671
+ _HANDLED: tuple[type[BaseException], ...] = (RateLimitExceeded, CircuitOpenError, BulkheadFull)
672
+
673
+
674
+ def fastapi_exception_handlers() -> dict[type[BaseException], Callable[..., Any]]:
675
+ """Return ``{exception_type: async handler}`` for FastAPI/Starlette.
676
+
677
+ Register with ``app.add_exception_handler(type, handler)`` for each pair, or pass the
678
+ dict as ``FastAPI(exception_handlers=...)``. Imports ``starlette.responses`` lazily.
679
+
680
+ Example:
681
+ >>> # for t, h in fastapi_exception_handlers().items(): app.add_exception_handler(t, h)
682
+ """
683
+ import importlib
684
+
685
+ response_class = importlib.import_module("starlette.responses").Response
686
+
687
+ async def handler(request: Any, exc: BaseException) -> Any:
688
+ status, headers, body = problem_response(exc)
689
+ return response_class(content=body, status_code=status, headers=headers)
690
+
691
+ return dict.fromkeys(_HANDLED, handler)
692
+
693
+
694
+ def flask_register_error_handlers(app: Any) -> None:
695
+ """Register problem+json handlers on a Flask app (``app.register_error_handler``).
696
+
697
+ Example:
698
+ >>> # flask_register_error_handlers(app)
699
+ """
700
+
701
+ def handler(exc: BaseException) -> tuple[bytes, int, dict[str, str]]:
702
+ status, headers, body = problem_response(exc)
703
+ return body, status, headers
704
+
705
+ for exc_type in _HANDLED:
706
+ app.register_error_handler(exc_type, handler)
707
+
708
+
709
+ def django_response(exc: BaseException) -> Any:
710
+ """Build a Django ``HttpResponse`` for a handled exception (lazy ``django.http``).
711
+
712
+ Example:
713
+ >>> # return django_response(exc) # inside a view or middleware
714
+ """
715
+ import importlib
716
+
717
+ status, headers, body = problem_response(exc)
718
+ http = importlib.import_module("django.http")
719
+ response = http.HttpResponse(body, status=status, content_type=_PROBLEM)
720
+ for name, value in headers.items():
721
+ if name != "Content-Type":
722
+ response[name] = value
723
+ return response