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
python_wrap/debounce.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""`throttle` and `debounce`: run at most once per interval, or once activity stops."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import functools
|
|
8
|
+
import threading
|
|
9
|
+
import weakref
|
|
10
|
+
from collections.abc import Awaitable, Callable, Coroutine, Hashable
|
|
11
|
+
from typing import (
|
|
12
|
+
Any,
|
|
13
|
+
Concatenate,
|
|
14
|
+
ParamSpec,
|
|
15
|
+
Protocol,
|
|
16
|
+
TypeVar,
|
|
17
|
+
cast,
|
|
18
|
+
overload,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from python_wrap import _core, _fork
|
|
22
|
+
from python_wrap._buckets import _Buckets
|
|
23
|
+
from python_wrap._core import P
|
|
24
|
+
|
|
25
|
+
T = TypeVar("T")
|
|
26
|
+
R_co = TypeVar("R_co", covariant=True)
|
|
27
|
+
P2 = ParamSpec("P2")
|
|
28
|
+
S = TypeVar("S")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _ThrottleDecorator(Protocol):
|
|
32
|
+
@overload
|
|
33
|
+
def __call__(
|
|
34
|
+
self, func: Callable[P, Coroutine[Any, Any, T]], /
|
|
35
|
+
) -> Callable[P, Coroutine[Any, Any, T | None]]: ...
|
|
36
|
+
@overload
|
|
37
|
+
def __call__(self, func: Callable[P, T], /) -> Callable[P, T | None]: ...
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _ThrottleState:
|
|
41
|
+
"""One throttle window: when the last run started and what the last run returned."""
|
|
42
|
+
|
|
43
|
+
__slots__ = ("last_result", "last_start")
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
self.last_start: float | None = None
|
|
47
|
+
self.last_result: Any = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def throttle(
|
|
51
|
+
interval: float,
|
|
52
|
+
*,
|
|
53
|
+
key: Callable[..., Hashable] | None = None,
|
|
54
|
+
per_instance: bool = False,
|
|
55
|
+
) -> _ThrottleDecorator:
|
|
56
|
+
"""Run the function at most once per ``interval`` seconds.
|
|
57
|
+
|
|
58
|
+
The first call runs and opens a window of ``interval`` seconds (measured from when
|
|
59
|
+
the call started). Calls inside the window do not run; they return the result of the
|
|
60
|
+
most recent run that *returned* (``None`` if none has returned yet). A call that
|
|
61
|
+
raises propagates its exception to its own caller and still uses up its window, but
|
|
62
|
+
does not replace the remembered result: calls skipped inside that window get the
|
|
63
|
+
previous successful result (or ``None``), not the error. Thread-safe; the function
|
|
64
|
+
itself runs outside the lock, so a slow call does not block skipped callers.
|
|
65
|
+
``async def`` functions get the same semantics with an ``async`` wrapper.
|
|
66
|
+
|
|
67
|
+
The window belongs to the decorated function, so on a method every instance shares
|
|
68
|
+
it. ``key`` gives each key its own window and ``per_instance`` gives each instance
|
|
69
|
+
its own; they combine (a window per instance and key).
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
interval: Minimum seconds between runs; must be positive.
|
|
73
|
+
key: Optional function called with the call's arguments (including ``self`` for
|
|
74
|
+
methods) that returns a hashable key, e.g. a user id; each key has its own
|
|
75
|
+
window, like ``key=`` on `rate_limit`. Windows that have run out are dropped
|
|
76
|
+
now and then, so keys do not pile up.
|
|
77
|
+
per_instance: For methods: one window per instance, found by identity through a
|
|
78
|
+
weak reference, so instances stay collectable and need not be hashable. They
|
|
79
|
+
must be weak-referenceable (a ``__slots__`` class must list ``'__weakref__'``).
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
A decorator; the wrapped function returns ``R | None``.
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
ValueError: If ``interval`` is not positive.
|
|
86
|
+
TypeError: At call time with ``per_instance``, for an instance that cannot be
|
|
87
|
+
weakly referenced.
|
|
88
|
+
|
|
89
|
+
Example:
|
|
90
|
+
>>> @throttle(1.0)
|
|
91
|
+
... def refresh() -> str:
|
|
92
|
+
... return "fresh"
|
|
93
|
+
>>> class Sensor:
|
|
94
|
+
... @throttle(1.0, per_instance=True)
|
|
95
|
+
... def read(self) -> str: ...
|
|
96
|
+
"""
|
|
97
|
+
if interval <= 0:
|
|
98
|
+
raise ValueError(f"throttle interval must be positive, got {interval!r}")
|
|
99
|
+
|
|
100
|
+
def decorate(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
101
|
+
lock = _fork.ForkSafeLock()
|
|
102
|
+
buckets = _Buckets(
|
|
103
|
+
_ThrottleState,
|
|
104
|
+
key=key,
|
|
105
|
+
per_instance=per_instance,
|
|
106
|
+
idle=lambda st: st.last_start is None or _core.monotonic() - st.last_start >= interval,
|
|
107
|
+
what="throttle",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
name = _core.qualname(func)
|
|
111
|
+
|
|
112
|
+
def should_run(args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[Any, bool, Any]:
|
|
113
|
+
state = buckets.get(args, kwargs)
|
|
114
|
+
if _core.overrides.disable_rate_limits:
|
|
115
|
+
return state, True, None
|
|
116
|
+
now = _core.monotonic()
|
|
117
|
+
with lock:
|
|
118
|
+
if state.last_start is None or now - state.last_start >= interval:
|
|
119
|
+
state.last_start = now
|
|
120
|
+
return state, True, None
|
|
121
|
+
previous = state.last_result
|
|
122
|
+
_core.emit("throttle.skipped", name)
|
|
123
|
+
return state, False, previous
|
|
124
|
+
|
|
125
|
+
def store(state: _ThrottleState, result: Any) -> Any:
|
|
126
|
+
with lock:
|
|
127
|
+
state.last_result = result
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
if _core.is_async(func):
|
|
131
|
+
|
|
132
|
+
@functools.wraps(func)
|
|
133
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
134
|
+
state, run, previous = should_run(args, kwargs)
|
|
135
|
+
if not run:
|
|
136
|
+
return previous
|
|
137
|
+
return store(state, await func(*args, **kwargs))
|
|
138
|
+
|
|
139
|
+
return async_wrapper
|
|
140
|
+
|
|
141
|
+
@functools.wraps(func)
|
|
142
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
143
|
+
state, run, previous = should_run(args, kwargs)
|
|
144
|
+
if not run:
|
|
145
|
+
return previous
|
|
146
|
+
return store(state, func(*args, **kwargs))
|
|
147
|
+
|
|
148
|
+
return wrapper
|
|
149
|
+
|
|
150
|
+
return cast(_ThrottleDecorator, decorate)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---------------------------------------------------------------------------------------
|
|
154
|
+
# debounce
|
|
155
|
+
# ---------------------------------------------------------------------------------------
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class Debounced(Protocol[P, R_co]):
|
|
159
|
+
"""A debounced sync function: calls return ``None``; the real call happens later.
|
|
160
|
+
|
|
161
|
+
Binds ``self`` and ``cls`` like `python_wrap.caching.Memoized`, with the same typing
|
|
162
|
+
limitations.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...
|
|
166
|
+
|
|
167
|
+
@overload
|
|
168
|
+
def __get__(
|
|
169
|
+
self: Debounced[Concatenate[type[T], P2], R_co], instance: None, owner: type[T]
|
|
170
|
+
) -> _DebouncedOnClass[P, P2, R_co]: ...
|
|
171
|
+
@overload
|
|
172
|
+
def __get__(self, instance: None, owner: type | None = None) -> Debounced[P, R_co]: ...
|
|
173
|
+
@overload
|
|
174
|
+
def __get__(
|
|
175
|
+
self: Debounced[Concatenate[Any, P2], R_co], instance: object, owner: type | None = None
|
|
176
|
+
) -> Debounced[P2, R_co]: ...
|
|
177
|
+
|
|
178
|
+
def cancel(self, *args: Any, **kwargs: Any) -> None:
|
|
179
|
+
"""Drop the pending call, if any (``key``/``per_instance``: pass a call's arguments)."""
|
|
180
|
+
|
|
181
|
+
def flush(self, *args: Any, **kwargs: Any) -> R_co | None:
|
|
182
|
+
"""Run the pending call now and return its result (``None`` if nothing pending)."""
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class _DebouncedOnClass(Debounced[P, R_co], Protocol[P, P2, R_co]):
|
|
186
|
+
"""`Debounced` read from a class: accepts the call with and without the first argument.
|
|
187
|
+
|
|
188
|
+
Returned for class access (``Cls.attr``) when the first parameter could be ``cls``.
|
|
189
|
+
pyright only picks it under ``@classmethod``; mypy cannot tell a classmethod from an
|
|
190
|
+
instance or static method there, so both call forms are accepted.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
@overload
|
|
194
|
+
def __call__(self, *args: P2.args, **kwargs: P2.kwargs) -> None: ...
|
|
195
|
+
@overload
|
|
196
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class AsyncDebounced(Protocol[P, R_co]):
|
|
200
|
+
"""A debounced ``async def`` function; see `debounce` for the await semantics.
|
|
201
|
+
|
|
202
|
+
Binds ``self`` and ``cls`` like `python_wrap.caching.Memoized`, with the same typing
|
|
203
|
+
limitations.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, R_co]: ...
|
|
207
|
+
|
|
208
|
+
@overload
|
|
209
|
+
def __get__(
|
|
210
|
+
self: AsyncDebounced[Concatenate[type[T], P2], R_co], instance: None, owner: type[T]
|
|
211
|
+
) -> _AsyncDebouncedOnClass[P, P2, R_co]: ...
|
|
212
|
+
@overload
|
|
213
|
+
def __get__(self, instance: None, owner: type | None = None) -> AsyncDebounced[P, R_co]: ...
|
|
214
|
+
@overload
|
|
215
|
+
def __get__(
|
|
216
|
+
self: AsyncDebounced[Concatenate[Any, P2], R_co],
|
|
217
|
+
instance: object,
|
|
218
|
+
owner: type | None = None,
|
|
219
|
+
) -> AsyncDebounced[P2, R_co]: ...
|
|
220
|
+
|
|
221
|
+
def cancel(self, *args: Any, **kwargs: Any) -> None:
|
|
222
|
+
"""Drop the pending call; callers awaiting it get ``CancelledError``."""
|
|
223
|
+
|
|
224
|
+
def flush(self, *args: Any, **kwargs: Any) -> Coroutine[Any, Any, R_co | None]:
|
|
225
|
+
"""Run the pending call now; awaiting returns its result (``None`` if none)."""
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class _AsyncDebouncedOnClass(AsyncDebounced[P, R_co], Protocol[P, P2, R_co]):
|
|
229
|
+
"""`AsyncDebounced` read from a class: accepts the call with and without the first argument.
|
|
230
|
+
|
|
231
|
+
Returned for class access (``Cls.attr``) when the first parameter could be ``cls``.
|
|
232
|
+
pyright only picks it under ``@classmethod``; mypy cannot tell a classmethod from an
|
|
233
|
+
instance or static method there, so both call forms are accepted.
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
@overload
|
|
237
|
+
def __call__(self, *args: P2.args, **kwargs: P2.kwargs) -> Coroutine[Any, Any, R_co]: ...
|
|
238
|
+
@overload
|
|
239
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, R_co]: ...
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class _DebounceDecorator(Protocol):
|
|
243
|
+
@overload
|
|
244
|
+
def __call__( # type: ignore[overload-overlap]
|
|
245
|
+
self, func: Callable[P, Coroutine[Any, Any, T]], /
|
|
246
|
+
) -> AsyncDebounced[P, T]: ...
|
|
247
|
+
@overload
|
|
248
|
+
def __call__(self, func: Callable[P, T], /) -> Debounced[P, T]: ...
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
_Pending = tuple[tuple[Any, ...], dict[str, Any]]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class _SyncDebState:
|
|
255
|
+
"""One sync debounce slot: the running timer and the call waiting for it."""
|
|
256
|
+
|
|
257
|
+
__slots__ = ("pending", "timer")
|
|
258
|
+
|
|
259
|
+
def __init__(self) -> None:
|
|
260
|
+
self.timer: threading.Timer | None = None
|
|
261
|
+
self.pending: _Pending | None = None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _debounce_sync(
|
|
265
|
+
func: Callable[..., Any],
|
|
266
|
+
wait: float,
|
|
267
|
+
key: Callable[..., Hashable] | None,
|
|
268
|
+
per_instance: bool,
|
|
269
|
+
) -> Callable[..., None]:
|
|
270
|
+
lock = _fork.ForkSafeLock()
|
|
271
|
+
buckets = _Buckets(
|
|
272
|
+
_SyncDebState,
|
|
273
|
+
key=key,
|
|
274
|
+
per_instance=per_instance,
|
|
275
|
+
idle=lambda st: st.timer is None and st.pending is None,
|
|
276
|
+
what="debounce",
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
def take(st: _SyncDebState) -> _Pending | None:
|
|
280
|
+
if st.timer is not None:
|
|
281
|
+
st.timer.cancel()
|
|
282
|
+
call, st.timer, st.pending = st.pending, None, None
|
|
283
|
+
return call
|
|
284
|
+
|
|
285
|
+
def fire(st: _SyncDebState, me: list[threading.Timer]) -> None:
|
|
286
|
+
with lock:
|
|
287
|
+
if st.timer is not me[0]: # superseded or cancelled meanwhile
|
|
288
|
+
return
|
|
289
|
+
call = take(st)
|
|
290
|
+
if call is not None:
|
|
291
|
+
func(*call[0], **call[1])
|
|
292
|
+
|
|
293
|
+
@functools.wraps(func)
|
|
294
|
+
def wrapper(*args: Any, **kwargs: Any) -> None:
|
|
295
|
+
st = buckets.get(args, kwargs)
|
|
296
|
+
with lock:
|
|
297
|
+
take(st)
|
|
298
|
+
me: list[threading.Timer] = []
|
|
299
|
+
timer = st.timer = threading.Timer(wait, fire, args=(st, me))
|
|
300
|
+
me.append(timer)
|
|
301
|
+
timer.daemon = True
|
|
302
|
+
st.pending = (args, kwargs)
|
|
303
|
+
timer.start()
|
|
304
|
+
|
|
305
|
+
def selected(args: tuple[Any, ...], kwargs: dict[str, Any]) -> list[_SyncDebState] | None:
|
|
306
|
+
"""The states to act on, or None if the arguments name a state that does not exist."""
|
|
307
|
+
if buckets.selective and (args or kwargs):
|
|
308
|
+
found = buckets.find(args, kwargs)
|
|
309
|
+
return None if found is None else [found]
|
|
310
|
+
return buckets.states()
|
|
311
|
+
|
|
312
|
+
def cancel(*args: Any, **kwargs: Any) -> None:
|
|
313
|
+
with lock:
|
|
314
|
+
for st in selected(args, kwargs) or ():
|
|
315
|
+
take(st)
|
|
316
|
+
|
|
317
|
+
def flush(*args: Any, **kwargs: Any) -> Any:
|
|
318
|
+
with lock:
|
|
319
|
+
calls = [take(st) for st in selected(args, kwargs) or ()]
|
|
320
|
+
results = [func(*call[0], **call[1]) for call in calls if call is not None]
|
|
321
|
+
return results[0] if len(results) == 1 else None
|
|
322
|
+
|
|
323
|
+
wrapper.cancel = cancel # type: ignore[attr-defined]
|
|
324
|
+
wrapper.flush = flush # type: ignore[attr-defined]
|
|
325
|
+
return wrapper
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
class _AsyncBurst:
|
|
329
|
+
"""One burst of async debounced calls: the latest arguments and a shared outcome."""
|
|
330
|
+
|
|
331
|
+
def __init__(self, loop: asyncio.AbstractEventLoop, state: _AsyncDebState) -> None:
|
|
332
|
+
self.outcome: asyncio.Future[Any] = loop.create_future()
|
|
333
|
+
self.timer: asyncio.Task[None] | None = None
|
|
334
|
+
self.call: _Pending | None = None
|
|
335
|
+
self.state = state
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class _AsyncDebState:
|
|
339
|
+
"""One async debounce slot: its pending burst per event loop."""
|
|
340
|
+
|
|
341
|
+
__slots__ = ("bursts",)
|
|
342
|
+
|
|
343
|
+
def __init__(self) -> None:
|
|
344
|
+
self.bursts: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, _AsyncBurst] = (
|
|
345
|
+
weakref.WeakKeyDictionary()
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _debounce_async(
|
|
350
|
+
func: Callable[..., Awaitable[Any]],
|
|
351
|
+
wait: float,
|
|
352
|
+
key: Callable[..., Hashable] | None,
|
|
353
|
+
per_instance: bool,
|
|
354
|
+
) -> Callable[..., Any]:
|
|
355
|
+
# Several loops (in several threads) share each state's `bursts`; each burst itself
|
|
356
|
+
# is only ever touched from its own loop's thread.
|
|
357
|
+
bursts_lock = _fork.ForkSafeLock()
|
|
358
|
+
buckets = _Buckets(
|
|
359
|
+
_AsyncDebState,
|
|
360
|
+
key=key,
|
|
361
|
+
per_instance=per_instance,
|
|
362
|
+
idle=lambda st: not st.bursts,
|
|
363
|
+
what="debounce",
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
async def run(burst: _AsyncBurst) -> Any:
|
|
367
|
+
loop = asyncio.get_running_loop()
|
|
368
|
+
with bursts_lock:
|
|
369
|
+
if burst.state.bursts.get(loop) is burst:
|
|
370
|
+
del burst.state.bursts[loop]
|
|
371
|
+
call = burst.call
|
|
372
|
+
if call is None or burst.outcome.done():
|
|
373
|
+
return None
|
|
374
|
+
try:
|
|
375
|
+
result = await func(*call[0], **call[1])
|
|
376
|
+
except asyncio.CancelledError:
|
|
377
|
+
burst.outcome.cancel()
|
|
378
|
+
raise
|
|
379
|
+
except BaseException as exc:
|
|
380
|
+
if not burst.outcome.done():
|
|
381
|
+
burst.outcome.set_exception(exc)
|
|
382
|
+
burst.outcome.exception() # mark retrieved: callers may all be gone
|
|
383
|
+
raise
|
|
384
|
+
if not burst.outcome.done():
|
|
385
|
+
burst.outcome.set_result(result)
|
|
386
|
+
return result
|
|
387
|
+
|
|
388
|
+
async def sleep_then_run(burst: _AsyncBurst) -> None:
|
|
389
|
+
await asyncio.sleep(wait) # real time, like the sync `threading.Timer`
|
|
390
|
+
burst.timer = None # past the cancellation point: run even if called again now
|
|
391
|
+
with contextlib.suppress(Exception): # delivered to callers via burst.outcome
|
|
392
|
+
await run(burst)
|
|
393
|
+
|
|
394
|
+
@functools.wraps(func)
|
|
395
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
396
|
+
loop = asyncio.get_running_loop()
|
|
397
|
+
st = buckets.get(args, kwargs)
|
|
398
|
+
with bursts_lock:
|
|
399
|
+
burst = st.bursts.get(loop)
|
|
400
|
+
if burst is None:
|
|
401
|
+
burst = st.bursts[loop] = _AsyncBurst(loop, st)
|
|
402
|
+
if burst.timer is not None:
|
|
403
|
+
burst.timer.cancel()
|
|
404
|
+
burst.call = (args, kwargs)
|
|
405
|
+
burst.timer = loop.create_task(sleep_then_run(burst))
|
|
406
|
+
return await asyncio.shield(burst.outcome)
|
|
407
|
+
|
|
408
|
+
def cancel_burst(burst: _AsyncBurst) -> None:
|
|
409
|
+
if burst.timer is not None:
|
|
410
|
+
burst.timer.cancel()
|
|
411
|
+
burst.outcome.cancel()
|
|
412
|
+
|
|
413
|
+
def selected(args: tuple[Any, ...], kwargs: dict[str, Any]) -> list[_AsyncDebState]:
|
|
414
|
+
if buckets.selective and (args or kwargs):
|
|
415
|
+
found = buckets.find(args, kwargs)
|
|
416
|
+
return [] if found is None else [found]
|
|
417
|
+
return buckets.states()
|
|
418
|
+
|
|
419
|
+
def cancel(*args: Any, **kwargs: Any) -> None:
|
|
420
|
+
try:
|
|
421
|
+
running: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()
|
|
422
|
+
except RuntimeError:
|
|
423
|
+
running = None
|
|
424
|
+
taken: list[tuple[asyncio.AbstractEventLoop, _AsyncBurst | None]] = []
|
|
425
|
+
states = selected(args, kwargs)
|
|
426
|
+
with bursts_lock:
|
|
427
|
+
for st in states:
|
|
428
|
+
if running is not None:
|
|
429
|
+
taken.append((running, st.bursts.pop(running, None)))
|
|
430
|
+
else:
|
|
431
|
+
taken.extend((lp, st.bursts.pop(lp)) for lp in list(st.bursts))
|
|
432
|
+
for lp, burst in taken:
|
|
433
|
+
if burst is None:
|
|
434
|
+
continue
|
|
435
|
+
if lp.is_closed():
|
|
436
|
+
continue
|
|
437
|
+
if lp is running or not lp.is_running():
|
|
438
|
+
cancel_burst(burst)
|
|
439
|
+
else:
|
|
440
|
+
# Another thread's loop: futures are not thread-safe, so hand the
|
|
441
|
+
# cancellation to that loop (which also wakes it up).
|
|
442
|
+
with contextlib.suppress(RuntimeError): # closed meanwhile
|
|
443
|
+
lp.call_soon_threadsafe(cancel_burst, burst)
|
|
444
|
+
|
|
445
|
+
async def flush(*args: Any, **kwargs: Any) -> Any:
|
|
446
|
+
loop = asyncio.get_running_loop()
|
|
447
|
+
states = selected(args, kwargs)
|
|
448
|
+
with bursts_lock:
|
|
449
|
+
found = [b for b in (st.bursts.get(loop) for st in states) if b is not None]
|
|
450
|
+
results = []
|
|
451
|
+
for burst in found:
|
|
452
|
+
if burst.timer is not None:
|
|
453
|
+
burst.timer.cancel()
|
|
454
|
+
burst.timer = None
|
|
455
|
+
results.append(await run(burst))
|
|
456
|
+
return results[0] if len(results) == 1 else None
|
|
457
|
+
|
|
458
|
+
wrapper.cancel = cancel # type: ignore[attr-defined]
|
|
459
|
+
wrapper.flush = flush # type: ignore[attr-defined]
|
|
460
|
+
return wrapper
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def debounce(
|
|
464
|
+
wait: float,
|
|
465
|
+
*,
|
|
466
|
+
key: Callable[..., Hashable] | None = None,
|
|
467
|
+
per_instance: bool = False,
|
|
468
|
+
) -> _DebounceDecorator:
|
|
469
|
+
"""Postpone running until ``wait`` seconds have passed since the last call.
|
|
470
|
+
|
|
471
|
+
Each call restarts the countdown and replaces the pending arguments, so only the last
|
|
472
|
+
call of a burst runs.
|
|
473
|
+
|
|
474
|
+
* Sync functions: the countdown is a daemon `threading.Timer`, so the function
|
|
475
|
+
runs in the timer's thread. The wrapper returns ``None`` immediately.
|
|
476
|
+
* ``async def`` functions: a call schedules a task on the running loop (cancelling the
|
|
477
|
+
previously scheduled one) and then waits for the burst to finish. **Every caller in
|
|
478
|
+
a burst awaits the same outcome** — the result (or exception) of the final call —
|
|
479
|
+
so superseded callers are not left hanging or cancelled. Calls must be awaited (or
|
|
480
|
+
wrapped in a task) to take effect; a single task awaiting sequentially simply waits
|
|
481
|
+
``wait`` seconds per call. Bursts are tracked per event loop.
|
|
482
|
+
|
|
483
|
+
The wrapper also has:
|
|
484
|
+
|
|
485
|
+
* ``.cancel()`` — drop the pending call (async awaiters get ``CancelledError``).
|
|
486
|
+
Thread-safe. For ``async def`` functions, inside a running loop it cancels that
|
|
487
|
+
loop's pending call; from a thread with no running loop it cancels the pending
|
|
488
|
+
call of every loop (handing the cancellation to each loop's own thread).
|
|
489
|
+
* ``.flush()`` — run the pending call right now and return its result, or ``None``
|
|
490
|
+
if nothing is pending. For ``async def`` functions it is a coroutine to ``await``.
|
|
491
|
+
|
|
492
|
+
State belongs to the decorated function, so on a method it is shared by all
|
|
493
|
+
instances: calls on different instances debounce each other. ``key`` gives each key
|
|
494
|
+
its own countdown and pending call, and ``per_instance`` gives each instance its own.
|
|
495
|
+
Then ``.cancel()`` and ``.flush()`` take the arguments of a call to say which one
|
|
496
|
+
(``obj.save.cancel(obj)``, since the attribute of a bound method is the function's);
|
|
497
|
+
without arguments they act on every pending call, and ``.flush()`` returns the result
|
|
498
|
+
only when exactly one call was flushed.
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
wait: Quiet period in seconds; must be non-negative.
|
|
502
|
+
key: Optional function called with the call's arguments (including ``self`` for
|
|
503
|
+
methods) that returns a hashable key; calls with different keys do not
|
|
504
|
+
debounce each other. Idle keys are dropped now and then.
|
|
505
|
+
per_instance: For methods: one debounce slot per instance, found by identity
|
|
506
|
+
through a weak reference, so instances stay collectable and need not be
|
|
507
|
+
hashable. They must be weak-referenceable (a ``__slots__`` class must list
|
|
508
|
+
``'__weakref__'``). A pending call keeps its instance alive until it runs.
|
|
509
|
+
|
|
510
|
+
Returns:
|
|
511
|
+
A decorator producing a `Debounced` or `AsyncDebounced` wrapper.
|
|
512
|
+
|
|
513
|
+
Raises:
|
|
514
|
+
ValueError: If ``wait`` is negative.
|
|
515
|
+
TypeError: At call time with ``per_instance``, for an instance that cannot be
|
|
516
|
+
weakly referenced.
|
|
517
|
+
|
|
518
|
+
Example:
|
|
519
|
+
>>> @debounce(0.3)
|
|
520
|
+
... def save(text: str) -> None: ...
|
|
521
|
+
>>> save("a"); save("ab"); save.flush() # runs once, with "ab"
|
|
522
|
+
>>> @debounce(0.3, key=lambda doc_id, *_: doc_id)
|
|
523
|
+
... def autosave(doc_id: int, text: str) -> None: ...
|
|
524
|
+
"""
|
|
525
|
+
if wait < 0:
|
|
526
|
+
raise ValueError(f"debounce wait must be non-negative, got {wait!r}")
|
|
527
|
+
|
|
528
|
+
def decorate(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
529
|
+
if _core.is_async(func):
|
|
530
|
+
return _debounce_async(func, wait, key, per_instance)
|
|
531
|
+
return _debounce_sync(func, wait, key, per_instance)
|
|
532
|
+
|
|
533
|
+
return cast(_DebounceDecorator, decorate)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
# ---------------------------------------------------------------------------------------
|
|
537
|
+
# singleflight
|
|
538
|
+
# ---------------------------------------------------------------------------------------
|
python_wrap/django.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Sync/async Django middleware for request context and cooperative deadlines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from python_wrap import _core
|
|
9
|
+
from python_wrap._integration import request_id, scope
|
|
10
|
+
from python_wrap._runtime import seconds
|
|
11
|
+
from python_wrap.propagation import deadline_budget, header_names
|
|
12
|
+
|
|
13
|
+
__all__ = ["ContextMiddleware"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ContextMiddleware:
|
|
17
|
+
"""Add python_wrap.django.ContextMiddleware to Django's MIDDLEWARE.
|
|
18
|
+
|
|
19
|
+
Optional constructor arguments are suitable for a configured middleware factory.
|
|
20
|
+
Context covers view dispatch; streaming iterator code should bind its own context.
|
|
21
|
+
The default user field uses the authenticated user's primary key, not credentials.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
sync_capable = True
|
|
25
|
+
async_capable = True
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
get_response: Callable[..., Any],
|
|
30
|
+
*,
|
|
31
|
+
budget: float | None = None,
|
|
32
|
+
user: Callable[[Any], Any] | None = None,
|
|
33
|
+
trust_deadline_header: bool = False,
|
|
34
|
+
) -> None:
|
|
35
|
+
budget = None if budget is None else seconds(budget, positive=False)
|
|
36
|
+
self.get_response, self.budget, self.user = get_response, budget, user
|
|
37
|
+
self.trust_deadline = trust_deadline_header
|
|
38
|
+
import importlib
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
async_helpers = importlib.import_module("asgiref.sync")
|
|
42
|
+
except ImportError:
|
|
43
|
+
async_helpers = None
|
|
44
|
+
self.is_async = _core.is_async(get_response) or (
|
|
45
|
+
async_helpers is not None and async_helpers.iscoroutinefunction(get_response)
|
|
46
|
+
)
|
|
47
|
+
if self.is_async:
|
|
48
|
+
if async_helpers is None:
|
|
49
|
+
raise ImportError("Django async middleware requires asgiref")
|
|
50
|
+
async_helpers.markcoroutinefunction(self)
|
|
51
|
+
|
|
52
|
+
def _scope(self, request: Any) -> Any:
|
|
53
|
+
fields: dict[str, Any] = {"request_id": request_id(request.META.get(self._id_meta_key()))}
|
|
54
|
+
if self.user:
|
|
55
|
+
fields["user"] = self.user(request)
|
|
56
|
+
else:
|
|
57
|
+
user = getattr(request, "user", None)
|
|
58
|
+
if user is not None and getattr(user, "is_authenticated", False):
|
|
59
|
+
fields["user"] = str(user.pk)
|
|
60
|
+
return scope(fields, self._budget(request))
|
|
61
|
+
|
|
62
|
+
def _budget(self, request: Any) -> float | None:
|
|
63
|
+
meta_key = "HTTP_" + header_names()[1].upper().replace("-", "_")
|
|
64
|
+
return deadline_budget(request.META.get(meta_key), self.budget, trust=self.trust_deadline)
|
|
65
|
+
|
|
66
|
+
def _id_meta_key(self) -> str:
|
|
67
|
+
return "HTTP_" + header_names()[0].upper().replace("-", "_")
|
|
68
|
+
|
|
69
|
+
def __call__(self, request: Any) -> Any:
|
|
70
|
+
if self.is_async:
|
|
71
|
+
return self._acall(request)
|
|
72
|
+
with self._scope(request):
|
|
73
|
+
return self.get_response(request)
|
|
74
|
+
|
|
75
|
+
async def _acall(self, request: Any) -> Any:
|
|
76
|
+
import importlib
|
|
77
|
+
|
|
78
|
+
async_helpers = importlib.import_module("asgiref.sync")
|
|
79
|
+
sync_to_async = async_helpers.sync_to_async
|
|
80
|
+
fields: dict[str, Any] = {"request_id": request_id(request.META.get(self._id_meta_key()))}
|
|
81
|
+
if self.user:
|
|
82
|
+
if _core.is_async(self.user) or async_helpers.iscoroutinefunction(self.user):
|
|
83
|
+
fields["user"] = await self.user(request)
|
|
84
|
+
else:
|
|
85
|
+
fields["user"] = await sync_to_async(self.user, thread_sensitive=True)(request)
|
|
86
|
+
elif hasattr(request, "auser"):
|
|
87
|
+
user = await request.auser()
|
|
88
|
+
if getattr(user, "is_authenticated", False):
|
|
89
|
+
fields["user"] = str(user.pk)
|
|
90
|
+
else:
|
|
91
|
+
|
|
92
|
+
def user_value() -> str | None:
|
|
93
|
+
user = getattr(request, "user", None)
|
|
94
|
+
return str(user.pk) if user is not None and user.is_authenticated else None
|
|
95
|
+
|
|
96
|
+
value = await sync_to_async(user_value, thread_sensitive=True)()
|
|
97
|
+
if value is not None:
|
|
98
|
+
fields["user"] = value
|
|
99
|
+
with scope(fields, self._budget(request)):
|
|
100
|
+
return await self.get_response(request)
|