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/adaptive.py
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"""Adaptive concurrency limits and per-key limiter pools.
|
|
2
|
+
|
|
3
|
+
* `AdaptiveLimiter` — an AIMD (additive increase, multiplicative decrease) concurrency
|
|
4
|
+
limit that finds a safe level by itself and sheds the excess with `LoadShed`.
|
|
5
|
+
* `PerKeyLimiter` — lazily creates one limiter per key (tenant, user, host) with LRU
|
|
6
|
+
eviction of idle keys.
|
|
7
|
+
* `per_key` — decorator applying a per-key limiter (any python-wrap limiter or
|
|
8
|
+
bulkhead) to each call.
|
|
9
|
+
|
|
10
|
+
A fixed `Bulkhead` needs a number picked in advance. An adaptive limit starts at
|
|
11
|
+
`initial`, creeps up while calls succeed quickly and backs off when calls time out, drop
|
|
12
|
+
connections or get slow, so a struggling dependency sees less load instead of more.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import functools
|
|
18
|
+
from collections import OrderedDict
|
|
19
|
+
from collections.abc import Callable, Hashable
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from types import TracebackType
|
|
22
|
+
from typing import Any, Generic, Literal, NoReturn, TypeVar, cast
|
|
23
|
+
|
|
24
|
+
from python_wrap import _core, _fork
|
|
25
|
+
from python_wrap.errors import BulkheadFull
|
|
26
|
+
|
|
27
|
+
__all__ = ["AdaptiveLimiter", "AdaptiveStats", "LoadShed", "PerKeyLimiter", "Permit", "per_key"]
|
|
28
|
+
|
|
29
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
30
|
+
L = TypeVar("L")
|
|
31
|
+
|
|
32
|
+
Priority = Literal["low", "normal", "critical"]
|
|
33
|
+
_PRIORITIES = ("low", "normal", "critical")
|
|
34
|
+
_DEFAULT_ON: tuple[type[BaseException], ...] = (TimeoutError, ConnectionError, BulkheadFull)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LoadShed(BulkheadFull):
|
|
38
|
+
"""The adaptive limit is reached, so the call was rejected without being attempted.
|
|
39
|
+
|
|
40
|
+
A `BulkheadFull`, so code that already handles bulkhead rejections handles this too.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
limit: The concurrency limit at that moment.
|
|
44
|
+
in_flight: Calls running at that moment.
|
|
45
|
+
priority: The priority the rejected call asked for.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
message: str,
|
|
51
|
+
*,
|
|
52
|
+
name: str | None,
|
|
53
|
+
limit: int,
|
|
54
|
+
in_flight: int,
|
|
55
|
+
priority: str,
|
|
56
|
+
) -> None:
|
|
57
|
+
super().__init__(message, name=name, max_concurrent=limit)
|
|
58
|
+
self.limit = limit
|
|
59
|
+
self.in_flight = in_flight
|
|
60
|
+
self.priority = priority
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class AdaptiveStats:
|
|
65
|
+
"""A snapshot of an `AdaptiveLimiter`.
|
|
66
|
+
|
|
67
|
+
Attributes:
|
|
68
|
+
limit: Current concurrency limit.
|
|
69
|
+
in_flight: Calls running now.
|
|
70
|
+
admitted: Calls let in since creation.
|
|
71
|
+
shed: Calls rejected with `LoadShed`.
|
|
72
|
+
successes: Calls that finished well.
|
|
73
|
+
drops: Calls that signalled overload (matching error or too slow).
|
|
74
|
+
increases: How many times the limit went up.
|
|
75
|
+
decreases: How many times the limit went down.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
limit: int
|
|
79
|
+
in_flight: int
|
|
80
|
+
admitted: int
|
|
81
|
+
shed: int
|
|
82
|
+
successes: int
|
|
83
|
+
drops: int
|
|
84
|
+
increases: int
|
|
85
|
+
decreases: int
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Permit:
|
|
89
|
+
"""One admitted call. Release it exactly once, or use it as a context manager.
|
|
90
|
+
|
|
91
|
+
As a context manager it measures the block: leaving it with an exception that
|
|
92
|
+
matches the limiter's `on` types counts as an overload signal, leaving it cleanly
|
|
93
|
+
counts as a success (unless the block was slower than `target_latency`), and any
|
|
94
|
+
other exception releases the slot without influencing the limit.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
__slots__ = ("_limiter", "_released", "_started", "priority")
|
|
98
|
+
|
|
99
|
+
def __init__(self, limiter: AdaptiveLimiter, started: float, priority: str) -> None:
|
|
100
|
+
self._limiter = limiter
|
|
101
|
+
self._started = started
|
|
102
|
+
self._released = False
|
|
103
|
+
self.priority = priority
|
|
104
|
+
|
|
105
|
+
def release(self, *, error: BaseException | None = None, ignore: bool = False) -> None:
|
|
106
|
+
"""Give the slot back and feed the outcome to the limiter.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
error: The exception the call ended with, if any.
|
|
110
|
+
ignore: Release without influencing the limit (e.g. a client error).
|
|
111
|
+
"""
|
|
112
|
+
if self._released:
|
|
113
|
+
return
|
|
114
|
+
self._released = True
|
|
115
|
+
self._limiter._finish(self._started, error, ignore)
|
|
116
|
+
|
|
117
|
+
def __enter__(self) -> Permit:
|
|
118
|
+
return self
|
|
119
|
+
|
|
120
|
+
def __exit__(
|
|
121
|
+
self,
|
|
122
|
+
exc_type: type[BaseException] | None,
|
|
123
|
+
exc: BaseException | None,
|
|
124
|
+
tb: TracebackType | None,
|
|
125
|
+
) -> None:
|
|
126
|
+
self.release(error=exc)
|
|
127
|
+
|
|
128
|
+
async def __aenter__(self) -> Permit:
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
async def __aexit__(
|
|
132
|
+
self,
|
|
133
|
+
exc_type: type[BaseException] | None,
|
|
134
|
+
exc: BaseException | None,
|
|
135
|
+
tb: TracebackType | None,
|
|
136
|
+
) -> None:
|
|
137
|
+
self.release(error=exc)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AdaptiveLimiter:
|
|
141
|
+
"""An AIMD concurrency limit that adapts to how the protected resource is doing.
|
|
142
|
+
|
|
143
|
+
Every call asks for a slot with `acquire()` (or goes through the decorator). If
|
|
144
|
+
`in_flight` is already at the limit the call is shed at once with `LoadShed`; no
|
|
145
|
+
queueing. Finished calls steer the limit:
|
|
146
|
+
|
|
147
|
+
* success (no error, and under `target_latency` when one is set): after `window`
|
|
148
|
+
successful samples (default: the current limit) the limit grows by `increase`;
|
|
149
|
+
* overload signal (an exception matching `on`, or a latency above `target_latency`):
|
|
150
|
+
the limit is multiplied by `backoff_ratio` and the sample count restarts.
|
|
151
|
+
|
|
152
|
+
Exceptions that do not match `on` (a validation error, say) release the slot and
|
|
153
|
+
leave the limit alone. A burst of overload signals compounds, so the limit drops
|
|
154
|
+
quickly; the floor is `min_limit`.
|
|
155
|
+
|
|
156
|
+
Thread-safe and usable from several event loops (it never blocks). Time comes from
|
|
157
|
+
`python_wrap._core.monotonic`, so `fake_clock` controls latency in tests.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
initial: Starting limit.
|
|
161
|
+
min_limit: Lowest the limit may fall to (>= 1).
|
|
162
|
+
max_limit: Highest the limit may rise to.
|
|
163
|
+
target_latency: Seconds above which a finished call counts as overload. `None`
|
|
164
|
+
judges by errors only.
|
|
165
|
+
backoff_ratio: Multiplier applied on overload, in (0, 1).
|
|
166
|
+
increase: Amount added after a full window of successes (> 0).
|
|
167
|
+
window: Successful samples needed per increase. `None` uses the current limit.
|
|
168
|
+
low_priority_share: Fraction of the limit at which `priority="low"` calls are
|
|
169
|
+
shed.
|
|
170
|
+
on: Exception types that signal overload.
|
|
171
|
+
name: Label for events and error messages.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
ValueError: An argument is out of range.
|
|
175
|
+
|
|
176
|
+
Example:
|
|
177
|
+
```python
|
|
178
|
+
from python_wrap.adaptive import AdaptiveLimiter, LoadShed
|
|
179
|
+
|
|
180
|
+
limiter = AdaptiveLimiter(initial=2, min_limit=1, max_limit=4, name="search")
|
|
181
|
+
|
|
182
|
+
@limiter
|
|
183
|
+
def search(q: str) -> str:
|
|
184
|
+
return q.upper()
|
|
185
|
+
|
|
186
|
+
assert search("a") == "A"
|
|
187
|
+
first = limiter.acquire()
|
|
188
|
+
second = limiter.acquire()
|
|
189
|
+
try:
|
|
190
|
+
limiter.acquire() # two calls are in flight: this one is shed
|
|
191
|
+
except LoadShed as shed:
|
|
192
|
+
assert shed.limit == 2
|
|
193
|
+
first.release(); second.release()
|
|
194
|
+
```
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
def __reduce__(self) -> NoReturn:
|
|
198
|
+
_core.refuse_pickle(self)
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
*,
|
|
203
|
+
initial: int = 10,
|
|
204
|
+
min_limit: int = 1,
|
|
205
|
+
max_limit: int = 200,
|
|
206
|
+
target_latency: float | None = None,
|
|
207
|
+
backoff_ratio: float = 0.9,
|
|
208
|
+
increase: float = 1,
|
|
209
|
+
window: int | None = None,
|
|
210
|
+
low_priority_share: float = 0.8,
|
|
211
|
+
on: tuple[type[BaseException], ...] = _DEFAULT_ON,
|
|
212
|
+
name: str | None = None,
|
|
213
|
+
) -> None:
|
|
214
|
+
if min_limit < 1:
|
|
215
|
+
raise ValueError(f"min_limit must be >= 1, got {min_limit}")
|
|
216
|
+
if max_limit < min_limit:
|
|
217
|
+
raise ValueError(f"max_limit must be >= min_limit, got {max_limit}")
|
|
218
|
+
if not min_limit <= initial <= max_limit:
|
|
219
|
+
raise ValueError(f"initial must be between {min_limit} and {max_limit}, got {initial}")
|
|
220
|
+
if target_latency is not None and target_latency <= 0:
|
|
221
|
+
raise ValueError(f"target_latency must be > 0 or None, got {target_latency}")
|
|
222
|
+
if not 0 < backoff_ratio < 1:
|
|
223
|
+
raise ValueError(f"backoff_ratio must be in (0, 1), got {backoff_ratio}")
|
|
224
|
+
if increase <= 0:
|
|
225
|
+
raise ValueError(f"increase must be > 0, got {increase}")
|
|
226
|
+
if window is not None and window < 1:
|
|
227
|
+
raise ValueError(f"window must be >= 1 or None, got {window}")
|
|
228
|
+
if not 0 < low_priority_share <= 1:
|
|
229
|
+
raise ValueError(f"low_priority_share must be in (0, 1], got {low_priority_share}")
|
|
230
|
+
self.min_limit = min_limit
|
|
231
|
+
self.max_limit = max_limit
|
|
232
|
+
self.target_latency = target_latency
|
|
233
|
+
self.backoff_ratio = backoff_ratio
|
|
234
|
+
self.increase = increase
|
|
235
|
+
self.window = window
|
|
236
|
+
self.low_priority_share = low_priority_share
|
|
237
|
+
self.on = tuple(on)
|
|
238
|
+
self.name = name
|
|
239
|
+
self._initial = initial
|
|
240
|
+
self._lock = _fork.ForkSafeLock()
|
|
241
|
+
self._reset_state()
|
|
242
|
+
_fork.register(self)
|
|
243
|
+
|
|
244
|
+
def _reset_state(self) -> None:
|
|
245
|
+
self._limit = float(self._initial)
|
|
246
|
+
self._in_flight = 0
|
|
247
|
+
self._samples = 0
|
|
248
|
+
self._admitted = 0
|
|
249
|
+
self._shed = 0
|
|
250
|
+
self._successes = 0
|
|
251
|
+
self._drops = 0
|
|
252
|
+
self._increases = 0
|
|
253
|
+
self._decreases = 0
|
|
254
|
+
|
|
255
|
+
def _reset_after_fork(self) -> None:
|
|
256
|
+
self._reset_state()
|
|
257
|
+
|
|
258
|
+
# -- introspection ------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def limit(self) -> int:
|
|
262
|
+
"""The current concurrency limit (whole calls)."""
|
|
263
|
+
with self._lock:
|
|
264
|
+
return self._whole()
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def in_flight(self) -> int:
|
|
268
|
+
"""Calls currently holding a slot."""
|
|
269
|
+
with self._lock:
|
|
270
|
+
return self._in_flight
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def stats(self) -> AdaptiveStats:
|
|
274
|
+
"""A consistent snapshot of the counters."""
|
|
275
|
+
with self._lock:
|
|
276
|
+
return AdaptiveStats(
|
|
277
|
+
limit=self._whole(),
|
|
278
|
+
in_flight=self._in_flight,
|
|
279
|
+
admitted=self._admitted,
|
|
280
|
+
shed=self._shed,
|
|
281
|
+
successes=self._successes,
|
|
282
|
+
drops=self._drops,
|
|
283
|
+
increases=self._increases,
|
|
284
|
+
decreases=self._decreases,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def __repr__(self) -> str:
|
|
288
|
+
return (
|
|
289
|
+
f"AdaptiveLimiter(name={self.name!r}, limit={self.limit}, in_flight={self.in_flight})"
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
def _whole(self) -> int:
|
|
293
|
+
return max(self.min_limit, int(self._limit))
|
|
294
|
+
|
|
295
|
+
def _label(self) -> str:
|
|
296
|
+
return self.name or "adaptive"
|
|
297
|
+
|
|
298
|
+
# -- admission ----------------------------------------------------------------------
|
|
299
|
+
|
|
300
|
+
def acquire(self, *, priority: Priority = "normal") -> Permit:
|
|
301
|
+
"""Take a slot now, or raise `LoadShed`. Never blocks.
|
|
302
|
+
|
|
303
|
+
`priority="low"` calls are shed once `in_flight >= limit * low_priority_share`;
|
|
304
|
+
`"normal"` and `"critical"` calls only at the full limit. Keep `"critical"` for
|
|
305
|
+
calls you would rather fail than drop (health checks, payments); it is the
|
|
306
|
+
label operators see in `LoadShed.priority` and in events.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
priority: `"low"`, `"normal"` or `"critical"`.
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
A `Permit`; call `release()` on it or use it in a `with` / `async with`.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
LoadShed: The limit (or the low-priority share of it) is reached.
|
|
316
|
+
ValueError: Unknown priority.
|
|
317
|
+
"""
|
|
318
|
+
if priority not in _PRIORITIES:
|
|
319
|
+
raise ValueError(f"priority must be one of {_PRIORITIES}, got {priority!r}")
|
|
320
|
+
with self._lock:
|
|
321
|
+
limit = self._whole()
|
|
322
|
+
threshold = (
|
|
323
|
+
max(1.0, limit * self.low_priority_share) if priority == "low" else float(limit)
|
|
324
|
+
)
|
|
325
|
+
in_flight = self._in_flight
|
|
326
|
+
shed = in_flight >= threshold
|
|
327
|
+
if shed:
|
|
328
|
+
self._shed += 1
|
|
329
|
+
else:
|
|
330
|
+
self._in_flight += 1
|
|
331
|
+
self._admitted += 1
|
|
332
|
+
if shed:
|
|
333
|
+
_core.emit("adaptive.shed", self._label(), limit=limit, in_flight=in_flight)
|
|
334
|
+
label = f"limiter {self.name!r}" if self.name else "limiter"
|
|
335
|
+
raise LoadShed(
|
|
336
|
+
f"{label} shed a {priority} call: {in_flight} in flight, limit {limit}",
|
|
337
|
+
name=self.name,
|
|
338
|
+
limit=limit,
|
|
339
|
+
in_flight=in_flight,
|
|
340
|
+
priority=priority,
|
|
341
|
+
)
|
|
342
|
+
return Permit(self, _core.monotonic(), priority)
|
|
343
|
+
|
|
344
|
+
def _finish(self, started: float, error: BaseException | None, ignore: bool) -> None:
|
|
345
|
+
latency = _core.monotonic() - started
|
|
346
|
+
overload = False
|
|
347
|
+
success = False
|
|
348
|
+
if not ignore:
|
|
349
|
+
if error is not None:
|
|
350
|
+
overload = isinstance(error, self.on)
|
|
351
|
+
elif self.target_latency is not None and latency > self.target_latency:
|
|
352
|
+
overload = True
|
|
353
|
+
else:
|
|
354
|
+
success = True
|
|
355
|
+
old = new = 0
|
|
356
|
+
with self._lock:
|
|
357
|
+
old = self._whole()
|
|
358
|
+
self._in_flight = max(0, self._in_flight - 1)
|
|
359
|
+
if overload:
|
|
360
|
+
self._drops += 1
|
|
361
|
+
self._samples = 0
|
|
362
|
+
self._limit = max(float(self.min_limit), self._limit * self.backoff_ratio)
|
|
363
|
+
if self._whole() < old:
|
|
364
|
+
self._decreases += 1
|
|
365
|
+
elif success:
|
|
366
|
+
self._successes += 1
|
|
367
|
+
self._samples += 1
|
|
368
|
+
needed = self.window if self.window is not None else old
|
|
369
|
+
if self._samples >= needed:
|
|
370
|
+
self._samples = 0
|
|
371
|
+
self._limit = min(float(self.max_limit), self._limit + self.increase)
|
|
372
|
+
if self._whole() > old:
|
|
373
|
+
self._increases += 1
|
|
374
|
+
new = self._whole()
|
|
375
|
+
if new != old:
|
|
376
|
+
_core.emit("adaptive.limit_changed", self._label(), old=old, new=new)
|
|
377
|
+
|
|
378
|
+
# -- decorator ----------------------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
def __call__(self, func: F, /) -> F:
|
|
381
|
+
"""Guard every call of `func` (sync or `async def`) at normal priority."""
|
|
382
|
+
return self.guard()(func)
|
|
383
|
+
|
|
384
|
+
def guard(self, *, priority: Priority = "normal") -> Callable[[F], F]:
|
|
385
|
+
"""A decorator guarding calls at a fixed `priority`.
|
|
386
|
+
|
|
387
|
+
Example:
|
|
388
|
+
```python
|
|
389
|
+
from python_wrap.adaptive import AdaptiveLimiter
|
|
390
|
+
|
|
391
|
+
limiter = AdaptiveLimiter(initial=5)
|
|
392
|
+
|
|
393
|
+
@limiter.guard(priority="low")
|
|
394
|
+
def report() -> int:
|
|
395
|
+
return 1
|
|
396
|
+
|
|
397
|
+
assert report() == 1
|
|
398
|
+
```
|
|
399
|
+
"""
|
|
400
|
+
if priority not in _PRIORITIES:
|
|
401
|
+
raise ValueError(f"priority must be one of {_PRIORITIES}, got {priority!r}")
|
|
402
|
+
|
|
403
|
+
def decorate(func: F) -> F:
|
|
404
|
+
if _core.is_async(func):
|
|
405
|
+
|
|
406
|
+
@functools.wraps(func)
|
|
407
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
408
|
+
async with self.acquire(priority=priority):
|
|
409
|
+
return await func(*args, **kwargs)
|
|
410
|
+
|
|
411
|
+
async_wrapper.__python_wrap_layer__ = ("adaptive", self) # type: ignore[attr-defined]
|
|
412
|
+
return cast(F, async_wrapper)
|
|
413
|
+
|
|
414
|
+
@functools.wraps(func)
|
|
415
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
416
|
+
with self.acquire(priority=priority):
|
|
417
|
+
return func(*args, **kwargs)
|
|
418
|
+
|
|
419
|
+
wrapper.__python_wrap_layer__ = ("adaptive", self) # type: ignore[attr-defined]
|
|
420
|
+
return cast(F, wrapper)
|
|
421
|
+
|
|
422
|
+
return decorate
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
# ------------------------------------------------------------------------- per key
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _busy(obj: Any) -> bool:
|
|
429
|
+
"""True if a pooled limiter has calls running (so it must not be evicted)."""
|
|
430
|
+
for attr in ("in_flight", "active"):
|
|
431
|
+
value = getattr(obj, attr, None)
|
|
432
|
+
if isinstance(value, int) and not isinstance(value, bool) and value > 0:
|
|
433
|
+
return True
|
|
434
|
+
return False
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
class PerKeyLimiter(Generic[L]):
|
|
438
|
+
"""A pool of limiters, one per key, created on first use.
|
|
439
|
+
|
|
440
|
+
Use it to give every tenant, user or upstream host its own limit so one noisy key
|
|
441
|
+
cannot starve the rest. Keys are kept in least-recently-used order; when more than
|
|
442
|
+
`max_keys` exist, the oldest *idle* ones (nothing in flight) are dropped, so memory
|
|
443
|
+
stays bounded. A dropped key simply starts fresh the next time it is seen.
|
|
444
|
+
|
|
445
|
+
Args:
|
|
446
|
+
factory: Called with the key to build its limiter, e.g.
|
|
447
|
+
`lambda key: Bulkhead(5, max_waiting=0)`.
|
|
448
|
+
max_keys: Most keys kept before idle ones are evicted (>= 1).
|
|
449
|
+
|
|
450
|
+
Raises:
|
|
451
|
+
ValueError: `max_keys` is below 1.
|
|
452
|
+
|
|
453
|
+
Example:
|
|
454
|
+
```python
|
|
455
|
+
from python_wrap.adaptive import AdaptiveLimiter, PerKeyLimiter
|
|
456
|
+
|
|
457
|
+
pool = PerKeyLimiter(lambda tenant: AdaptiveLimiter(initial=3), max_keys=100)
|
|
458
|
+
assert pool.get("acme") is pool.get("acme")
|
|
459
|
+
assert pool.get("acme") is not pool.get("globex")
|
|
460
|
+
assert len(pool) == 2
|
|
461
|
+
```
|
|
462
|
+
"""
|
|
463
|
+
|
|
464
|
+
def __init__(self, factory: Callable[[Hashable], L], *, max_keys: int = 10_000) -> None:
|
|
465
|
+
if max_keys < 1:
|
|
466
|
+
raise ValueError(f"max_keys must be >= 1, got {max_keys}")
|
|
467
|
+
self._factory = factory
|
|
468
|
+
self.max_keys = max_keys
|
|
469
|
+
self._items: OrderedDict[Hashable, L] = OrderedDict()
|
|
470
|
+
self._lock = _fork.ForkSafeLock()
|
|
471
|
+
_fork.register(self)
|
|
472
|
+
|
|
473
|
+
def __reduce__(self) -> NoReturn:
|
|
474
|
+
_core.refuse_pickle(self)
|
|
475
|
+
|
|
476
|
+
def _reset_after_fork(self) -> None:
|
|
477
|
+
self._items.clear()
|
|
478
|
+
|
|
479
|
+
def get(self, key: Hashable) -> L:
|
|
480
|
+
"""The limiter for `key`, created if needed and marked most recently used."""
|
|
481
|
+
with self._lock:
|
|
482
|
+
item = self._items.get(key)
|
|
483
|
+
if item is not None:
|
|
484
|
+
self._items.move_to_end(key)
|
|
485
|
+
return item
|
|
486
|
+
item = self._factory(key)
|
|
487
|
+
self._items[key] = item
|
|
488
|
+
self._evict()
|
|
489
|
+
return item
|
|
490
|
+
|
|
491
|
+
def _evict(self) -> None:
|
|
492
|
+
if len(self._items) <= self.max_keys:
|
|
493
|
+
return
|
|
494
|
+
for key in list(self._items):
|
|
495
|
+
if len(self._items) <= self.max_keys:
|
|
496
|
+
break
|
|
497
|
+
if not _busy(self._items[key]):
|
|
498
|
+
del self._items[key]
|
|
499
|
+
|
|
500
|
+
def discard(self, key: Hashable) -> bool:
|
|
501
|
+
"""Forget `key`. Returns True if it existed."""
|
|
502
|
+
with self._lock:
|
|
503
|
+
return self._items.pop(key, None) is not None
|
|
504
|
+
|
|
505
|
+
def clear(self) -> None:
|
|
506
|
+
"""Forget every key."""
|
|
507
|
+
with self._lock:
|
|
508
|
+
self._items.clear()
|
|
509
|
+
|
|
510
|
+
def keys(self) -> list[Hashable]:
|
|
511
|
+
"""Current keys, least recently used first."""
|
|
512
|
+
with self._lock:
|
|
513
|
+
return list(self._items)
|
|
514
|
+
|
|
515
|
+
def __len__(self) -> int:
|
|
516
|
+
with self._lock:
|
|
517
|
+
return len(self._items)
|
|
518
|
+
|
|
519
|
+
def __contains__(self, key: object) -> bool:
|
|
520
|
+
with self._lock:
|
|
521
|
+
return key in self._items
|
|
522
|
+
|
|
523
|
+
def __getitem__(self, key: Hashable) -> L:
|
|
524
|
+
return self.get(key)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
class _Slot:
|
|
528
|
+
"""A key's limiter plus the function wrapped by it."""
|
|
529
|
+
|
|
530
|
+
__slots__ = ("limiter", "wrapped")
|
|
531
|
+
|
|
532
|
+
def __init__(self, limiter: Any, wrapped: Callable[..., Any]) -> None:
|
|
533
|
+
self.limiter = limiter
|
|
534
|
+
self.wrapped = wrapped
|
|
535
|
+
|
|
536
|
+
@property
|
|
537
|
+
def in_flight(self) -> int:
|
|
538
|
+
return 1 if _busy(self.limiter) else 0
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def per_key(
|
|
542
|
+
limiter_factory: Callable[[Hashable], Any],
|
|
543
|
+
*,
|
|
544
|
+
key: Callable[..., Hashable],
|
|
545
|
+
max_keys: int = 10_000,
|
|
546
|
+
) -> Callable[[F], F]:
|
|
547
|
+
"""Apply a separate limiter to each distinct key of the call.
|
|
548
|
+
|
|
549
|
+
`limiter_factory(key)` must return something that works as a decorator, which is
|
|
550
|
+
true of `Bulkhead`, `AdaptiveLimiter` and `RateLimiter`. The decorated function
|
|
551
|
+
keeps its sync or async nature. The pool is bounded and LRU-evicted like
|
|
552
|
+
`PerKeyLimiter`; the pool is reachable as `wrapped.limiters`.
|
|
553
|
+
|
|
554
|
+
(`rate_limit(..., key=...)` and `RateLimiter` already split their window per key
|
|
555
|
+
themselves; use `per_key` for bulkheads and adaptive limiters, or when each key
|
|
556
|
+
needs a different configuration.)
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
limiter_factory: Builds the limiter for a key.
|
|
560
|
+
key: Called with the call's arguments; returns the hashable key.
|
|
561
|
+
max_keys: Most keys kept before idle ones are evicted.
|
|
562
|
+
|
|
563
|
+
Returns:
|
|
564
|
+
A decorator.
|
|
565
|
+
|
|
566
|
+
Example:
|
|
567
|
+
```python
|
|
568
|
+
from python_wrap.adaptive import per_key
|
|
569
|
+
from python_wrap.bulkhead import Bulkhead
|
|
570
|
+
|
|
571
|
+
@per_key(lambda tenant: Bulkhead(2, max_waiting=0), key=lambda tenant, **_: tenant)
|
|
572
|
+
def handle(tenant: str) -> str:
|
|
573
|
+
return tenant
|
|
574
|
+
|
|
575
|
+
assert handle("acme") == "acme"
|
|
576
|
+
assert "acme" in handle.limiters # type: ignore[attr-defined]
|
|
577
|
+
```
|
|
578
|
+
"""
|
|
579
|
+
|
|
580
|
+
def decorate(func: F) -> F:
|
|
581
|
+
def make(k: Hashable) -> _Slot:
|
|
582
|
+
limiter = limiter_factory(k)
|
|
583
|
+
return _Slot(limiter, limiter(func))
|
|
584
|
+
|
|
585
|
+
pool: PerKeyLimiter[_Slot] = PerKeyLimiter(make, max_keys=max_keys)
|
|
586
|
+
|
|
587
|
+
if _core.is_async(func):
|
|
588
|
+
|
|
589
|
+
@functools.wraps(func)
|
|
590
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
591
|
+
slot = pool.get(key(*args, **kwargs))
|
|
592
|
+
return await slot.wrapped(*args, **kwargs)
|
|
593
|
+
|
|
594
|
+
async_wrapper.limiters = pool # type: ignore[attr-defined]
|
|
595
|
+
return cast(F, async_wrapper)
|
|
596
|
+
|
|
597
|
+
@functools.wraps(func)
|
|
598
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
599
|
+
slot = pool.get(key(*args, **kwargs))
|
|
600
|
+
return slot.wrapped(*args, **kwargs)
|
|
601
|
+
|
|
602
|
+
wrapper.limiters = pool # type: ignore[attr-defined]
|
|
603
|
+
return cast(F, wrapper)
|
|
604
|
+
|
|
605
|
+
return decorate
|