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/shared.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
"""Redis coordination backends for circuit breakers and bulkheads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextvars
|
|
7
|
+
import hashlib
|
|
8
|
+
import math
|
|
9
|
+
import threading
|
|
10
|
+
import uuid
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from python_wrap import _core, _fork
|
|
15
|
+
from python_wrap._backend import BackendMonitor
|
|
16
|
+
from python_wrap._runtime import digest, seconds
|
|
17
|
+
from python_wrap.coordination import AlreadyRunning, Lease
|
|
18
|
+
from python_wrap.errors import BulkheadFull
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AsyncRedisBreakerState",
|
|
22
|
+
"RedisBreakerState",
|
|
23
|
+
"RedisRetryBudget",
|
|
24
|
+
"SharedBackends",
|
|
25
|
+
"SharedBulkhead",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
_BREAKER = """
|
|
29
|
+
local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000)
|
|
30
|
+
local op=ARGV[1]; local threshold=tonumber(ARGV[2]); local window=tonumber(ARGV[3])
|
|
31
|
+
local reset=tonumber(ARGV[4]); local halfmax=tonumber(ARGV[5]); local target=tonumber(ARGV[6])
|
|
32
|
+
local n=tonumber(ARGV[10] or '1'); local frate=tonumber(ARGV[11] or '0')
|
|
33
|
+
local srate=tonumber(ARGV[12] or '0'); local minc=tonumber(ARGV[13] or '1')
|
|
34
|
+
local slow=tonumber(ARGV[14] or '0'); local rated=frate>0 or srate>0
|
|
35
|
+
local gen=tonumber(redis.call('HGET',KEYS[1],'gen') or '0')
|
|
36
|
+
local state=redis.call('HGET',KEYS[1],'state') or 'closed'; local old=state
|
|
37
|
+
local opened=tonumber(redis.call('HGET',KEYS[1],'opened') or '0')
|
|
38
|
+
local failures=tonumber(redis.call('HGET',KEYS[1],'failures') or '0')
|
|
39
|
+
local trials=tonumber(redis.call('HGET',KEYS[1],'trials') or '0')
|
|
40
|
+
local successes=tonumber(redis.call('HGET',KEYS[1],'successes') or '0')
|
|
41
|
+
local admitted=1; local trial=0; local wait=0; local trip=false
|
|
42
|
+
local wc,wf,ws=0,0,0
|
|
43
|
+
-- Calls, failures and slow calls in window, in ten slots of one hash (KEYS[3]).
|
|
44
|
+
local function slots(ac,af,as)
|
|
45
|
+
local width=math.max(1,math.floor(window/10)); local epoch=math.floor(now/width)
|
|
46
|
+
if ac>0 then redis.call('HINCRBY',KEYS[3],'c:'..epoch,ac)
|
|
47
|
+
if af>0 then redis.call('HINCRBY',KEYS[3],'f:'..epoch,af) end
|
|
48
|
+
if as>0 then redis.call('HINCRBY',KEYS[3],'s:'..epoch,as) end
|
|
49
|
+
redis.call('PEXPIRE',KEYS[3],window*2) end
|
|
50
|
+
local c,f,s=0,0,0
|
|
51
|
+
local all=redis.call('HGETALL',KEYS[3])
|
|
52
|
+
for i=1,#all,2 do
|
|
53
|
+
local field=all[i]; local e=tonumber(string.sub(field,3))
|
|
54
|
+
if e<=epoch-10 then redis.call('HDEL',KEYS[3],field)
|
|
55
|
+
else local v=tonumber(all[i+1]); local k=string.sub(field,1,1)
|
|
56
|
+
if k=='c' then c=c+v elseif k=='f' then f=f+v else s=s+v end end
|
|
57
|
+
end
|
|
58
|
+
return c,f,s
|
|
59
|
+
end
|
|
60
|
+
local function trips()
|
|
61
|
+
if wc<minc then return false end
|
|
62
|
+
return (frate>0 and wf>=frate*wc) or (srate>0 and ws>=srate*wc)
|
|
63
|
+
end
|
|
64
|
+
if op=='reset' then
|
|
65
|
+
state='closed'; failures=0; trials=0; successes=0; opened=0; gen=gen+1
|
|
66
|
+
redis.call('DEL',KEYS[2],KEYS[3])
|
|
67
|
+
redis.call('HSET',KEYS[1],'total_failures',0,'total_successes',0,'total_rejected',0)
|
|
68
|
+
elseif op=='force_open' then state='open'; opened=now; trials=0; gen=gen+1
|
|
69
|
+
else
|
|
70
|
+
if state=='open' and now-opened>=reset then
|
|
71
|
+
state='half_open'; gen=gen+1; trials=0; successes=0
|
|
72
|
+
redis.call('HSET',KEYS[1],'trial_deadline',now+math.max(1000,reset))
|
|
73
|
+
end
|
|
74
|
+
if op=='admit' then
|
|
75
|
+
if state=='half_open' then
|
|
76
|
+
local deadline=tonumber(redis.call('HGET',KEYS[1],'trial_deadline') or '0')
|
|
77
|
+
if now>=deadline then gen=gen+1; trials=0; successes=0
|
|
78
|
+
redis.call('HSET',KEYS[1],'trial_deadline',now+math.max(1000,reset)) end
|
|
79
|
+
end
|
|
80
|
+
if state=='open' or (state=='half_open' and trials>=halfmax) then
|
|
81
|
+
admitted=0; wait=math.max(0,opened+reset-now)
|
|
82
|
+
redis.call('HINCRBY',KEYS[1],'total_rejected',1)
|
|
83
|
+
elseif state=='half_open' then trial=1; trials=trials+1 end
|
|
84
|
+
elseif (op=='success' or op=='failure' or op=='neutral') and tonumber(ARGV[7])==gen then
|
|
85
|
+
local is_trial=tonumber(ARGV[8])==1
|
|
86
|
+
if is_trial then trials=math.max(0,trials-1) end
|
|
87
|
+
if op=='success' then
|
|
88
|
+
redis.call('HINCRBY',KEYS[1],'total_successes',n)
|
|
89
|
+
if state=='half_open' then
|
|
90
|
+
if slow==1 and srate>0 then trip=true
|
|
91
|
+
else
|
|
92
|
+
successes=successes+n
|
|
93
|
+
if successes>=target then state='closed'; gen=gen+1; failures=0
|
|
94
|
+
redis.call('DEL',KEYS[2],KEYS[3]) end
|
|
95
|
+
end
|
|
96
|
+
else
|
|
97
|
+
if window==0 then failures=0 end
|
|
98
|
+
if rated and not is_trial then wc,wf,ws=slots(n,0,slow*n); trip=trips() end
|
|
99
|
+
end
|
|
100
|
+
elseif op=='failure' then
|
|
101
|
+
redis.call('HINCRBY',KEYS[1],'total_failures',1)
|
|
102
|
+
if rated and not is_trial and state~='half_open' then
|
|
103
|
+
wc,wf,ws=slots(1,1,slow); trip=trips()
|
|
104
|
+
end
|
|
105
|
+
if frate>0 then failures=wf
|
|
106
|
+
elseif window>0 then
|
|
107
|
+
redis.call('ZREMRANGEBYSCORE',KEYS[2],'-inf',now-window)
|
|
108
|
+
redis.call('ZADD',KEYS[2],now,ARGV[9]); failures=redis.call('ZCARD',KEYS[2])
|
|
109
|
+
redis.call('PEXPIRE',KEYS[2],window)
|
|
110
|
+
else failures=failures+1 end
|
|
111
|
+
if state=='half_open' or (frate==0 and failures>=threshold) then trip=true end
|
|
112
|
+
end
|
|
113
|
+
if trip then state='open'; opened=now; trials=0; successes=0; gen=gen+1 end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
if rated and wc==0 then wc,wf,ws=slots(0,0,0) end
|
|
117
|
+
redis.call('HSET',KEYS[1],'state',state,'gen',gen,'opened',opened,'failures',failures,
|
|
118
|
+
'trials',trials,'successes',successes)
|
|
119
|
+
return {admitted,state,gen,trial,wait,failures,
|
|
120
|
+
redis.call('HGET',KEYS[1],'total_failures') or '0',
|
|
121
|
+
redis.call('HGET',KEYS[1],'total_successes') or '0',
|
|
122
|
+
redis.call('HGET',KEYS[1],'total_rejected') or '0',opened,old,wc,wf,ws}
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_BREAKER_SHA = hashlib.sha1(_BREAKER.encode(), usedforsecurity=False).hexdigest() # Redis script id
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _no_script(exc: Exception) -> bool:
|
|
130
|
+
"""True for Redis's NOSCRIPT reply (redis-py: NoScriptError, "No matching script")."""
|
|
131
|
+
text = str(exc)
|
|
132
|
+
return type(exc).__name__ == "NoScriptError" or "NOSCRIPT" in text or "No matching" in text
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
_BUDGET = """
|
|
136
|
+
local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000)
|
|
137
|
+
local width=tonumber(ARGV[2]); local epoch=math.floor(now/width)
|
|
138
|
+
local op=ARGV[1]
|
|
139
|
+
if op=='deposit' then
|
|
140
|
+
redis.call('HINCRBY',KEYS[1],'r:'..epoch,1); redis.call('PEXPIRE',KEYS[1],width*12); return 1
|
|
141
|
+
end
|
|
142
|
+
local req,ret=0,0
|
|
143
|
+
local all=redis.call('HGETALL',KEYS[1])
|
|
144
|
+
for i=1,#all,2 do
|
|
145
|
+
local f=all[i]; local e=tonumber(string.sub(f,3))
|
|
146
|
+
if e<=epoch-10 then redis.call('HDEL',KEYS[1],f)
|
|
147
|
+
elseif string.sub(f,1,1)=='r' then req=req+tonumber(all[i+1])
|
|
148
|
+
else ret=ret+tonumber(all[i+1]) end
|
|
149
|
+
end
|
|
150
|
+
if op=='totals' then return {req,ret} end
|
|
151
|
+
if tonumber(ARGV[3])*req+tonumber(ARGV[4])-ret>=1 then
|
|
152
|
+
redis.call('HINCRBY',KEYS[1],'t:'..epoch,1); redis.call('PEXPIRE',KEYS[1],width*12); return 1
|
|
153
|
+
end
|
|
154
|
+
return 0
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class RedisRetryBudget:
|
|
159
|
+
"""A `RetryBudget` backend that counts requests and retries in Redis.
|
|
160
|
+
|
|
161
|
+
Two counters per time slot live in one hash and one Lua script updates them on the
|
|
162
|
+
Redis clock, so every process (and host) draws on one allowance. Keys come from
|
|
163
|
+
``name``: two services that use the same name share a budget on purpose. Pass it as
|
|
164
|
+
``RetryBudget(..., backend=RedisRetryBudget(client, "vendor"))``.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
client: Any,
|
|
170
|
+
name: str,
|
|
171
|
+
*,
|
|
172
|
+
prefix: str = "python-wrap:budget:",
|
|
173
|
+
on_backend_error: str | None = None,
|
|
174
|
+
retry_backend_after: float = 1.0,
|
|
175
|
+
) -> None:
|
|
176
|
+
if not name:
|
|
177
|
+
raise ValueError("a shared retry budget needs a name")
|
|
178
|
+
self.client, self.name = client, name
|
|
179
|
+
self.key = prefix + "{" + digest(name) + "}"
|
|
180
|
+
self._monitor = BackendMonitor("budget", name, on_backend_error, retry_backend_after)
|
|
181
|
+
|
|
182
|
+
def _eval(self, budget: Any, op: str) -> Any:
|
|
183
|
+
width = max(1, math.ceil(budget.window * 1000 / 10))
|
|
184
|
+
return self.client.eval(_BUDGET, 1, self.key, op, width, budget.ratio, budget._reserve)
|
|
185
|
+
|
|
186
|
+
def deposit(self, budget: Any) -> None:
|
|
187
|
+
self._monitor.call("deposit", lambda: self._eval(budget, "deposit"), budget._deposit_local)
|
|
188
|
+
|
|
189
|
+
def try_withdraw(self, budget: Any) -> bool:
|
|
190
|
+
def fallback() -> bool:
|
|
191
|
+
return budget._withdraw_local() if self._monitor.mode == "local" else True
|
|
192
|
+
|
|
193
|
+
return bool(
|
|
194
|
+
self._monitor.call(
|
|
195
|
+
"withdraw", lambda: int(self._eval(budget, "withdraw")) == 1, fallback
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def totals(self, budget: Any) -> tuple[int, int]:
|
|
200
|
+
def local() -> tuple[int, int]:
|
|
201
|
+
with budget._lock:
|
|
202
|
+
totals: tuple[int, int] = budget._totals(budget._slot()[1])
|
|
203
|
+
return totals
|
|
204
|
+
|
|
205
|
+
row = self._monitor.call("totals", lambda: self._eval(budget, "totals"), local)
|
|
206
|
+
return int(row[0]), int(row[1])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class RedisBreakerState:
|
|
210
|
+
"""Atomic Redis breaker state, window failures and bounded half-open trial leases.
|
|
211
|
+
|
|
212
|
+
Use the same name and settings in every process. Keys share a Redis Cluster hash
|
|
213
|
+
tag. Backend errors reach the breaker, which applies its ``on_backend_error``; they
|
|
214
|
+
are never read as a healthy dependency. Half-open reservations expire after
|
|
215
|
+
recovery_timeout (minimum one second), so a crashed probing worker cannot
|
|
216
|
+
permanently consume the trial slot.
|
|
217
|
+
|
|
218
|
+
A closed state read from the store is trusted for ``state_ttl`` seconds: during that
|
|
219
|
+
time calls are admitted without a round trip, successes are counted locally and sent
|
|
220
|
+
in one batch every ``flush_interval`` seconds or ``flush_every`` calls, and the
|
|
221
|
+
breaker's ``state``/``stats`` come from the cached answer. Failures, half-open trials
|
|
222
|
+
and admin calls always go to the store. The trade: a process may keep admitting calls
|
|
223
|
+
for up to ``state_ttl`` after another process opened the breaker. ``state_ttl=0``
|
|
224
|
+
sends every call to the store. The script runs with ``EVALSHA`` and is loaded again
|
|
225
|
+
on ``NOSCRIPT``.
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
def __init__(
|
|
229
|
+
self,
|
|
230
|
+
client: Any,
|
|
231
|
+
prefix: str = "python-wrap:breaker:",
|
|
232
|
+
*,
|
|
233
|
+
state_ttl: float = 1.0,
|
|
234
|
+
flush_interval: float = 1.0,
|
|
235
|
+
flush_every: int = 1000,
|
|
236
|
+
) -> None:
|
|
237
|
+
if not prefix:
|
|
238
|
+
raise ValueError("prefix must not be empty")
|
|
239
|
+
if not math.isfinite(state_ttl) or state_ttl < 0:
|
|
240
|
+
raise ValueError("state_ttl must be >= 0")
|
|
241
|
+
if not math.isfinite(flush_interval) or flush_interval < 0:
|
|
242
|
+
raise ValueError("flush_interval must be >= 0")
|
|
243
|
+
if isinstance(flush_every, bool) or not isinstance(flush_every, int) or flush_every < 1:
|
|
244
|
+
raise ValueError("flush_every must be a positive integer")
|
|
245
|
+
self.client, self.prefix = client, prefix
|
|
246
|
+
self.state_ttl, self.flush_interval, self.flush_every = (
|
|
247
|
+
state_ttl,
|
|
248
|
+
flush_interval,
|
|
249
|
+
flush_every,
|
|
250
|
+
)
|
|
251
|
+
# breaker name -> [last closed answer, read at, pending successes, last flush]
|
|
252
|
+
self._cache: dict[str, list[Any]] = {}
|
|
253
|
+
self._lock = _fork.ForkSafeLock()
|
|
254
|
+
_fork.register(self)
|
|
255
|
+
|
|
256
|
+
def _reset_after_fork(self) -> None:
|
|
257
|
+
self._cache.clear()
|
|
258
|
+
|
|
259
|
+
def _local(
|
|
260
|
+
self, breaker: Any, operation: str, trial: bool, slow: bool = False
|
|
261
|
+
) -> tuple[Any, int, int]:
|
|
262
|
+
"""``(answer or None, successes to flush, their generation)`` from the cache."""
|
|
263
|
+
if self.state_ttl == 0 or trial or slow: # a slow call can open a rated breaker
|
|
264
|
+
return None, 0, 0
|
|
265
|
+
now = _core.monotonic()
|
|
266
|
+
with self._lock:
|
|
267
|
+
entry = self._cache.get(breaker.name)
|
|
268
|
+
if entry is None:
|
|
269
|
+
return None, 0, 0
|
|
270
|
+
data, read_at, pending, flushed = entry
|
|
271
|
+
generation = data["generation"]
|
|
272
|
+
if operation in {"failure", "reset", "force_open"} or now - read_at >= self.state_ttl:
|
|
273
|
+
# The store answers; a failure (or a refresh) carries batched successes first.
|
|
274
|
+
entry[2], entry[3] = 0, now
|
|
275
|
+
return None, 0 if operation in {"reset", "force_open"} else pending, generation
|
|
276
|
+
if operation == "success":
|
|
277
|
+
pending += 1
|
|
278
|
+
if pending >= self.flush_every or now - flushed >= self.flush_interval:
|
|
279
|
+
entry[2], entry[3] = 0, now
|
|
280
|
+
return dict(data, old=data["state"]), pending, generation
|
|
281
|
+
entry[2] = pending
|
|
282
|
+
answer = dict(data, admitted=1, trial=0, wait=0, old=data["state"])
|
|
283
|
+
answer["total_successes"] = data["total_successes"] + entry[2]
|
|
284
|
+
return answer, 0, 0
|
|
285
|
+
|
|
286
|
+
def _remember(self, breaker: Any, data: dict[str, Any]) -> dict[str, Any]:
|
|
287
|
+
if self.state_ttl:
|
|
288
|
+
with self._lock:
|
|
289
|
+
if data["state"] == "closed":
|
|
290
|
+
old = self._cache.get(breaker.name)
|
|
291
|
+
pending, flushed = (old[2], old[3]) if old else (0, _core.monotonic())
|
|
292
|
+
self._cache[breaker.name] = [data, _core.monotonic(), pending, flushed]
|
|
293
|
+
else:
|
|
294
|
+
self._cache.pop(breaker.name, None)
|
|
295
|
+
return data
|
|
296
|
+
|
|
297
|
+
def _call(self, args: tuple[Any, ...]) -> Any:
|
|
298
|
+
evalsha = getattr(self.client, "evalsha", None)
|
|
299
|
+
if evalsha is None:
|
|
300
|
+
return self.client.eval(_BREAKER, *args)
|
|
301
|
+
try:
|
|
302
|
+
return evalsha(_BREAKER_SHA, *args)
|
|
303
|
+
except Exception as exc:
|
|
304
|
+
if not _no_script(exc):
|
|
305
|
+
raise
|
|
306
|
+
return self.client.eval(_BREAKER, *args)
|
|
307
|
+
|
|
308
|
+
def operate(
|
|
309
|
+
self,
|
|
310
|
+
breaker: Any,
|
|
311
|
+
operation: str,
|
|
312
|
+
generation: int = 0,
|
|
313
|
+
trial: bool = False,
|
|
314
|
+
slow: bool = False,
|
|
315
|
+
) -> dict[str, Any]:
|
|
316
|
+
data, flush, flush_gen = self._local(breaker, operation, trial, slow)
|
|
317
|
+
if flush:
|
|
318
|
+
self._remember(
|
|
319
|
+
breaker,
|
|
320
|
+
self._parse(self._call(self._args(breaker, "success", flush_gen, False, flush))),
|
|
321
|
+
)
|
|
322
|
+
if data is not None:
|
|
323
|
+
return data # type: ignore[no-any-return]
|
|
324
|
+
row = self._call(self._args(breaker, operation, generation, trial, 1, slow))
|
|
325
|
+
return self._remember(breaker, self._parse(row))
|
|
326
|
+
|
|
327
|
+
def _args(
|
|
328
|
+
self,
|
|
329
|
+
breaker: Any,
|
|
330
|
+
operation: str,
|
|
331
|
+
generation: int,
|
|
332
|
+
trial: bool,
|
|
333
|
+
count: int = 1,
|
|
334
|
+
slow: bool = False,
|
|
335
|
+
) -> tuple[Any, ...]:
|
|
336
|
+
key = self.prefix + "{" + digest(breaker.name) + "}"
|
|
337
|
+
return (
|
|
338
|
+
3,
|
|
339
|
+
key,
|
|
340
|
+
key + ":failures",
|
|
341
|
+
key + ":slots",
|
|
342
|
+
operation,
|
|
343
|
+
breaker.failure_threshold,
|
|
344
|
+
0 if breaker.window is None else max(1, math.ceil(breaker.window * 1000)),
|
|
345
|
+
math.ceil(breaker.recovery_timeout * 1000),
|
|
346
|
+
breaker.half_open_max_calls,
|
|
347
|
+
breaker.success_threshold,
|
|
348
|
+
generation,
|
|
349
|
+
int(trial),
|
|
350
|
+
uuid.uuid4().hex,
|
|
351
|
+
count,
|
|
352
|
+
getattr(breaker, "failure_rate", None) or 0,
|
|
353
|
+
getattr(breaker, "slow_call_rate", None) or 0,
|
|
354
|
+
getattr(breaker, "minimum_calls", 1),
|
|
355
|
+
int(slow),
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
@staticmethod
|
|
359
|
+
def _parse(row: Any) -> dict[str, Any]:
|
|
360
|
+
keys = (
|
|
361
|
+
"admitted",
|
|
362
|
+
"state",
|
|
363
|
+
"generation",
|
|
364
|
+
"trial",
|
|
365
|
+
"wait",
|
|
366
|
+
"failures",
|
|
367
|
+
"total_failures",
|
|
368
|
+
"total_successes",
|
|
369
|
+
"total_rejected",
|
|
370
|
+
"opened",
|
|
371
|
+
"old",
|
|
372
|
+
"window_calls",
|
|
373
|
+
"window_failures",
|
|
374
|
+
"window_slow",
|
|
375
|
+
)
|
|
376
|
+
row = [*row, *[0] * (len(keys) - len(row))] # scripts before 0.4.0b2 sent 11 values
|
|
377
|
+
values = [value.decode() if isinstance(value, bytes) else value for value in row]
|
|
378
|
+
data = dict(zip(keys, values, strict=True))
|
|
379
|
+
for name in keys:
|
|
380
|
+
if name not in {"state", "old"}:
|
|
381
|
+
data[name] = int(data[name])
|
|
382
|
+
return data
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class AsyncRedisBreakerState(RedisBreakerState):
|
|
386
|
+
"""`RedisBreakerState` for ``redis.asyncio`` clients: ``operate`` is awaited.
|
|
387
|
+
|
|
388
|
+
Same Lua script and keys, so sync and async processes share one breaker. A breaker
|
|
389
|
+
with this backend protects ``async def`` functions only; its sync ``state`` and
|
|
390
|
+
``stats`` report the last state the store returned in this process.
|
|
391
|
+
"""
|
|
392
|
+
|
|
393
|
+
async def _acall(self, args: tuple[Any, ...]) -> Any:
|
|
394
|
+
evalsha = getattr(self.client, "evalsha", None)
|
|
395
|
+
if evalsha is None:
|
|
396
|
+
return await self.client.eval(_BREAKER, *args)
|
|
397
|
+
try:
|
|
398
|
+
return await evalsha(_BREAKER_SHA, *args)
|
|
399
|
+
except Exception as exc:
|
|
400
|
+
if not _no_script(exc):
|
|
401
|
+
raise
|
|
402
|
+
return await self.client.eval(_BREAKER, *args)
|
|
403
|
+
|
|
404
|
+
async def operate( # type: ignore[override]
|
|
405
|
+
self,
|
|
406
|
+
breaker: Any,
|
|
407
|
+
operation: str,
|
|
408
|
+
generation: int = 0,
|
|
409
|
+
trial: bool = False,
|
|
410
|
+
slow: bool = False,
|
|
411
|
+
) -> dict[str, Any]:
|
|
412
|
+
data, flush, flush_gen = self._local(breaker, operation, trial, slow)
|
|
413
|
+
if flush:
|
|
414
|
+
row = await self._acall(self._args(breaker, "success", flush_gen, False, flush))
|
|
415
|
+
self._remember(breaker, self._parse(row))
|
|
416
|
+
if data is not None:
|
|
417
|
+
return data # type: ignore[no-any-return]
|
|
418
|
+
row = await self._acall(self._args(breaker, operation, generation, trial, 1, slow))
|
|
419
|
+
return self._remember(breaker, self._parse(row))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class SharedBulkhead:
|
|
423
|
+
"""Renewable lease-backed concurrency cap; max_waiting is a per-process queue bound."""
|
|
424
|
+
|
|
425
|
+
def __init__(
|
|
426
|
+
self,
|
|
427
|
+
max_concurrent: int,
|
|
428
|
+
*,
|
|
429
|
+
backend: Any,
|
|
430
|
+
name: str,
|
|
431
|
+
max_waiting: int | None = None,
|
|
432
|
+
timeout: float | None = None,
|
|
433
|
+
ttl: float = 60,
|
|
434
|
+
on_backend_error: str | None = None,
|
|
435
|
+
retry_backend_after: float = 1.0,
|
|
436
|
+
) -> None:
|
|
437
|
+
if (
|
|
438
|
+
isinstance(max_concurrent, bool)
|
|
439
|
+
or not isinstance(max_concurrent, int)
|
|
440
|
+
or max_concurrent < 1
|
|
441
|
+
):
|
|
442
|
+
raise ValueError("max_concurrent must be a positive integer")
|
|
443
|
+
if max_waiting is not None and (
|
|
444
|
+
isinstance(max_waiting, bool) or not isinstance(max_waiting, int) or max_waiting < 0
|
|
445
|
+
):
|
|
446
|
+
raise ValueError("max_waiting must be a nonnegative integer")
|
|
447
|
+
if not name:
|
|
448
|
+
raise ValueError("shared bulkheads require an explicit name")
|
|
449
|
+
self.capacity, self.backend, self.name = max_concurrent, backend, name
|
|
450
|
+
self.max_waiting = max_waiting
|
|
451
|
+
self.timeout = None if timeout is None else seconds(timeout, positive=False)
|
|
452
|
+
self.ttl = seconds(ttl)
|
|
453
|
+
self._monitor = BackendMonitor("bulkhead", name, on_backend_error, retry_backend_after)
|
|
454
|
+
acquire = getattr(backend, "acquire", None)
|
|
455
|
+
self._async = acquire is not None and _core.is_async(acquire)
|
|
456
|
+
self._stack: contextvars.ContextVar[tuple[tuple[Lease, object], ...]] = (
|
|
457
|
+
contextvars.ContextVar("bulkhead_leases", default=())
|
|
458
|
+
)
|
|
459
|
+
self._lock = _fork.ForkSafeLock()
|
|
460
|
+
self._waiting = self._active = 0
|
|
461
|
+
_fork.register(self)
|
|
462
|
+
|
|
463
|
+
def _reset_after_fork(self) -> None:
|
|
464
|
+
self._waiting = self._active = 0
|
|
465
|
+
self._stack.set(())
|
|
466
|
+
|
|
467
|
+
@property
|
|
468
|
+
def waiting(self) -> int:
|
|
469
|
+
with self._lock:
|
|
470
|
+
return self._waiting
|
|
471
|
+
|
|
472
|
+
@property
|
|
473
|
+
def active(self) -> int:
|
|
474
|
+
"""Active calls in this process (the backend enforces the global limit)."""
|
|
475
|
+
with self._lock:
|
|
476
|
+
return self._active
|
|
477
|
+
|
|
478
|
+
def _store_down(self, exc: Exception) -> None:
|
|
479
|
+
"""Apply on_backend_error to a failed lease call (re-raise in "raise" mode)."""
|
|
480
|
+
self._monitor.failed(exc, "acquire")
|
|
481
|
+
if self._monitor.mode == "raise":
|
|
482
|
+
raise exc
|
|
483
|
+
|
|
484
|
+
def _local_admit(self, owner: object) -> None:
|
|
485
|
+
"""Store is down: "allow" admits; "local" admits up to this process's capacity."""
|
|
486
|
+
if self._monitor.mode == "local" and self.active >= self.capacity:
|
|
487
|
+
raise self._rejected("shared bulkhead full (local fallback)")
|
|
488
|
+
self._admitted(None, owner) # type: ignore[arg-type]
|
|
489
|
+
|
|
490
|
+
def _lease(self) -> Lease:
|
|
491
|
+
return Lease(self.name, backend=self.backend, ttl=self.ttl, limit=self.capacity, wait=False)
|
|
492
|
+
|
|
493
|
+
def _rejected(self, reason: str) -> BulkheadFull:
|
|
494
|
+
_core.emit("bulkhead.rejected", self.name, active=self.active, waiting=self.waiting)
|
|
495
|
+
return BulkheadFull(reason, name=self.name, max_concurrent=self.capacity)
|
|
496
|
+
|
|
497
|
+
def _queued(self) -> None:
|
|
498
|
+
with self._lock:
|
|
499
|
+
rejected = self.max_waiting is not None and self._waiting >= self.max_waiting
|
|
500
|
+
if not rejected:
|
|
501
|
+
self._waiting += 1
|
|
502
|
+
if rejected:
|
|
503
|
+
raise self._rejected("shared bulkhead queue full")
|
|
504
|
+
|
|
505
|
+
def _admitted(self, lease: Lease, owner: object) -> None:
|
|
506
|
+
self._stack.set((*self._stack.get(), (lease, owner)))
|
|
507
|
+
with self._lock:
|
|
508
|
+
self._active += 1
|
|
509
|
+
|
|
510
|
+
def acquire(self) -> None:
|
|
511
|
+
if self._async:
|
|
512
|
+
raise TypeError(
|
|
513
|
+
"this bulkhead's backend is async; it protects async def functions only"
|
|
514
|
+
)
|
|
515
|
+
if self._monitor._skipping():
|
|
516
|
+
return self._local_admit(threading.get_ident())
|
|
517
|
+
lease = self._lease()
|
|
518
|
+
try:
|
|
519
|
+
lease.__enter__()
|
|
520
|
+
except AlreadyRunning:
|
|
521
|
+
self._queued()
|
|
522
|
+
try:
|
|
523
|
+
lease.wait, lease.timeout = True, self.timeout
|
|
524
|
+
lease.__enter__()
|
|
525
|
+
except AlreadyRunning as exc:
|
|
526
|
+
raise self._rejected("shared bulkhead timed out") from exc
|
|
527
|
+
finally:
|
|
528
|
+
with self._lock:
|
|
529
|
+
self._waiting -= 1
|
|
530
|
+
except Exception as exc:
|
|
531
|
+
self._store_down(exc)
|
|
532
|
+
return self._local_admit(threading.get_ident())
|
|
533
|
+
self._monitor.succeeded()
|
|
534
|
+
self._admitted(lease, threading.get_ident())
|
|
535
|
+
|
|
536
|
+
def release(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None:
|
|
537
|
+
stack = self._stack.get()
|
|
538
|
+
if not stack:
|
|
539
|
+
raise RuntimeError("shared bulkhead released without acquisition")
|
|
540
|
+
lease, owner = stack[-1]
|
|
541
|
+
if owner != threading.get_ident():
|
|
542
|
+
raise RuntimeError("shared bulkhead must be released in its acquiring thread")
|
|
543
|
+
self._stack.set(stack[:-1])
|
|
544
|
+
try:
|
|
545
|
+
if lease is not None:
|
|
546
|
+
lease.__exit__(typ, exc, tb)
|
|
547
|
+
finally:
|
|
548
|
+
with self._lock:
|
|
549
|
+
self._active -= 1
|
|
550
|
+
|
|
551
|
+
async def acquire_async(self) -> None:
|
|
552
|
+
if self._monitor._skipping():
|
|
553
|
+
return self._local_admit(asyncio.current_task())
|
|
554
|
+
lease = self._lease()
|
|
555
|
+
try:
|
|
556
|
+
await lease.__aenter__()
|
|
557
|
+
except AlreadyRunning:
|
|
558
|
+
self._queued()
|
|
559
|
+
try:
|
|
560
|
+
lease.wait, lease.timeout = True, self.timeout
|
|
561
|
+
await lease.__aenter__()
|
|
562
|
+
except AlreadyRunning as exc:
|
|
563
|
+
raise self._rejected("shared bulkhead timed out") from exc
|
|
564
|
+
finally:
|
|
565
|
+
with self._lock:
|
|
566
|
+
self._waiting -= 1
|
|
567
|
+
except Exception as exc:
|
|
568
|
+
self._store_down(exc)
|
|
569
|
+
return self._local_admit(asyncio.current_task())
|
|
570
|
+
self._monitor.succeeded()
|
|
571
|
+
self._admitted(lease, asyncio.current_task())
|
|
572
|
+
|
|
573
|
+
async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None:
|
|
574
|
+
stack = self._stack.get()
|
|
575
|
+
if not stack:
|
|
576
|
+
raise RuntimeError("shared bulkhead released without acquisition")
|
|
577
|
+
lease, owner = stack[-1]
|
|
578
|
+
if owner is not asyncio.current_task():
|
|
579
|
+
raise RuntimeError("shared bulkhead must be released in its acquiring task")
|
|
580
|
+
self._stack.set(stack[:-1])
|
|
581
|
+
try:
|
|
582
|
+
if lease is not None:
|
|
583
|
+
await lease.__aexit__(typ, exc, tb)
|
|
584
|
+
finally:
|
|
585
|
+
with self._lock:
|
|
586
|
+
self._active -= 1
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
@dataclass
|
|
590
|
+
class SharedBackends:
|
|
591
|
+
"""The shared stores a preset or policy uses, built from one Redis client.
|
|
592
|
+
|
|
593
|
+
Give a bare ``client`` to share everything, or set a field to override one layer:
|
|
594
|
+
``breaker_state`` (a `RedisBreakerState`), ``window`` (a Redis client for rate
|
|
595
|
+
windows), ``semaphore`` (a lease backend such as `RedisSemaphore`) and ``budget``
|
|
596
|
+
(a `RedisRetryBudget`-style backend). Keys derive from the preset or policy name.
|
|
597
|
+
"""
|
|
598
|
+
|
|
599
|
+
client: Any = None
|
|
600
|
+
breaker_state: Any = None
|
|
601
|
+
window: Any = None
|
|
602
|
+
semaphore: Any = None
|
|
603
|
+
budget: Any = None
|
|
604
|
+
|
|
605
|
+
@property
|
|
606
|
+
def is_async(self) -> bool:
|
|
607
|
+
"""True for a ``redis.asyncio`` client: layers are built from the async classes."""
|
|
608
|
+
return self.client is not None and _core.is_async(self.client.eval)
|
|
609
|
+
|
|
610
|
+
def breaker(self) -> Any:
|
|
611
|
+
if self.breaker_state is not None:
|
|
612
|
+
return self.breaker_state
|
|
613
|
+
if self.client is None:
|
|
614
|
+
return None
|
|
615
|
+
return (AsyncRedisBreakerState if self.is_async else RedisBreakerState)(self.client)
|
|
616
|
+
|
|
617
|
+
def rate_window(self, name: str, calls: int, period: float) -> Any:
|
|
618
|
+
from python_wrap.quotas import AsyncRedisWindow, RedisWindow
|
|
619
|
+
|
|
620
|
+
client = self.window if self.window is not None else self.client
|
|
621
|
+
if client is None:
|
|
622
|
+
return None
|
|
623
|
+
kind = AsyncRedisWindow if _core.is_async(client.eval) else RedisWindow
|
|
624
|
+
return kind(client, f"python-wrap:window:{name}", calls=calls, period=period)
|
|
625
|
+
|
|
626
|
+
def lease_backend(self) -> Any:
|
|
627
|
+
if self.semaphore is not None:
|
|
628
|
+
return self.semaphore
|
|
629
|
+
if self.client is None:
|
|
630
|
+
return None
|
|
631
|
+
from python_wrap.coordination import AsyncRedisSemaphore, RedisSemaphore
|
|
632
|
+
|
|
633
|
+
return (AsyncRedisSemaphore if self.is_async else RedisSemaphore)(self.client)
|
|
634
|
+
|
|
635
|
+
def budget_backend(self, name: str) -> Any:
|
|
636
|
+
if self.budget is not None:
|
|
637
|
+
return self.budget
|
|
638
|
+
# shortcut: retry budgets are sync only, so an async client keeps them per process;
|
|
639
|
+
# pass budget=RedisRetryBudget(sync_client, name) to share them.
|
|
640
|
+
if self.client is None or self.is_async:
|
|
641
|
+
return None
|
|
642
|
+
return RedisRetryBudget(self.client, name)
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def resolve_shared(shared: Any) -> SharedBackends | None:
|
|
646
|
+
"""Turn ``shared=`` (a client or `SharedBackends`) or ``configure(shared=)`` into one."""
|
|
647
|
+
if shared is None:
|
|
648
|
+
from python_wrap.config import get_config
|
|
649
|
+
|
|
650
|
+
shared = get_config()["shared"]
|
|
651
|
+
if shared is None or shared is False:
|
|
652
|
+
return None
|
|
653
|
+
return shared if isinstance(shared, SharedBackends) else SharedBackends(client=shared)
|