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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""`singleflight`: concurrent identical calls share one execution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import concurrent.futures
|
|
7
|
+
import contextlib
|
|
8
|
+
import functools
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import weakref
|
|
12
|
+
from collections.abc import Awaitable, Callable, Coroutine, Hashable
|
|
13
|
+
from typing import (
|
|
14
|
+
Any,
|
|
15
|
+
Final,
|
|
16
|
+
Generic,
|
|
17
|
+
ParamSpec,
|
|
18
|
+
TypeVar,
|
|
19
|
+
cast,
|
|
20
|
+
overload,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from python_wrap import _core, _fork
|
|
24
|
+
from python_wrap._core import F, P, R
|
|
25
|
+
|
|
26
|
+
T = TypeVar("T")
|
|
27
|
+
R_co = TypeVar("R_co", covariant=True)
|
|
28
|
+
P2 = ParamSpec("P2")
|
|
29
|
+
S = TypeVar("S")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _KwargsMark:
|
|
33
|
+
"""Private marker in keys built from keyword arguments (never equal to user data)."""
|
|
34
|
+
|
|
35
|
+
__slots__ = ()
|
|
36
|
+
|
|
37
|
+
def __repr__(self) -> str:
|
|
38
|
+
return "<kwargs>"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_KWARGS: Final = _KwargsMark()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _default_key(*args: Any, **kwargs: Any) -> Hashable:
|
|
45
|
+
# The marker keeps ``f(1, b=2)`` and ``f((1,), (("b", 2),))`` apart.
|
|
46
|
+
return (args, _KWARGS, tuple(sorted(kwargs.items()))) if kwargs else args
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _Flights(Generic[T]):
|
|
50
|
+
"""Thread-side bookkeeping for singleflight: key -> (in-flight future, leader thread)."""
|
|
51
|
+
|
|
52
|
+
def __init__(self) -> None:
|
|
53
|
+
self.lock = _fork.ForkSafeLock()
|
|
54
|
+
self.inflight: dict[Hashable, tuple[concurrent.futures.Future[T], int]] = {}
|
|
55
|
+
_fork.register(self)
|
|
56
|
+
|
|
57
|
+
def _reset_after_fork(self) -> None:
|
|
58
|
+
self.inflight.clear()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _AsyncFlight:
|
|
62
|
+
"""One in-flight async singleflight run: its task and the callers waiting for it."""
|
|
63
|
+
|
|
64
|
+
__slots__ = ("task", "waiters")
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self.task: asyncio.Task[None] | None = None
|
|
68
|
+
self.waiters: list[asyncio.Future[Any]] = []
|
|
69
|
+
|
|
70
|
+
def deliver(self, result: Any = None, exc: BaseException | None = None) -> None:
|
|
71
|
+
"""Hand the outcome to every caller still waiting (``exc=None`` means success)."""
|
|
72
|
+
waiters, self.waiters = self.waiters, []
|
|
73
|
+
for waiter in waiters:
|
|
74
|
+
if waiter.done():
|
|
75
|
+
continue
|
|
76
|
+
if exc is None:
|
|
77
|
+
waiter.set_result(result)
|
|
78
|
+
elif isinstance(exc, asyncio.CancelledError):
|
|
79
|
+
waiter.cancel()
|
|
80
|
+
else:
|
|
81
|
+
waiter.set_exception(exc)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _start_task(
|
|
85
|
+
loop: asyncio.AbstractEventLoop, coro: Coroutine[Any, Any, None]
|
|
86
|
+
) -> asyncio.Task[None]:
|
|
87
|
+
"""Start the shared run, eagerly where possible.
|
|
88
|
+
|
|
89
|
+
On Python 3.12+ with no custom task factory the task starts eagerly: it runs right
|
|
90
|
+
away, up to its first suspension, so a run that never suspends (an in-memory hit,
|
|
91
|
+
say) has finished before the caller would have waited at all. Otherwise (3.10/3.11,
|
|
92
|
+
or a task factory is installed, which is respected) it starts on the next loop
|
|
93
|
+
iteration, as `loop.create_task` does.
|
|
94
|
+
"""
|
|
95
|
+
if _EAGER_TASKS and loop.get_task_factory() is None:
|
|
96
|
+
return asyncio.Task(coro, loop=loop, eager_start=True) # type: ignore[call-arg,unused-ignore]
|
|
97
|
+
return loop.create_task(coro)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_EAGER_TASKS = sys.version_info >= (3, 12)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
async def _await_flight(flight: _AsyncFlight, waiter: asyncio.Future[T]) -> T:
|
|
104
|
+
"""Wait for a flight's outcome; a cancelled caller detaches, the run carries on.
|
|
105
|
+
|
|
106
|
+
The run resolves ``waiter`` itself (no done-callback relay), so an uncontended call
|
|
107
|
+
costs one loop iteration for the run plus the wake-up, and none at all when the
|
|
108
|
+
task ran eagerly to completion.
|
|
109
|
+
"""
|
|
110
|
+
try:
|
|
111
|
+
return await waiter
|
|
112
|
+
except asyncio.CancelledError:
|
|
113
|
+
if waiter.done() and not waiter.cancelled():
|
|
114
|
+
waiter.exception() # outcome arrived just as we were cancelled: retrieved
|
|
115
|
+
else:
|
|
116
|
+
with contextlib.suppress(ValueError):
|
|
117
|
+
flight.waiters.remove(waiter)
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@overload
|
|
122
|
+
def singleflight(func: F, /) -> F: ...
|
|
123
|
+
@overload
|
|
124
|
+
def singleflight(
|
|
125
|
+
func: None = None, /, *, key: Callable[..., Hashable] | None = None
|
|
126
|
+
) -> Callable[[F], F]: ...
|
|
127
|
+
def singleflight(
|
|
128
|
+
func: Callable[..., Any] | None = None,
|
|
129
|
+
/,
|
|
130
|
+
*,
|
|
131
|
+
key: Callable[..., Hashable] | None = None,
|
|
132
|
+
) -> Any:
|
|
133
|
+
"""Let concurrent calls with the same arguments share a single execution.
|
|
134
|
+
|
|
135
|
+
While a call for a given key is running, further calls with that key do not start
|
|
136
|
+
the function again; they wait and receive the same result, or the same exception.
|
|
137
|
+
Once it finishes, the next call runs fresh — this de-duplicates work in flight, it
|
|
138
|
+
is not a cache.
|
|
139
|
+
|
|
140
|
+
Sync functions de-duplicate across threads. ``async def`` functions de-duplicate
|
|
141
|
+
across tasks on the same event loop: the work runs in a shared task, so cancelling
|
|
142
|
+
one waiting caller does not cancel it for the others.
|
|
143
|
+
|
|
144
|
+
A re-entrant call — the function calling itself with the same key, on the leader's
|
|
145
|
+
own thread (sync) or from inside the shared task (async) — cannot wait for its own
|
|
146
|
+
result, so it runs the function directly, as if it were not decorated.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
func: The function to wrap (bare ``@singleflight`` form).
|
|
150
|
+
key: Function of the call's arguments returning a hashable key. Defaults to the
|
|
151
|
+
positional arguments plus sorted keyword arguments (including ``self`` for
|
|
152
|
+
methods), which must then be hashable.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
The wrapped function, or a decorator when called with options only.
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
TypeError: If the default key is used and an argument is unhashable.
|
|
159
|
+
|
|
160
|
+
Example:
|
|
161
|
+
>>> @singleflight
|
|
162
|
+
... def load_config(path: str) -> str:
|
|
163
|
+
... return open(path).read()
|
|
164
|
+
"""
|
|
165
|
+
key_func = key or _default_key
|
|
166
|
+
|
|
167
|
+
def decorate(f: Callable[P, R]) -> Callable[P, R]:
|
|
168
|
+
if _core.is_async(f):
|
|
169
|
+
async_f = cast(Callable[P, Awaitable[Any]], f)
|
|
170
|
+
flights_by_loop: weakref.WeakKeyDictionary[
|
|
171
|
+
asyncio.AbstractEventLoop, dict[Hashable, _AsyncFlight]
|
|
172
|
+
] = weakref.WeakKeyDictionary()
|
|
173
|
+
loops_lock = _fork.ForkSafeLock() # loops in several threads share the mapping
|
|
174
|
+
|
|
175
|
+
@functools.wraps(f)
|
|
176
|
+
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
|
|
177
|
+
k = key_func(*args, **kwargs)
|
|
178
|
+
loop = asyncio.get_running_loop()
|
|
179
|
+
inflight = flights_by_loop.get(loop)
|
|
180
|
+
if inflight is None:
|
|
181
|
+
with loops_lock:
|
|
182
|
+
inflight = flights_by_loop.setdefault(loop, {})
|
|
183
|
+
flight = inflight.get(k)
|
|
184
|
+
if flight is not None and flight.task is asyncio.current_task():
|
|
185
|
+
# Re-entrant call from inside the shared task: waiting for ourselves
|
|
186
|
+
# would deadlock, so run the function directly.
|
|
187
|
+
return await async_f(*args, **kwargs)
|
|
188
|
+
waiter: asyncio.Future[Any] = loop.create_future()
|
|
189
|
+
if flight is not None:
|
|
190
|
+
flight.waiters.append(waiter)
|
|
191
|
+
return await _await_flight(flight, waiter)
|
|
192
|
+
|
|
193
|
+
new = inflight[k] = _AsyncFlight()
|
|
194
|
+
new.waiters.append(waiter) # before the task starts: it may run eagerly
|
|
195
|
+
|
|
196
|
+
async def run() -> None:
|
|
197
|
+
new.task = asyncio.current_task()
|
|
198
|
+
try:
|
|
199
|
+
result = await async_f(*args, **kwargs)
|
|
200
|
+
except BaseException as exc:
|
|
201
|
+
if inflight.get(k) is new:
|
|
202
|
+
del inflight[k]
|
|
203
|
+
new.deliver(exc=exc)
|
|
204
|
+
if not isinstance(exc, Exception):
|
|
205
|
+
raise # CancelledError, KeyboardInterrupt, SystemExit
|
|
206
|
+
# Delivered to the callers; the task itself ends quietly, so an
|
|
207
|
+
# orphaned failure is never logged as "never retrieved".
|
|
208
|
+
else:
|
|
209
|
+
if inflight.get(k) is new:
|
|
210
|
+
del inflight[k]
|
|
211
|
+
new.deliver(result)
|
|
212
|
+
|
|
213
|
+
# Keep a strong reference: the event loop only holds tasks weakly.
|
|
214
|
+
new.task = _start_task(loop, run())
|
|
215
|
+
return await _await_flight(new, waiter)
|
|
216
|
+
|
|
217
|
+
async_wrapper.__dict__["_fork_reset"] = _fork.register_reset(flights_by_loop.clear)
|
|
218
|
+
return cast(Callable[P, R], async_wrapper)
|
|
219
|
+
|
|
220
|
+
flights: _Flights[R] = _Flights()
|
|
221
|
+
|
|
222
|
+
@functools.wraps(f)
|
|
223
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
224
|
+
k = key_func(*args, **kwargs)
|
|
225
|
+
me = threading.get_ident()
|
|
226
|
+
with flights.lock:
|
|
227
|
+
entry = flights.inflight.get(k)
|
|
228
|
+
if entry is None:
|
|
229
|
+
future: concurrent.futures.Future[R] = concurrent.futures.Future()
|
|
230
|
+
flights.inflight[k] = (future, me)
|
|
231
|
+
leader = True
|
|
232
|
+
else:
|
|
233
|
+
future, owner = entry
|
|
234
|
+
leader = False
|
|
235
|
+
if not leader:
|
|
236
|
+
if owner == me:
|
|
237
|
+
# Re-entrant call on the leader's own thread: waiting for our own
|
|
238
|
+
# result would deadlock, so run the function directly.
|
|
239
|
+
return f(*args, **kwargs)
|
|
240
|
+
return future.result()
|
|
241
|
+
try:
|
|
242
|
+
result = f(*args, **kwargs)
|
|
243
|
+
except BaseException as exc:
|
|
244
|
+
with flights.lock:
|
|
245
|
+
del flights.inflight[k]
|
|
246
|
+
future.set_exception(exc)
|
|
247
|
+
raise
|
|
248
|
+
with flights.lock:
|
|
249
|
+
del flights.inflight[k]
|
|
250
|
+
future.set_result(result)
|
|
251
|
+
return result
|
|
252
|
+
|
|
253
|
+
return wrapper
|
|
254
|
+
|
|
255
|
+
return decorate if func is None else decorate(func)
|
python_wrap/slow.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Slow-call detection for synchronous and asynchronous functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Any, TypeVar, cast
|
|
9
|
+
|
|
10
|
+
from python_wrap import _core
|
|
11
|
+
from python_wrap._runtime import seconds
|
|
12
|
+
from python_wrap.logs import _ArgBinder, _signature
|
|
13
|
+
from python_wrap.redaction import DEFAULT_REDACT, is_sensitive, redact
|
|
14
|
+
|
|
15
|
+
__all__ = ["timed"]
|
|
16
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def timed(
|
|
20
|
+
*,
|
|
21
|
+
warn_over: float | str = "2s",
|
|
22
|
+
log_args: bool = False,
|
|
23
|
+
redact_names: tuple[str, ...] = DEFAULT_REDACT,
|
|
24
|
+
logger: Any = None,
|
|
25
|
+
level: int = logging.WARNING,
|
|
26
|
+
) -> Callable[[F], F]:
|
|
27
|
+
"""Log only calls at or above the threshold, masking argument names and nested keys.
|
|
28
|
+
|
|
29
|
+
Error/cancellation paths are timed too; instrumentation never replaces the outcome.
|
|
30
|
+
The logging handler's formatter controls final output size; no return value is logged.
|
|
31
|
+
"""
|
|
32
|
+
threshold = seconds(warn_over, positive=False)
|
|
33
|
+
|
|
34
|
+
def decorate(func: F) -> F:
|
|
35
|
+
binder = _ArgBinder(_signature(func), lambda name: is_sensitive(name, redact_names))
|
|
36
|
+
name = _core.qualname(func)
|
|
37
|
+
log = _core.get_logger(logger)
|
|
38
|
+
|
|
39
|
+
def finish(start: float, args: tuple[Any, ...], kw: dict[str, Any]) -> None:
|
|
40
|
+
elapsed = _core.perf_counter() - start
|
|
41
|
+
if elapsed < threshold:
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
payload = redact(binder(args, kw), fragments=redact_names) if log_args else {}
|
|
45
|
+
log.log(level, "%s slow call: %.6fs arguments=%r", name, elapsed, payload)
|
|
46
|
+
_core.emit("timing.slow", name, seconds=elapsed)
|
|
47
|
+
except Exception:
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
if _core.is_async(func):
|
|
51
|
+
|
|
52
|
+
@functools.wraps(func)
|
|
53
|
+
async def aw(*args: Any, **kw: Any) -> Any:
|
|
54
|
+
start = _core.perf_counter()
|
|
55
|
+
try:
|
|
56
|
+
return await func(*args, **kw)
|
|
57
|
+
finally:
|
|
58
|
+
finish(start, args, kw)
|
|
59
|
+
|
|
60
|
+
return cast(F, aw)
|
|
61
|
+
|
|
62
|
+
@functools.wraps(func)
|
|
63
|
+
def sw(*args: Any, **kw: Any) -> Any:
|
|
64
|
+
start = _core.perf_counter()
|
|
65
|
+
try:
|
|
66
|
+
return func(*args, **kw)
|
|
67
|
+
finally:
|
|
68
|
+
finish(start, args, kw)
|
|
69
|
+
|
|
70
|
+
return cast(F, sw)
|
|
71
|
+
|
|
72
|
+
return decorate
|
python_wrap/stores.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Optional Redis cache adapter. The caller supplies a client; redis is not imported."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import math
|
|
8
|
+
import pickle
|
|
9
|
+
import re
|
|
10
|
+
import warnings
|
|
11
|
+
from collections.abc import Callable, Hashable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from python_wrap._backend import BackendMonitor
|
|
15
|
+
from python_wrap._runtime import stable_digest
|
|
16
|
+
|
|
17
|
+
KEY_FORMAT = "k2:" # key encoding version: entries written by 0.4.0b1 expire unread
|
|
18
|
+
|
|
19
|
+
__all__ = ["RedisStore", "json_codec", "signed_pickle_codec"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvalidSignature(ValueError):
|
|
23
|
+
"""A cache entry failed authentication."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def signed_pickle_codec(secret: bytes) -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]:
|
|
27
|
+
"""Authenticate pickle bytes before loading them; keep the signing key private."""
|
|
28
|
+
if not isinstance(secret, bytes) or len(secret) < 16:
|
|
29
|
+
raise ValueError("secret must be at least 16 bytes")
|
|
30
|
+
|
|
31
|
+
def dumps(value: Any) -> bytes:
|
|
32
|
+
payload = pickle.dumps(value)
|
|
33
|
+
return hmac.digest(secret, payload, hashlib.sha256) + payload
|
|
34
|
+
|
|
35
|
+
def loads(data: bytes) -> Any:
|
|
36
|
+
signature, payload = data[:32], data[32:]
|
|
37
|
+
if not hmac.compare_digest(signature, hmac.digest(secret, payload, hashlib.sha256)):
|
|
38
|
+
raise InvalidSignature("cache entry signature is invalid")
|
|
39
|
+
return pickle.loads(payload) # nosec B301 - payload authenticated by the HMAC above
|
|
40
|
+
|
|
41
|
+
return dumps, loads
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def json_codec() -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]:
|
|
45
|
+
"""Return a JSON codec for cache entries with JSON-compatible values."""
|
|
46
|
+
import json
|
|
47
|
+
|
|
48
|
+
return lambda value: json.dumps(value, separators=(",", ":")).encode(), json.loads
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RedisStore:
|
|
52
|
+
"""A namespaced `CacheStore` with opaque hashed keys and configurable serialization.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
client: A synchronous Redis-compatible client.
|
|
56
|
+
prefix: A nonempty namespace unique to one cached function.
|
|
57
|
+
dumps: Serializer for entries; defaults to pickle (trusted Redis data only).
|
|
58
|
+
loads: Deserializer matching dumps.
|
|
59
|
+
key_format: Optional function turning a cache key into a stable external key.
|
|
60
|
+
fail_open: Treat backend errors as misses/no-ops and log them, rather than raise.
|
|
61
|
+
|
|
62
|
+
`size()` is unknown (None); `cache_info()` never scans Redis. `clear()` scans only
|
|
63
|
+
this namespace, escaping glob metacharacters, and deletes in bounded batches.
|
|
64
|
+
`memoize` on an ``async def`` function calls CacheStore methods synchronously, so
|
|
65
|
+
every Redis round trip would block the event loop. For async code use
|
|
66
|
+
``amemoize(store=ThreadedStore(RedisStore(...)))`` (round trips in worker threads)
|
|
67
|
+
or `python_wrap.async_cache.AsyncRedisStore` with a ``redis.asyncio`` client.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
client: Any,
|
|
73
|
+
prefix: str,
|
|
74
|
+
*,
|
|
75
|
+
dumps: Callable[[Any], bytes] | None = None,
|
|
76
|
+
loads: Callable[[bytes], Any] | None = None,
|
|
77
|
+
key_format: Callable[[Hashable], str] | None = None,
|
|
78
|
+
fail_open: bool = True,
|
|
79
|
+
retry_backend_after: float = 1.0,
|
|
80
|
+
version: int | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
if not prefix:
|
|
83
|
+
raise ValueError("RedisStore needs a nonempty per-function prefix")
|
|
84
|
+
if version is not None and (
|
|
85
|
+
isinstance(version, bool) or not isinstance(version, int) or version < 1
|
|
86
|
+
):
|
|
87
|
+
raise ValueError("version must be a positive integer")
|
|
88
|
+
if dumps is None and loads is None:
|
|
89
|
+
from python_wrap.config import get_config
|
|
90
|
+
|
|
91
|
+
codec = get_config().get("cache_codec")
|
|
92
|
+
if codec is None:
|
|
93
|
+
warnings.warn(
|
|
94
|
+
"implicit pickle cache codec is deprecated; pass a codec",
|
|
95
|
+
DeprecationWarning,
|
|
96
|
+
stacklevel=2,
|
|
97
|
+
)
|
|
98
|
+
codec = (pickle.dumps, pickle.loads)
|
|
99
|
+
dumps, loads = codec
|
|
100
|
+
self.client, self.prefix = client, prefix + (f"v{version}:" if version else "")
|
|
101
|
+
self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads
|
|
102
|
+
self.key_format, self.fail_open = key_format, fail_open
|
|
103
|
+
# fail_open=True is "allow" (a miss); False is "raise".
|
|
104
|
+
self._monitor = BackendMonitor(
|
|
105
|
+
"cache", prefix, "allow" if fail_open else "raise", retry_backend_after
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def _key(self, key: Hashable) -> str:
|
|
109
|
+
if self.key_format:
|
|
110
|
+
return self.prefix + self.key_format(key)
|
|
111
|
+
return self.prefix + KEY_FORMAT + stable_digest(key)
|
|
112
|
+
|
|
113
|
+
def _run(self, action: Callable[[], Any], default: Any = None) -> Any:
|
|
114
|
+
return self._monitor.call("cache", action, lambda: default)
|
|
115
|
+
|
|
116
|
+
def get(self, key: Hashable, /) -> Any:
|
|
117
|
+
"""Return a decoded entry, or None on a miss."""
|
|
118
|
+
|
|
119
|
+
def read() -> Any:
|
|
120
|
+
value = self.client.get(self._key(key))
|
|
121
|
+
if value is None:
|
|
122
|
+
return None
|
|
123
|
+
try:
|
|
124
|
+
return self.loads(value)
|
|
125
|
+
except InvalidSignature:
|
|
126
|
+
from python_wrap import _core
|
|
127
|
+
|
|
128
|
+
_core.emit("cache.rejected", self.prefix, reason="signature")
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
return self._run(read)
|
|
132
|
+
|
|
133
|
+
def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None:
|
|
134
|
+
"""Store an entry with millisecond TTL precision."""
|
|
135
|
+
if ttl is not None and ttl <= 0:
|
|
136
|
+
self.delete(key)
|
|
137
|
+
return
|
|
138
|
+
options = {} if ttl is None else {"px": max(1, math.ceil(ttl * 1000))}
|
|
139
|
+
self._run(lambda: self.client.set(self._key(key), self.dumps(entry), **options))
|
|
140
|
+
|
|
141
|
+
def delete(self, key: Hashable, /) -> bool:
|
|
142
|
+
"""Delete one entry; report whether it existed."""
|
|
143
|
+
return bool(self._run(lambda: self.client.delete(self._key(key)), False))
|
|
144
|
+
|
|
145
|
+
def clear(self) -> None:
|
|
146
|
+
"""Delete this namespace, in batches, using UNLINK where supported."""
|
|
147
|
+
|
|
148
|
+
def clear() -> None:
|
|
149
|
+
pattern = re.sub(r"([\\*?\[\]])", r"\\\1", self.prefix) + "*"
|
|
150
|
+
batch = []
|
|
151
|
+
delete = getattr(self.client, "unlink", None) or self.client.delete
|
|
152
|
+
for key in self.client.scan_iter(match=pattern, count=200):
|
|
153
|
+
batch.append(key)
|
|
154
|
+
if len(batch) == 200:
|
|
155
|
+
delete(*batch)
|
|
156
|
+
batch.clear()
|
|
157
|
+
if batch:
|
|
158
|
+
delete(*batch)
|
|
159
|
+
|
|
160
|
+
self._run(clear)
|
|
161
|
+
|
|
162
|
+
def size(self) -> None:
|
|
163
|
+
"""Return None: an exact distributed entry count is intentionally not scanned."""
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
def __len__(self) -> int:
|
|
167
|
+
"""Return zero for compatibility; use size() for the unknown-size contract."""
|
|
168
|
+
return 0
|
python_wrap/switches.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Dynamic kill switches, with explicit sources and bounded local read caching."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Callable, Coroutine
|
|
8
|
+
from typing import Any, Literal, TypeVar, cast, overload
|
|
9
|
+
|
|
10
|
+
from python_wrap import _core
|
|
11
|
+
from python_wrap._backend import BackendMonitor
|
|
12
|
+
from python_wrap._runtime import seconds
|
|
13
|
+
from python_wrap.caching import memoize
|
|
14
|
+
from python_wrap.retry import _Decorator
|
|
15
|
+
|
|
16
|
+
__all__ = ["EnvSource", "FeatureDisabled", "RedisSource", "switch"]
|
|
17
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
18
|
+
T = TypeVar("T")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _enabled(value: Any) -> bool:
|
|
22
|
+
if isinstance(value, bytes):
|
|
23
|
+
value = value.decode()
|
|
24
|
+
if isinstance(value, str):
|
|
25
|
+
if value.casefold() in {"1", "true", "yes", "on", "enabled"}:
|
|
26
|
+
return True
|
|
27
|
+
if value.casefold() in {"0", "false", "no", "off", "disabled"}:
|
|
28
|
+
return False
|
|
29
|
+
raise ValueError(f"invalid switch value: {value!r}")
|
|
30
|
+
return bool(value)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FeatureDisabled(RuntimeError):
|
|
34
|
+
"""A disabled integration was called."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class EnvSource:
|
|
38
|
+
"""Read PREFIX + uppercased switch name from the current process environment."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, prefix: str = "PW_SWITCH_", *, default: bool = True) -> None:
|
|
41
|
+
self.prefix, self.default = prefix, default
|
|
42
|
+
|
|
43
|
+
def __call__(self, name: str) -> bool:
|
|
44
|
+
return _enabled(os.environ.get(self.prefix + name.upper(), self.default))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RedisSource:
|
|
48
|
+
"""Read a boolean flag from a supplied Redis client.
|
|
49
|
+
|
|
50
|
+
``on_backend_error="raise"`` (the default) propagates store errors; ``"local"`` and
|
|
51
|
+
``"allow"`` answer ``default`` while the store is down.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
client: Any,
|
|
57
|
+
prefix: str = "python-wrap:switch:",
|
|
58
|
+
*,
|
|
59
|
+
default: bool = True,
|
|
60
|
+
on_backend_error: str | None = None,
|
|
61
|
+
retry_backend_after: float = 1.0,
|
|
62
|
+
) -> None:
|
|
63
|
+
self.client, self.prefix, self.default = client, prefix, default
|
|
64
|
+
self._monitor = BackendMonitor("switch", prefix, on_backend_error, retry_backend_after)
|
|
65
|
+
|
|
66
|
+
def __call__(self, name: str) -> bool:
|
|
67
|
+
def read() -> bool:
|
|
68
|
+
value = self.client.get(self.prefix + name)
|
|
69
|
+
return self.default if value is None else _enabled(value)
|
|
70
|
+
|
|
71
|
+
return self._monitor.call("get", read, lambda: self.default)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@overload
|
|
75
|
+
def switch(
|
|
76
|
+
name: str,
|
|
77
|
+
*,
|
|
78
|
+
source: Callable[[str], bool] | None = None,
|
|
79
|
+
when_off: Literal["raise"] = "raise",
|
|
80
|
+
ttl: float = 0,
|
|
81
|
+
) -> Callable[[F], F]: ...
|
|
82
|
+
@overload
|
|
83
|
+
def switch(
|
|
84
|
+
name: str,
|
|
85
|
+
*,
|
|
86
|
+
source: Callable[[str], bool] | None = None,
|
|
87
|
+
when_off: Literal["skip"],
|
|
88
|
+
ttl: float = 0,
|
|
89
|
+
) -> _Decorator[None]: ...
|
|
90
|
+
@overload
|
|
91
|
+
def switch(
|
|
92
|
+
name: str,
|
|
93
|
+
*,
|
|
94
|
+
source: Callable[[str], bool] | None = None,
|
|
95
|
+
when_off: Callable[..., Coroutine[Any, Any, T]],
|
|
96
|
+
ttl: float = 0,
|
|
97
|
+
) -> _Decorator[T]: ...
|
|
98
|
+
@overload
|
|
99
|
+
def switch(
|
|
100
|
+
name: str,
|
|
101
|
+
*,
|
|
102
|
+
source: Callable[[str], bool] | None = None,
|
|
103
|
+
when_off: Callable[..., T],
|
|
104
|
+
ttl: float = 0,
|
|
105
|
+
) -> _Decorator[T]: ...
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def switch(
|
|
109
|
+
name: str,
|
|
110
|
+
*,
|
|
111
|
+
source: Callable[[str], bool] | None = None,
|
|
112
|
+
when_off: str | Callable[..., Any] = "raise",
|
|
113
|
+
ttl: float = 0,
|
|
114
|
+
) -> Any:
|
|
115
|
+
"""Read a switch at call time; disabled calls raise, skip, or use a fallback.
|
|
116
|
+
|
|
117
|
+
`when_off="skip"` returns None. `when_off=callable` receives the original arguments.
|
|
118
|
+
Async functions offload synchronous source I/O and await async fallbacks.
|
|
119
|
+
"""
|
|
120
|
+
import asyncio
|
|
121
|
+
import inspect
|
|
122
|
+
|
|
123
|
+
ttl = seconds(ttl, positive=False)
|
|
124
|
+
if not callable(when_off) and when_off not in {"raise", "skip"}:
|
|
125
|
+
raise ValueError("when_off must be 'raise', 'skip', or a callable")
|
|
126
|
+
read = source if source is not None else EnvSource()
|
|
127
|
+
check: Callable[[str], bool] = memoize(ttl=ttl)(read) if ttl else read
|
|
128
|
+
|
|
129
|
+
def decorate(func: F) -> F:
|
|
130
|
+
def off(args: tuple[Any, ...], kw: dict[str, Any]) -> Any:
|
|
131
|
+
if callable(when_off):
|
|
132
|
+
return when_off(*args, **kw)
|
|
133
|
+
if when_off == "raise":
|
|
134
|
+
raise FeatureDisabled(name)
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
if _core.is_async(func):
|
|
138
|
+
|
|
139
|
+
@functools.wraps(func)
|
|
140
|
+
async def aw(*args: Any, **kw: Any) -> Any:
|
|
141
|
+
if await asyncio.to_thread(check, name):
|
|
142
|
+
return await func(*args, **kw)
|
|
143
|
+
value = off(args, kw)
|
|
144
|
+
return await value if inspect.isawaitable(value) else value
|
|
145
|
+
|
|
146
|
+
return cast(F, aw)
|
|
147
|
+
|
|
148
|
+
if callable(when_off) and _core.is_async(when_off):
|
|
149
|
+
raise TypeError("a synchronous switch cannot await an async fallback")
|
|
150
|
+
|
|
151
|
+
@functools.wraps(func)
|
|
152
|
+
def sw(*args: Any, **kw: Any) -> Any:
|
|
153
|
+
if check(name):
|
|
154
|
+
return func(*args, **kw)
|
|
155
|
+
value = off(args, kw)
|
|
156
|
+
if inspect.isawaitable(value):
|
|
157
|
+
if inspect.iscoroutine(value):
|
|
158
|
+
value.close()
|
|
159
|
+
raise TypeError("a synchronous switch fallback returned an awaitable")
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
return cast(F, sw)
|
|
163
|
+
|
|
164
|
+
return decorate
|