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/circuit.py
CHANGED
|
@@ -2,14 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import enum
|
|
6
7
|
import functools
|
|
7
|
-
import
|
|
8
|
+
import math
|
|
9
|
+
import weakref
|
|
10
|
+
from collections import deque
|
|
8
11
|
from collections.abc import Callable, Coroutine
|
|
9
12
|
from dataclasses import dataclass
|
|
10
13
|
from typing import Any, Concatenate, NoReturn, ParamSpec, Protocol, TypeVar, cast, overload
|
|
11
14
|
|
|
12
|
-
from python_wrap import _core
|
|
15
|
+
from python_wrap import _core, _fork
|
|
16
|
+
from python_wrap._backend import BackendMonitor
|
|
13
17
|
from python_wrap._core import F, LoggerLike, P, R
|
|
14
18
|
from python_wrap.errors import CircuitOpenError
|
|
15
19
|
|
|
@@ -55,6 +59,10 @@ class CircuitStats:
|
|
|
55
59
|
consecutive_failures: Counted failures since the last success.
|
|
56
60
|
opened_at: ``_core.monotonic()`` time at which the circuit last opened, or
|
|
57
61
|
``None`` while it is closed.
|
|
62
|
+
failure_rate: Share of calls in ``window`` that failed, for a breaker with
|
|
63
|
+
``failure_rate`` or ``slow_call_rate``; otherwise ``None``.
|
|
64
|
+
slow_rate: Share of calls in ``window`` slower than ``slow_call_duration``
|
|
65
|
+
(same condition).
|
|
58
66
|
"""
|
|
59
67
|
|
|
60
68
|
name: str
|
|
@@ -64,6 +72,12 @@ class CircuitStats:
|
|
|
64
72
|
rejected: int
|
|
65
73
|
consecutive_failures: int
|
|
66
74
|
opened_at: float | None
|
|
75
|
+
failure_rate: float | None = None
|
|
76
|
+
slow_rate: float | None = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# Every live breaker in this process, so metrics can read each one's current state.
|
|
80
|
+
_BREAKERS: weakref.WeakSet[CircuitBreaker] = weakref.WeakSet()
|
|
67
81
|
|
|
68
82
|
|
|
69
83
|
class CircuitBreaker:
|
|
@@ -96,6 +110,20 @@ class CircuitBreaker:
|
|
|
96
110
|
on_state_change: Listener called with ``(breaker, old_state, new_state)``.
|
|
97
111
|
name: Name used in log messages, errors and events.
|
|
98
112
|
logger: Logger (or name) for state transitions.
|
|
113
|
+
window: Count failures inside this many seconds instead of consecutive failures.
|
|
114
|
+
failure_rate: Open when this share (0 to 1) of the calls in ``window`` failed,
|
|
115
|
+
once ``minimum_calls`` calls were seen. Needs ``window``; replaces
|
|
116
|
+
``failure_threshold`` (a non-default threshold with it raises ValueError).
|
|
117
|
+
minimum_calls: Calls in ``window`` needed before a rate can open the breaker.
|
|
118
|
+
slow_call_duration: Seconds after which a call counts as slow, success or not.
|
|
119
|
+
slow_call_rate: Open when this share of the calls in ``window`` was slow (after
|
|
120
|
+
``minimum_calls``). Needs ``window`` and ``slow_call_duration``. A slow
|
|
121
|
+
half-open trial re-opens the breaker.
|
|
122
|
+
backend: Shared state such as `python_wrap.shared.RedisBreakerState`.
|
|
123
|
+
on_backend_error: What a store error does: ``"raise"`` (default), ``"local"``
|
|
124
|
+
(use this process's own breaker until the store answers) or ``"allow"``
|
|
125
|
+
(admit the call, skip accounting). Defaults to ``configure(backend_errors=)``.
|
|
126
|
+
retry_backend_after: Seconds to skip a failed store before trying it again.
|
|
99
127
|
|
|
100
128
|
Raises:
|
|
101
129
|
ValueError: If a numeric option is out of range.
|
|
@@ -129,6 +157,10 @@ class CircuitBreaker:
|
|
|
129
157
|
```
|
|
130
158
|
"""
|
|
131
159
|
|
|
160
|
+
@staticmethod
|
|
161
|
+
def name_for(name: str | None) -> str:
|
|
162
|
+
return name or "circuit"
|
|
163
|
+
|
|
132
164
|
def __reduce__(self) -> NoReturn:
|
|
133
165
|
_core.refuse_pickle(self)
|
|
134
166
|
|
|
@@ -144,15 +176,73 @@ class CircuitBreaker:
|
|
|
144
176
|
on_state_change: StateChangeListener | None = None,
|
|
145
177
|
name: str | None = None,
|
|
146
178
|
logger: LoggerLike = None,
|
|
179
|
+
window: float | None = None,
|
|
180
|
+
backend: Any = None,
|
|
181
|
+
on_backend_error: str | None = None,
|
|
182
|
+
retry_backend_after: float = 1.0,
|
|
183
|
+
failure_rate: float | None = None,
|
|
184
|
+
minimum_calls: int = 10,
|
|
185
|
+
slow_call_duration: float | None = None,
|
|
186
|
+
slow_call_rate: float | None = None,
|
|
147
187
|
) -> None:
|
|
148
|
-
if failure_threshold
|
|
188
|
+
if failure_rate is not None and failure_threshold != 5:
|
|
189
|
+
raise ValueError("set failure_threshold or failure_rate, not both")
|
|
190
|
+
for label, rate in (("failure_rate", failure_rate), ("slow_call_rate", slow_call_rate)):
|
|
191
|
+
if rate is not None and (not math.isfinite(rate) or not 0 < rate <= 1):
|
|
192
|
+
raise ValueError(f"{label} must be in (0, 1], got {rate!r}")
|
|
193
|
+
if (slow_call_duration is None) != (slow_call_rate is None):
|
|
194
|
+
raise ValueError("slow_call_duration and slow_call_rate go together")
|
|
195
|
+
if slow_call_duration is not None and (
|
|
196
|
+
not math.isfinite(slow_call_duration) or slow_call_duration <= 0
|
|
197
|
+
):
|
|
198
|
+
raise ValueError("slow_call_duration must be positive")
|
|
199
|
+
if (failure_rate is not None or slow_call_rate is not None) and window is None:
|
|
200
|
+
raise ValueError("failure_rate and slow_call_rate need window=")
|
|
201
|
+
if (
|
|
202
|
+
isinstance(minimum_calls, bool)
|
|
203
|
+
or not isinstance(minimum_calls, int)
|
|
204
|
+
or minimum_calls < 1
|
|
205
|
+
):
|
|
206
|
+
raise ValueError(f"minimum_calls must be >= 1, got {minimum_calls!r}")
|
|
207
|
+
if (
|
|
208
|
+
isinstance(failure_threshold, bool)
|
|
209
|
+
or not isinstance(failure_threshold, int)
|
|
210
|
+
or failure_threshold < 1
|
|
211
|
+
):
|
|
149
212
|
raise ValueError(f"failure_threshold must be >= 1, got {failure_threshold!r}")
|
|
150
|
-
if recovery_timeout < 0:
|
|
213
|
+
if not math.isfinite(recovery_timeout) or recovery_timeout < 0:
|
|
151
214
|
raise ValueError(f"recovery_timeout must be >= 0, got {recovery_timeout!r}")
|
|
152
|
-
if
|
|
215
|
+
if (
|
|
216
|
+
isinstance(half_open_max_calls, bool)
|
|
217
|
+
or not isinstance(half_open_max_calls, int)
|
|
218
|
+
or half_open_max_calls < 1
|
|
219
|
+
):
|
|
153
220
|
raise ValueError(f"half_open_max_calls must be >= 1, got {half_open_max_calls!r}")
|
|
154
|
-
if
|
|
221
|
+
if (
|
|
222
|
+
isinstance(success_threshold, bool)
|
|
223
|
+
or not isinstance(success_threshold, int)
|
|
224
|
+
or success_threshold < 1
|
|
225
|
+
):
|
|
155
226
|
raise ValueError(f"success_threshold must be >= 1, got {success_threshold!r}")
|
|
227
|
+
if window is not None and (not math.isfinite(window) or window <= 0):
|
|
228
|
+
raise ValueError("window must be positive")
|
|
229
|
+
if backend is not None and not name:
|
|
230
|
+
raise ValueError("shared breakers require an explicit name")
|
|
231
|
+
self.window, self.backend = window, backend
|
|
232
|
+
self._async_backend = backend is not None and _core.is_async(backend.operate)
|
|
233
|
+
self._last: dict[str, Any] | None = None # last async-backend answer, for .state
|
|
234
|
+
self._monitor: BackendMonitor | None = (
|
|
235
|
+
None
|
|
236
|
+
if backend is None
|
|
237
|
+
else BackendMonitor(
|
|
238
|
+
"breaker", self.name_for(name), on_backend_error, retry_backend_after
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
self._failure_times: deque[float] = deque()
|
|
242
|
+
self.failure_rate, self.minimum_calls = failure_rate, minimum_calls
|
|
243
|
+
self.slow_call_duration, self.slow_call_rate = slow_call_duration, slow_call_rate
|
|
244
|
+
self._rated = failure_rate is not None or slow_call_rate is not None
|
|
245
|
+
self._slots: deque[list[int]] = deque() # [slot, calls, failures, slow] in window
|
|
156
246
|
self.failure_threshold = failure_threshold
|
|
157
247
|
self.recovery_timeout = recovery_timeout
|
|
158
248
|
self.half_open_max_calls = half_open_max_calls
|
|
@@ -162,7 +252,7 @@ class CircuitBreaker:
|
|
|
162
252
|
self.on_state_change = on_state_change
|
|
163
253
|
self.name = name or "circuit"
|
|
164
254
|
self._log = _core.get_logger(logger)
|
|
165
|
-
self._lock =
|
|
255
|
+
self._lock = _fork.ForkSafeLock()
|
|
166
256
|
self._state = CircuitState.CLOSED
|
|
167
257
|
self._failures = 0
|
|
168
258
|
self._opened_at = 0.0
|
|
@@ -174,11 +264,58 @@ class CircuitBreaker:
|
|
|
174
264
|
self._total_rejected = 0
|
|
175
265
|
# Transitions made under the lock, delivered to listeners after releasing it.
|
|
176
266
|
self._pending: list[tuple[CircuitState, CircuitState]] = []
|
|
267
|
+
_fork.register(self)
|
|
268
|
+
_BREAKERS.add(self)
|
|
269
|
+
|
|
270
|
+
def _adopt(self, old: CircuitBreaker) -> None:
|
|
271
|
+
"""Carry ``old``'s in-process state into this breaker (a policy reload).
|
|
272
|
+
|
|
273
|
+
An open breaker stays open with the new thresholds. Shared breakers need
|
|
274
|
+
nothing: their state lives in the backend under the same name.
|
|
275
|
+
"""
|
|
276
|
+
if self.backend is not None or old.backend is not None:
|
|
277
|
+
return
|
|
278
|
+
with old._lock:
|
|
279
|
+
snapshot = (
|
|
280
|
+
old._state,
|
|
281
|
+
old._failures,
|
|
282
|
+
old._opened_at,
|
|
283
|
+
deque(old._failure_times),
|
|
284
|
+
deque(list(slot) for slot in old._slots),
|
|
285
|
+
old._total_failures,
|
|
286
|
+
old._total_successes,
|
|
287
|
+
old._total_rejected,
|
|
288
|
+
)
|
|
289
|
+
with self._lock:
|
|
290
|
+
(
|
|
291
|
+
self._state,
|
|
292
|
+
self._failures,
|
|
293
|
+
self._opened_at,
|
|
294
|
+
self._failure_times,
|
|
295
|
+
self._slots,
|
|
296
|
+
self._total_failures,
|
|
297
|
+
self._total_successes,
|
|
298
|
+
self._total_rejected,
|
|
299
|
+
) = snapshot
|
|
300
|
+
|
|
301
|
+
def _reset_after_fork(self) -> None:
|
|
302
|
+
# Shared backends remain authoritative; never reset their state from a child.
|
|
303
|
+
self._pending.clear()
|
|
304
|
+
if self.backend is None:
|
|
305
|
+
self._state = CircuitState.CLOSED
|
|
306
|
+
self._failures = self._trials = self._trial_successes = 0
|
|
307
|
+
self._total_failures = self._total_successes = self._total_rejected = 0
|
|
308
|
+
self._failure_times.clear()
|
|
309
|
+
self._slots.clear()
|
|
310
|
+
self._generation += 1
|
|
177
311
|
|
|
178
312
|
# -- introspection -------------------------------------------------------------
|
|
179
313
|
@property
|
|
180
314
|
def state(self) -> CircuitState:
|
|
181
315
|
"""Current state (an open circuit past its timeout reports ``half_open``)."""
|
|
316
|
+
data = self._try("state")
|
|
317
|
+
if data is not None:
|
|
318
|
+
return CircuitState(data["state"])
|
|
182
319
|
with self._lock:
|
|
183
320
|
self._maybe_half_open()
|
|
184
321
|
state = self._state
|
|
@@ -188,12 +325,31 @@ class CircuitBreaker:
|
|
|
188
325
|
@property
|
|
189
326
|
def failure_count(self) -> int:
|
|
190
327
|
"""Consecutive failures counted so far."""
|
|
328
|
+
data = self._try("state")
|
|
329
|
+
if data is not None:
|
|
330
|
+
return int(data["failures"])
|
|
191
331
|
with self._lock:
|
|
192
332
|
return self._failures
|
|
193
333
|
|
|
194
334
|
@property
|
|
195
335
|
def stats(self) -> CircuitStats:
|
|
196
336
|
"""A consistent `CircuitStats` snapshot of the counters and state."""
|
|
337
|
+
data = self._try("state")
|
|
338
|
+
if data is not None:
|
|
339
|
+
return CircuitStats(
|
|
340
|
+
name=self.name,
|
|
341
|
+
state=CircuitState(data["state"]),
|
|
342
|
+
failures=data["total_failures"],
|
|
343
|
+
successes=data["total_successes"],
|
|
344
|
+
rejected=data["total_rejected"],
|
|
345
|
+
consecutive_failures=data["failures"],
|
|
346
|
+
opened_at=None if data["state"] == "closed" else data["opened"] / 1000,
|
|
347
|
+
**self._rates(
|
|
348
|
+
data.get("window_calls", 0),
|
|
349
|
+
data.get("window_failures", 0),
|
|
350
|
+
data.get("window_slow", 0),
|
|
351
|
+
),
|
|
352
|
+
)
|
|
197
353
|
with self._lock:
|
|
198
354
|
self._maybe_half_open()
|
|
199
355
|
snapshot = CircuitStats(
|
|
@@ -204,13 +360,20 @@ class CircuitBreaker:
|
|
|
204
360
|
rejected=self._total_rejected,
|
|
205
361
|
consecutive_failures=self._failures,
|
|
206
362
|
opened_at=None if self._state is CircuitState.CLOSED else self._opened_at,
|
|
363
|
+
**self._rates(*self._window_totals()),
|
|
207
364
|
)
|
|
208
365
|
self._notify()
|
|
209
366
|
return snapshot
|
|
210
367
|
|
|
211
368
|
def reset(self) -> None:
|
|
212
369
|
"""Force the breaker back to closed and zero every counter."""
|
|
370
|
+
if self._try("reset") is None:
|
|
371
|
+
self._local_reset()
|
|
372
|
+
|
|
373
|
+
def _local_reset(self) -> None:
|
|
213
374
|
with self._lock:
|
|
375
|
+
self._failure_times.clear()
|
|
376
|
+
self._slots.clear()
|
|
214
377
|
if self._state is not CircuitState.CLOSED:
|
|
215
378
|
self._log.info("circuit %s reset to closed", self.name)
|
|
216
379
|
self._set_state(CircuitState.CLOSED)
|
|
@@ -223,7 +386,130 @@ class CircuitBreaker:
|
|
|
223
386
|
self._generation += 1
|
|
224
387
|
self._notify()
|
|
225
388
|
|
|
389
|
+
def force_open(self) -> None:
|
|
390
|
+
"""Force open for maintenance/tests, without simulating dependency failures."""
|
|
391
|
+
if self._try("force_open") is None:
|
|
392
|
+
self._local_force_open()
|
|
393
|
+
|
|
394
|
+
def _local_force_open(self) -> None:
|
|
395
|
+
with self._lock:
|
|
396
|
+
self._open()
|
|
397
|
+
self._notify()
|
|
398
|
+
|
|
399
|
+
def _try(
|
|
400
|
+
self, operation: str, generation: int = 0, trial: bool = False, slow: bool = False
|
|
401
|
+
) -> dict[str, Any] | None:
|
|
402
|
+
"""Backend result, or None when this call must use the local state (or be bypassed)."""
|
|
403
|
+
if self._monitor is None:
|
|
404
|
+
return None
|
|
405
|
+
if self._async_backend:
|
|
406
|
+
if operation == "state":
|
|
407
|
+
return self._last
|
|
408
|
+
raise TypeError(
|
|
409
|
+
f"circuit {self.name} has an async backend; use the async form of this call"
|
|
410
|
+
)
|
|
411
|
+
return self._monitor.call(
|
|
412
|
+
operation, lambda: self._remote(operation, generation, trial, slow), lambda: None
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
async def _atry(
|
|
416
|
+
self, operation: str, generation: int = 0, trial: bool = False, slow: bool = False
|
|
417
|
+
) -> dict[str, Any] | None:
|
|
418
|
+
"""`_try` for an async backend: the store round trip is awaited."""
|
|
419
|
+
if self._monitor is None:
|
|
420
|
+
return None
|
|
421
|
+
|
|
422
|
+
async def run() -> dict[str, Any]:
|
|
423
|
+
extra = {"slow": True} if slow else {} # backends without slow-call support still work
|
|
424
|
+
data = await self.backend.operate(self, operation, generation, trial, **extra)
|
|
425
|
+
return self._observe(data)
|
|
426
|
+
|
|
427
|
+
return await self._monitor.acall(operation, run, lambda: None)
|
|
428
|
+
|
|
429
|
+
async def areset(self) -> None:
|
|
430
|
+
"""`reset` for a breaker with an async backend (works for any breaker)."""
|
|
431
|
+
if not self._async_backend:
|
|
432
|
+
return self.reset()
|
|
433
|
+
if await self._atry("reset") is None:
|
|
434
|
+
self._local_reset()
|
|
435
|
+
|
|
436
|
+
async def aforce_open(self) -> None:
|
|
437
|
+
"""`force_open` for a breaker with an async backend (works for any breaker)."""
|
|
438
|
+
if not self._async_backend:
|
|
439
|
+
return self.force_open()
|
|
440
|
+
if await self._atry("force_open") is None:
|
|
441
|
+
self._local_force_open()
|
|
442
|
+
|
|
443
|
+
def _bypass(self) -> bool:
|
|
444
|
+
return self._monitor is not None and self._monitor.mode == "allow"
|
|
445
|
+
|
|
446
|
+
def _remote(
|
|
447
|
+
self, operation: str, generation: int = 0, trial: bool = False, slow: bool = False
|
|
448
|
+
) -> dict[str, Any]:
|
|
449
|
+
extra = {"slow": True} if slow else {} # backends without slow-call support still work
|
|
450
|
+
return self._observe(self.backend.operate(self, operation, generation, trial, **extra))
|
|
451
|
+
|
|
452
|
+
def _observe(self, data: dict[str, Any]) -> dict[str, Any]:
|
|
453
|
+
"""Record a backend answer and report the transition it made, if any."""
|
|
454
|
+
self._last = data
|
|
455
|
+
if data["old"] != data["state"]:
|
|
456
|
+
rates = self._rates(
|
|
457
|
+
data.get("window_calls", 0),
|
|
458
|
+
data.get("window_failures", 0),
|
|
459
|
+
data.get("window_slow", 0),
|
|
460
|
+
)
|
|
461
|
+
_core.emit(
|
|
462
|
+
"circuit.state_changed", self.name, old=data["old"], new=data["state"], **rates
|
|
463
|
+
)
|
|
464
|
+
if self.on_state_change:
|
|
465
|
+
try:
|
|
466
|
+
self.on_state_change(
|
|
467
|
+
self, CircuitState(data["old"]), CircuitState(data["state"])
|
|
468
|
+
)
|
|
469
|
+
except Exception:
|
|
470
|
+
self._log.exception("circuit listener failed")
|
|
471
|
+
return data
|
|
472
|
+
|
|
473
|
+
# -- failure and slow-call rates ------------------------------------------------
|
|
474
|
+
def _rates(self, calls: int, failures: int, slow: int) -> dict[str, float | None]:
|
|
475
|
+
if not self._rated:
|
|
476
|
+
return {}
|
|
477
|
+
return {
|
|
478
|
+
"failure_rate": failures / calls if calls else 0.0,
|
|
479
|
+
"slow_rate": slow / calls if calls else 0.0,
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
def _trips(self, calls: int, failures: int, slow: int) -> bool:
|
|
483
|
+
if calls < self.minimum_calls:
|
|
484
|
+
return False
|
|
485
|
+
if self.failure_rate is not None and failures >= self.failure_rate * calls:
|
|
486
|
+
return True
|
|
487
|
+
return self.slow_call_rate is not None and slow >= self.slow_call_rate * calls
|
|
488
|
+
|
|
489
|
+
def _slow(self, started: float | None) -> bool:
|
|
490
|
+
return started is not None and _core.monotonic() - started >= self.slow_call_duration # type: ignore[operator]
|
|
491
|
+
|
|
226
492
|
# -- internals (call with the lock held) ---------------------------------------
|
|
493
|
+
def _window_totals(
|
|
494
|
+
self, failed: int = 0, slow: int = 0, add: bool = False
|
|
495
|
+
) -> tuple[int, int, int]:
|
|
496
|
+
"""Calls, failures and slow calls in ``window``, in ten slots; ``add`` records one."""
|
|
497
|
+
if not self._rated:
|
|
498
|
+
return 0, 0, 0
|
|
499
|
+
slot = math.floor(_core.monotonic() / (self.window / 10)) # type: ignore[operator]
|
|
500
|
+
while self._slots and self._slots[0][0] <= slot - 10:
|
|
501
|
+
self._slots.popleft()
|
|
502
|
+
if add:
|
|
503
|
+
if not self._slots or self._slots[-1][0] != slot:
|
|
504
|
+
self._slots.append([slot, 0, 0, 0])
|
|
505
|
+
last = self._slots[-1]
|
|
506
|
+
last[1], last[2], last[3] = last[1] + 1, last[2] + failed, last[3] + slow
|
|
507
|
+
return (
|
|
508
|
+
sum(s[1] for s in self._slots),
|
|
509
|
+
sum(s[2] for s in self._slots),
|
|
510
|
+
sum(s[3] for s in self._slots),
|
|
511
|
+
)
|
|
512
|
+
|
|
227
513
|
def _set_state(self, new: CircuitState) -> None:
|
|
228
514
|
old = self._state
|
|
229
515
|
self._state = new
|
|
@@ -261,8 +547,9 @@ class CircuitBreaker:
|
|
|
261
547
|
return
|
|
262
548
|
with self._lock:
|
|
263
549
|
pending, self._pending = self._pending, []
|
|
550
|
+
rates = self._rates(*self._window_totals())
|
|
264
551
|
for old, new in pending:
|
|
265
|
-
_core.emit("circuit.state_changed", self.name, old=old, new=new)
|
|
552
|
+
_core.emit("circuit.state_changed", self.name, old=old, new=new, **rates)
|
|
266
553
|
listener = self.on_state_change
|
|
267
554
|
if listener is None:
|
|
268
555
|
continue
|
|
@@ -273,6 +560,20 @@ class CircuitBreaker:
|
|
|
273
560
|
|
|
274
561
|
def _acquire(self) -> tuple[int, bool]:
|
|
275
562
|
"""Admit a call. Returns ``(generation, is_trial)`` or raises CircuitOpenError."""
|
|
563
|
+
return self._admit(self._try("admit"))
|
|
564
|
+
|
|
565
|
+
async def _aacquire(self) -> tuple[int, bool]:
|
|
566
|
+
return self._admit(await self._atry("admit"))
|
|
567
|
+
|
|
568
|
+
def _admit(self, data: dict[str, Any] | None) -> tuple[int, bool]:
|
|
569
|
+
if data is None and self._bypass():
|
|
570
|
+
return 0, False
|
|
571
|
+
if data is not None:
|
|
572
|
+
if not data["admitted"]:
|
|
573
|
+
wait = data["wait"] / 1000
|
|
574
|
+
_core.emit("circuit.rejected", self.name, retry_after=wait)
|
|
575
|
+
raise CircuitOpenError(f"circuit {self.name} is {data['state']}", retry_after=wait)
|
|
576
|
+
return data["generation"], bool(data["trial"])
|
|
276
577
|
error: CircuitOpenError | None = None
|
|
277
578
|
with self._lock:
|
|
278
579
|
self._maybe_half_open()
|
|
@@ -299,15 +600,27 @@ class CircuitBreaker:
|
|
|
299
600
|
raise error
|
|
300
601
|
return admitted
|
|
301
602
|
|
|
302
|
-
def _success(self, generation: int, trial: bool) -> None:
|
|
603
|
+
def _success(self, generation: int, trial: bool, slow: bool = False) -> None:
|
|
604
|
+
if self._try("success", generation, trial, slow) is None and not self._bypass():
|
|
605
|
+
self._local_success(generation, trial, slow)
|
|
606
|
+
|
|
607
|
+
async def _asuccess(self, generation: int, trial: bool, slow: bool = False) -> None:
|
|
608
|
+
if await self._atry("success", generation, trial, slow) is None and not self._bypass():
|
|
609
|
+
self._local_success(generation, trial, slow)
|
|
610
|
+
|
|
611
|
+
def _local_success(self, generation: int, trial: bool, slow: bool = False) -> None:
|
|
303
612
|
with self._lock:
|
|
304
613
|
self._total_successes += 1
|
|
305
614
|
if generation != self._generation:
|
|
306
615
|
return
|
|
307
|
-
if trial:
|
|
616
|
+
if trial and slow and self.slow_call_rate is not None:
|
|
617
|
+
self._trials = max(self._trials - 1, 0)
|
|
618
|
+
self._open()
|
|
619
|
+
elif trial:
|
|
308
620
|
self._trials = max(self._trials - 1, 0)
|
|
309
621
|
self._trial_successes += 1
|
|
310
622
|
if self._trial_successes >= self.success_threshold:
|
|
623
|
+
self._slots.clear()
|
|
311
624
|
self._set_state(CircuitState.CLOSED)
|
|
312
625
|
self._trials = 0
|
|
313
626
|
self._trial_successes = 0
|
|
@@ -317,34 +630,78 @@ class CircuitBreaker:
|
|
|
317
630
|
self.name,
|
|
318
631
|
self.success_threshold,
|
|
319
632
|
)
|
|
320
|
-
self.
|
|
633
|
+
if self.window is None or trial:
|
|
634
|
+
self._failures = 0
|
|
635
|
+
self._failure_times.clear()
|
|
636
|
+
if self._rated and not trial and self._trips(*self._window_totals(0, slow, True)):
|
|
637
|
+
self._open()
|
|
321
638
|
self._notify()
|
|
322
639
|
|
|
323
|
-
def _failure(self, generation: int, trial: bool) -> None:
|
|
640
|
+
def _failure(self, generation: int, trial: bool, slow: bool = False) -> None:
|
|
641
|
+
if self._try("failure", generation, trial, slow) is None and not self._bypass():
|
|
642
|
+
self._local_failure(generation, trial, slow)
|
|
643
|
+
|
|
644
|
+
def _local_failure(self, generation: int, trial: bool, slow: bool = False) -> None:
|
|
324
645
|
with self._lock:
|
|
325
646
|
self._total_failures += 1
|
|
326
647
|
if generation != self._generation:
|
|
327
648
|
return
|
|
328
|
-
self.
|
|
329
|
-
if
|
|
649
|
+
rated = self._rated and not trial and self._trips(*self._window_totals(1, slow, True))
|
|
650
|
+
if self.failure_rate is not None:
|
|
651
|
+
self._failures = self._window_totals()[1]
|
|
652
|
+
elif self.window is None:
|
|
653
|
+
self._failures += 1
|
|
654
|
+
else:
|
|
655
|
+
now = _core.monotonic()
|
|
656
|
+
while self._failure_times and self._failure_times[0] <= now - self.window:
|
|
657
|
+
self._failure_times.popleft()
|
|
658
|
+
self._failure_times.append(now)
|
|
659
|
+
self._failures = len(self._failure_times)
|
|
660
|
+
counted = self.failure_rate is None and self._failures >= self.failure_threshold
|
|
661
|
+
if trial or rated or counted:
|
|
330
662
|
self._open()
|
|
331
663
|
self._notify()
|
|
332
664
|
|
|
333
665
|
def _release(self, generation: int, trial: bool) -> None:
|
|
334
666
|
"""A non-counted exception ended the call: free its trial slot, if any."""
|
|
667
|
+
if self._try("neutral", generation, trial) is None and not self._bypass():
|
|
668
|
+
self._local_release(generation, trial)
|
|
669
|
+
|
|
670
|
+
async def _arelease(self, generation: int, trial: bool) -> None:
|
|
671
|
+
if await self._atry("neutral", generation, trial) is None and not self._bypass():
|
|
672
|
+
self._local_release(generation, trial)
|
|
673
|
+
|
|
674
|
+
def _local_release(self, generation: int, trial: bool) -> None:
|
|
335
675
|
if not trial:
|
|
336
676
|
return
|
|
337
677
|
with self._lock:
|
|
338
678
|
if generation == self._generation:
|
|
339
679
|
self._trials = max(self._trials - 1, 0)
|
|
340
680
|
|
|
341
|
-
def
|
|
681
|
+
def _counted(self, exc: BaseException) -> bool:
|
|
682
|
+
return isinstance(exc, self.on) and not isinstance(exc, self.exclude)
|
|
683
|
+
|
|
684
|
+
def _settle(self, generation: int, trial: bool, exc: BaseException, slow: bool = False) -> None:
|
|
342
685
|
"""Book a call that raised ``exc``: a failure, or uncounted."""
|
|
343
|
-
if
|
|
344
|
-
self._failure(generation, trial)
|
|
686
|
+
if self._counted(exc):
|
|
687
|
+
self._failure(generation, trial, slow)
|
|
345
688
|
else:
|
|
346
689
|
self._release(generation, trial)
|
|
347
690
|
|
|
691
|
+
async def _asettle(
|
|
692
|
+
self, generation: int, trial: bool, exc: BaseException, slow: bool = False
|
|
693
|
+
) -> None:
|
|
694
|
+
if not self._counted(exc):
|
|
695
|
+
return await self._arelease(generation, trial)
|
|
696
|
+
if await self._atry("failure", generation, trial, slow) is None and not self._bypass():
|
|
697
|
+
self._local_failure(generation, trial, slow)
|
|
698
|
+
|
|
699
|
+
def _offload(self, name: str, *args: Any) -> asyncio.Task[Any]:
|
|
700
|
+
"""Run a backend step as a task: awaited natively, or in a worker thread."""
|
|
701
|
+
if self._async_backend:
|
|
702
|
+
return asyncio.ensure_future(getattr(self, "_a" + name.lstrip("_"))(*args))
|
|
703
|
+
return asyncio.create_task(asyncio.to_thread(getattr(self, name), *args))
|
|
704
|
+
|
|
348
705
|
# -- public call API -----------------------------------------------------------
|
|
349
706
|
@overload
|
|
350
707
|
def call(
|
|
@@ -373,24 +730,71 @@ class CircuitBreaker:
|
|
|
373
730
|
return self._call_sync(func, args, kwargs)
|
|
374
731
|
|
|
375
732
|
def _call_sync(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any:
|
|
733
|
+
if self._async_backend:
|
|
734
|
+
raise TypeError(f"circuit {self.name} has an async backend; it protects async def only")
|
|
376
735
|
generation, trial = self._acquire()
|
|
736
|
+
started = None if self.slow_call_duration is None else _core.monotonic()
|
|
377
737
|
try:
|
|
378
738
|
result = func(*args, **kwargs)
|
|
379
739
|
except BaseException as exc:
|
|
380
|
-
|
|
740
|
+
try:
|
|
741
|
+
self._settle(generation, trial, exc, self._slow(started))
|
|
742
|
+
except Exception:
|
|
743
|
+
self._log.exception("circuit outcome bookkeeping failed; preserving original error")
|
|
381
744
|
raise
|
|
382
|
-
self._success(generation, trial)
|
|
745
|
+
self._success(generation, trial, self._slow(started))
|
|
383
746
|
return result
|
|
384
747
|
|
|
385
748
|
async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any:
|
|
386
|
-
|
|
387
|
-
|
|
749
|
+
from python_wrap.coordination import _drain
|
|
750
|
+
|
|
751
|
+
# Synchronous network admission cannot be abandoned on cancellation: a late
|
|
752
|
+
# successful admission would otherwise strand a half-open trial reservation.
|
|
753
|
+
if self.backend is not None:
|
|
754
|
+
admission = self._offload("_acquire")
|
|
755
|
+
try:
|
|
756
|
+
generation, trial = await asyncio.shield(admission)
|
|
757
|
+
except asyncio.CancelledError:
|
|
758
|
+
acquired, error, _ = await _drain(admission)
|
|
759
|
+
if error is None:
|
|
760
|
+
cleanup = self._offload("_release", *acquired)
|
|
761
|
+
await _drain(cleanup)
|
|
762
|
+
raise
|
|
763
|
+
else:
|
|
764
|
+
generation, trial = self._acquire()
|
|
765
|
+
started = None if self.slow_call_duration is None else _core.monotonic()
|
|
388
766
|
try:
|
|
389
767
|
result = await func(*args, **kwargs)
|
|
390
768
|
except BaseException as exc:
|
|
391
|
-
self.
|
|
769
|
+
slow = self._slow(started)
|
|
770
|
+
if self.backend is not None:
|
|
771
|
+
settlement = self._offload("_settle", generation, trial, exc, slow)
|
|
772
|
+
_, error, cancelled = await _drain(settlement)
|
|
773
|
+
if cancelled:
|
|
774
|
+
raise asyncio.CancelledError from None
|
|
775
|
+
if error is not None:
|
|
776
|
+
self._log.error(
|
|
777
|
+
"circuit outcome bookkeeping failed; preserving original error",
|
|
778
|
+
exc_info=(type(error), error, error.__traceback__),
|
|
779
|
+
)
|
|
780
|
+
else:
|
|
781
|
+
try:
|
|
782
|
+
self._settle(generation, trial, exc, slow)
|
|
783
|
+
except Exception:
|
|
784
|
+
self._log.exception(
|
|
785
|
+
"circuit outcome bookkeeping failed; preserving original error"
|
|
786
|
+
)
|
|
392
787
|
raise
|
|
393
|
-
self.
|
|
788
|
+
slow = self._slow(started)
|
|
789
|
+
if self.backend is not None:
|
|
790
|
+
success = self._offload("_success", generation, trial, slow)
|
|
791
|
+
_, error, cancelled = await _drain(success)
|
|
792
|
+
if cancelled:
|
|
793
|
+
raise asyncio.CancelledError
|
|
794
|
+
if error is not None:
|
|
795
|
+
raise error
|
|
796
|
+
else:
|
|
797
|
+
self._success(generation, trial, slow)
|
|
394
798
|
return result
|
|
395
799
|
|
|
396
800
|
def __call__(self, func: F) -> F:
|
|
@@ -405,6 +809,7 @@ class CircuitBreaker:
|
|
|
405
809
|
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
406
810
|
return await self._acall(func, args, kwargs)
|
|
407
811
|
|
|
812
|
+
async_wrapper.__python_wrap_layer__ = ("breaker", self) # type: ignore[attr-defined]
|
|
408
813
|
return cast(F, async_wrapper)
|
|
409
814
|
|
|
410
815
|
@functools.wraps(func)
|
|
@@ -412,6 +817,7 @@ class CircuitBreaker:
|
|
|
412
817
|
# Sync vs async was decided above, once: no per-call detection.
|
|
413
818
|
return self._call_sync(func, args, kwargs)
|
|
414
819
|
|
|
820
|
+
wrapper.__python_wrap_layer__ = ("breaker", self) # type: ignore[attr-defined]
|
|
415
821
|
return cast(F, wrapper)
|
|
416
822
|
|
|
417
823
|
def __repr__(self) -> str:
|
|
@@ -475,6 +881,11 @@ def circuit_breaker(
|
|
|
475
881
|
on_state_change: StateChangeListener | None = ...,
|
|
476
882
|
name: str | None = ...,
|
|
477
883
|
logger: LoggerLike = ...,
|
|
884
|
+
window: float | None = ...,
|
|
885
|
+
failure_rate: float | None = ...,
|
|
886
|
+
minimum_calls: int = ...,
|
|
887
|
+
slow_call_duration: float | None = ...,
|
|
888
|
+
slow_call_rate: float | None = ...,
|
|
478
889
|
) -> CircuitProtected[P, R]: ...
|
|
479
890
|
@overload
|
|
480
891
|
def circuit_breaker(
|
|
@@ -490,6 +901,11 @@ def circuit_breaker(
|
|
|
490
901
|
on_state_change: StateChangeListener | None = ...,
|
|
491
902
|
name: str | None = ...,
|
|
492
903
|
logger: LoggerLike = ...,
|
|
904
|
+
window: float | None = ...,
|
|
905
|
+
failure_rate: float | None = ...,
|
|
906
|
+
minimum_calls: int = ...,
|
|
907
|
+
slow_call_duration: float | None = ...,
|
|
908
|
+
slow_call_rate: float | None = ...,
|
|
493
909
|
) -> Callable[[Callable[P, R]], CircuitProtected[P, R]]: ...
|
|
494
910
|
def circuit_breaker(
|
|
495
911
|
func: Callable[..., Any] | None = None,
|
|
@@ -504,6 +920,11 @@ def circuit_breaker(
|
|
|
504
920
|
on_state_change: StateChangeListener | None = None,
|
|
505
921
|
name: str | None = None,
|
|
506
922
|
logger: LoggerLike = None,
|
|
923
|
+
window: float | None = None,
|
|
924
|
+
failure_rate: float | None = None,
|
|
925
|
+
minimum_calls: int = 10,
|
|
926
|
+
slow_call_duration: float | None = None,
|
|
927
|
+
slow_call_rate: float | None = None,
|
|
507
928
|
) -> Any:
|
|
508
929
|
"""Decorate a function with its own dedicated `CircuitBreaker`.
|
|
509
930
|
|
|
@@ -522,6 +943,11 @@ def circuit_breaker(
|
|
|
522
943
|
on_state_change: Listener called with ``(breaker, old_state, new_state)``.
|
|
523
944
|
name: Name for log messages, errors and events (defaults to the function's qualified name).
|
|
524
945
|
logger: Logger (or name) for state transitions.
|
|
946
|
+
window: Count failures inside this many seconds (see `CircuitBreaker`).
|
|
947
|
+
failure_rate: Open at this failed share of calls in ``window``.
|
|
948
|
+
minimum_calls: Calls in ``window`` needed before a rate can open the breaker.
|
|
949
|
+
slow_call_duration: Seconds after which a call counts as slow.
|
|
950
|
+
slow_call_rate: Open at this slow share of calls in ``window``.
|
|
525
951
|
|
|
526
952
|
Returns:
|
|
527
953
|
The wrapped function, or a decorator when ``func`` is omitted.
|
|
@@ -545,6 +971,11 @@ def circuit_breaker(
|
|
|
545
971
|
on_state_change=on_state_change,
|
|
546
972
|
name=name or _core.qualname(f),
|
|
547
973
|
logger=logger,
|
|
974
|
+
window=window,
|
|
975
|
+
failure_rate=failure_rate,
|
|
976
|
+
minimum_calls=minimum_calls,
|
|
977
|
+
slow_call_duration=slow_call_duration,
|
|
978
|
+
slow_call_rate=slow_call_rate,
|
|
548
979
|
)
|
|
549
980
|
wrapped: Any = breaker(f)
|
|
550
981
|
wrapped.breaker = breaker
|