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/policies.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""Named, inspectable resilience policies loaded from mappings, JSON env vars or sources.
|
|
2
|
+
|
|
3
|
+
Mappings may refer to objects by name: ``"on": ["builtins.ConnectionError"]``,
|
|
4
|
+
``"retry_if": "db_transient"`` and ``"backend": "@default"``. Names resolve only
|
|
5
|
+
through explicit registries (`PolicyRegistry.register_exception`,
|
|
6
|
+
`register_predicate`, `register_backend`); builtin exception names and the predicates
|
|
7
|
+
in `python_wrap.predicates` are registered already. No dotted path is ever imported.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import builtins
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import threading
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Protocol, TypeVar, cast
|
|
19
|
+
|
|
20
|
+
from python_wrap import _core, _fork
|
|
21
|
+
from python_wrap.policy import Policy, policy
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"EnvSource",
|
|
25
|
+
"FileSource",
|
|
26
|
+
"PolicyRegistry",
|
|
27
|
+
"PolicySource",
|
|
28
|
+
"RedisSource",
|
|
29
|
+
"Watch",
|
|
30
|
+
"policies",
|
|
31
|
+
"resilient",
|
|
32
|
+
]
|
|
33
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
34
|
+
|
|
35
|
+
_EXCEPTION_KEYS = frozenset({"on", "exclude"})
|
|
36
|
+
_PREDICATE_KEYS = frozenset({"retry_if", "retry_if_result"})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PolicySource(Protocol):
|
|
40
|
+
"""Where `PolicyRegistry.watch` reads a whole mapping of named policies from."""
|
|
41
|
+
|
|
42
|
+
def read(self) -> Mapping[str, Mapping[str, Any]]: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class EnvSource:
|
|
46
|
+
"""``PW_POLICY_<NAME>={JSON}`` environment variables (re-read on every poll)."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, prefix: str = "PW_POLICY_") -> None:
|
|
49
|
+
self.prefix = prefix
|
|
50
|
+
|
|
51
|
+
def read(self) -> dict[str, Any]:
|
|
52
|
+
return {
|
|
53
|
+
key[len(self.prefix) :]: json.loads(value)
|
|
54
|
+
for key, value in os.environ.items()
|
|
55
|
+
if key.startswith(self.prefix)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class FileSource:
|
|
60
|
+
"""A JSON file holding ``{"name": {settings}, ...}``."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, path: str | os.PathLike[str]) -> None:
|
|
63
|
+
self.path = Path(path)
|
|
64
|
+
|
|
65
|
+
def read(self) -> Any:
|
|
66
|
+
return json.loads(self.path.read_text(encoding="utf-8"))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class RedisSource:
|
|
70
|
+
"""One Redis string key holding the JSON mapping, shared by every replica."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, client: Any, key: str = "python-wrap:policies") -> None:
|
|
73
|
+
self.client, self.key = client, key
|
|
74
|
+
|
|
75
|
+
def read(self) -> Any:
|
|
76
|
+
raw = self.client.get(self.key)
|
|
77
|
+
if raw is None:
|
|
78
|
+
return {}
|
|
79
|
+
return json.loads(raw.decode() if isinstance(raw, bytes) else raw)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Watch:
|
|
83
|
+
"""A running `PolicyRegistry.watch`; ``stop()`` ends it. Does not survive a fork."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, registry: PolicyRegistry, source: PolicySource, interval: float):
|
|
86
|
+
self.registry, self.source, self.interval = registry, source, interval
|
|
87
|
+
self._stop = threading.Event()
|
|
88
|
+
self._last: str | None = None
|
|
89
|
+
self.poll() # the first read happens now, so a broken source fails loudly
|
|
90
|
+
self._thread = threading.Thread(target=self._run, daemon=True, name="python-wrap-policies")
|
|
91
|
+
self._thread.start()
|
|
92
|
+
|
|
93
|
+
def poll(self) -> bool:
|
|
94
|
+
"""Read the source once; apply it if it changed. True when a change was applied."""
|
|
95
|
+
try:
|
|
96
|
+
mapping = self.source.read()
|
|
97
|
+
text = json.dumps(mapping, sort_keys=True, default=repr)
|
|
98
|
+
if text == self._last:
|
|
99
|
+
return False
|
|
100
|
+
self.registry.load_from_mapping(mapping)
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
# A bad mapping keeps the current policies; the source is retried next poll.
|
|
103
|
+
_core.emit("config.rejected", "policies", error=type(exc).__name__)
|
|
104
|
+
return False
|
|
105
|
+
self._last = text
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
def _run(self) -> None:
|
|
109
|
+
while not self._stop.wait(self.interval):
|
|
110
|
+
self.poll()
|
|
111
|
+
|
|
112
|
+
def stop(self) -> None:
|
|
113
|
+
self._stop.set()
|
|
114
|
+
self._thread.join(timeout=self.interval + 1)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class PolicyRegistry:
|
|
118
|
+
"""A registry whose decorator resolves the named policy at each call.
|
|
119
|
+
|
|
120
|
+
Configuration updates are atomic: each in-flight call retains its resolved stack.
|
|
121
|
+
Each registered configuration compiles one shared policy, so named breaker,
|
|
122
|
+
bulkhead and limiter state is shared across its decorated functions. A replacement
|
|
123
|
+
starts a new policy generation.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
def __init__(self) -> None:
|
|
127
|
+
self._lock = _fork.ForkSafeRLock()
|
|
128
|
+
self._settings: dict[str, dict[str, Any]] = {}
|
|
129
|
+
self._versions: dict[str, int] = {}
|
|
130
|
+
self._compiled: dict[str, Policy] = {}
|
|
131
|
+
self._exceptions: dict[str, type[BaseException]] = {
|
|
132
|
+
f"builtins.{name}": value
|
|
133
|
+
for name, value in vars(builtins).items()
|
|
134
|
+
if isinstance(value, type) and issubclass(value, BaseException)
|
|
135
|
+
}
|
|
136
|
+
from python_wrap import predicates
|
|
137
|
+
|
|
138
|
+
self._predicates: dict[str, Callable[..., Any]] = {
|
|
139
|
+
name: getattr(predicates, name)
|
|
140
|
+
for name in predicates.__all__
|
|
141
|
+
if name.endswith("_transient")
|
|
142
|
+
}
|
|
143
|
+
self._backends: dict[str, Any] = {}
|
|
144
|
+
|
|
145
|
+
# -- names a mapping may refer to ------------------------------------------------
|
|
146
|
+
def register_exception(self, name: str, exception: type[BaseException]) -> None:
|
|
147
|
+
"""Allow ``name`` (e.g. ``"requests.exceptions.Timeout"``) in ``on``/``exclude``."""
|
|
148
|
+
if not (isinstance(exception, type) and issubclass(exception, BaseException)):
|
|
149
|
+
raise TypeError("register_exception needs an exception class")
|
|
150
|
+
self._exceptions[name] = exception
|
|
151
|
+
|
|
152
|
+
def register_predicate(self, name: str, predicate: Callable[..., Any]) -> None:
|
|
153
|
+
"""Allow ``name`` as a ``retry_if``/``retry_if_result`` value."""
|
|
154
|
+
if not callable(predicate):
|
|
155
|
+
raise TypeError("register_predicate needs a callable")
|
|
156
|
+
self._predicates[name] = predicate
|
|
157
|
+
|
|
158
|
+
def register_backend(self, name: str, backend: Any) -> None:
|
|
159
|
+
"""Allow ``"@name"`` wherever a mapping needs a backend object."""
|
|
160
|
+
self._backends[name] = backend
|
|
161
|
+
|
|
162
|
+
def _resolve(self, key: str | None, value: Any) -> Any:
|
|
163
|
+
"""Turn names in a JSON-shaped mapping into the registered objects."""
|
|
164
|
+
if isinstance(value, Mapping):
|
|
165
|
+
return {k: self._resolve(k, v) for k, v in value.items()}
|
|
166
|
+
if key in _EXCEPTION_KEYS and isinstance(value, (str, list, tuple)):
|
|
167
|
+
names = [value] if isinstance(value, str) else list(value)
|
|
168
|
+
found = []
|
|
169
|
+
for name in names:
|
|
170
|
+
if not isinstance(name, str):
|
|
171
|
+
found.append(name)
|
|
172
|
+
elif name in self._exceptions:
|
|
173
|
+
found.append(self._exceptions[name])
|
|
174
|
+
else:
|
|
175
|
+
raise ValueError(f"unknown exception name {name!r}; register_exception it")
|
|
176
|
+
return tuple(found)
|
|
177
|
+
if key in _PREDICATE_KEYS and isinstance(value, str):
|
|
178
|
+
if value not in self._predicates:
|
|
179
|
+
raise ValueError(f"unknown predicate {value!r}; register_predicate it")
|
|
180
|
+
return self._predicates[value]
|
|
181
|
+
if isinstance(value, str) and value.startswith("@"):
|
|
182
|
+
if value[1:] not in self._backends:
|
|
183
|
+
raise ValueError(f"unknown backend {value!r}; register_backend it")
|
|
184
|
+
return self._backends[value[1:]]
|
|
185
|
+
if isinstance(value, list):
|
|
186
|
+
return [self._resolve(None, item) for item in value]
|
|
187
|
+
return value
|
|
188
|
+
|
|
189
|
+
def watch(self, source: PolicySource, interval: float = 30) -> Watch:
|
|
190
|
+
"""Poll ``source`` every ``interval`` seconds and apply each changed mapping.
|
|
191
|
+
|
|
192
|
+
A whole mapping is validated before it is applied; a bad one keeps the current
|
|
193
|
+
policies and emits ``config.rejected``. Each applied policy emits
|
|
194
|
+
``config.changed``. Runtime state carries over when a policy keeps its name: an
|
|
195
|
+
open in-process breaker stays open under the new thresholds (shared breakers
|
|
196
|
+
keep their state in the backend anyway).
|
|
197
|
+
"""
|
|
198
|
+
if interval <= 0:
|
|
199
|
+
raise ValueError("interval must be positive")
|
|
200
|
+
return Watch(self, source, interval)
|
|
201
|
+
|
|
202
|
+
def register(self, name: str, **settings: Any) -> None:
|
|
203
|
+
"""Atomically replace one named policy after validating its full configuration."""
|
|
204
|
+
self.load_from_mapping({name: settings})
|
|
205
|
+
|
|
206
|
+
def load_from_mapping(self, mapping: Mapping[str, Mapping[str, Any]]) -> None:
|
|
207
|
+
"""Validate an entire mapping before atomically applying it.
|
|
208
|
+
|
|
209
|
+
Configuration containers are copied without copying live clients or callbacks.
|
|
210
|
+
Named breaker/limiter/bulkhead instances are shared across decorated functions.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def snapshot(value: Any) -> Any:
|
|
214
|
+
if isinstance(value, Mapping):
|
|
215
|
+
return {key: snapshot(item) for key, item in value.items()}
|
|
216
|
+
if isinstance(value, list):
|
|
217
|
+
return [snapshot(item) for item in value]
|
|
218
|
+
if isinstance(value, tuple):
|
|
219
|
+
return tuple(snapshot(item) for item in value)
|
|
220
|
+
return value
|
|
221
|
+
|
|
222
|
+
staged: dict[str, dict[str, Any]] = {}
|
|
223
|
+
compiled: dict[str, Policy] = {}
|
|
224
|
+
for name, settings in mapping.items():
|
|
225
|
+
if not isinstance(name, str) or not name or not isinstance(settings, Mapping):
|
|
226
|
+
raise ValueError("policies need nonempty names and mapping configurations")
|
|
227
|
+
staged[name] = snapshot(settings)
|
|
228
|
+
compiled[name] = self._compile(name, staged[name])
|
|
229
|
+
changed = []
|
|
230
|
+
with self._lock:
|
|
231
|
+
for name, settings in staged.items():
|
|
232
|
+
if self._settings.get(name) == settings and name in self._compiled:
|
|
233
|
+
continue # unchanged: keep the generation and its live state
|
|
234
|
+
old = self._compiled.get(name)
|
|
235
|
+
if old is not None:
|
|
236
|
+
_carry_state(old, compiled[name])
|
|
237
|
+
self._settings[name] = settings
|
|
238
|
+
self._compiled[name] = compiled[name]
|
|
239
|
+
self._versions[name] = self._versions.get(name, 0) + 1
|
|
240
|
+
changed.append((name, self._versions[name]))
|
|
241
|
+
if changed and self is policies and not _health_registered:
|
|
242
|
+
_register_health()
|
|
243
|
+
for name, generation in changed:
|
|
244
|
+
_core.emit("config.changed", name, generation=generation)
|
|
245
|
+
|
|
246
|
+
def load_from_env(self, prefix: str = "PW_POLICY_") -> None:
|
|
247
|
+
"""Read NAME={JSON policy settings} from env; existing names are case-sensitive."""
|
|
248
|
+
mapping = {
|
|
249
|
+
key[len(prefix) :]: json.loads(value)
|
|
250
|
+
for key, value in os.environ.items()
|
|
251
|
+
if key.startswith(prefix)
|
|
252
|
+
}
|
|
253
|
+
self.load_from_mapping(mapping)
|
|
254
|
+
|
|
255
|
+
def describe(self, name: str | None = None) -> dict[str, Any]:
|
|
256
|
+
"""Return effective layer names and settings; do not include object reprs/secrets."""
|
|
257
|
+
with self._lock:
|
|
258
|
+
selected = self._settings if name is None else {name: self._settings[name]}
|
|
259
|
+
return {
|
|
260
|
+
key: {
|
|
261
|
+
"order": self._compiled[key].order,
|
|
262
|
+
"roles": tuple(value),
|
|
263
|
+
"generation": self._versions[key],
|
|
264
|
+
}
|
|
265
|
+
for key, value in selected.items()
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
def _compile(self, name: str, settings: Mapping[str, Any]) -> Policy:
|
|
269
|
+
from python_wrap.bulkhead import Bulkhead
|
|
270
|
+
from python_wrap.caching import memoize
|
|
271
|
+
from python_wrap.circuit import CircuitBreaker
|
|
272
|
+
from python_wrap.concurrency import RateLimiter, timeout
|
|
273
|
+
from python_wrap.quotas import shared_rate_limit
|
|
274
|
+
from python_wrap.retry import fallback, retry
|
|
275
|
+
from python_wrap.shared import resolve_shared
|
|
276
|
+
|
|
277
|
+
sb = resolve_shared(None)
|
|
278
|
+
settings = self._resolve(None, settings)
|
|
279
|
+
allowed = {"timeout", "retry", "breaker", "limiter", "bulkhead", "fallback", "cache"}
|
|
280
|
+
unknown = set(settings) - allowed
|
|
281
|
+
if unknown:
|
|
282
|
+
raise ValueError(f"unknown policy roles: {sorted(unknown)}")
|
|
283
|
+
roles: dict[str, Any] = {}
|
|
284
|
+
for role, value in settings.items():
|
|
285
|
+
if value is None:
|
|
286
|
+
continue
|
|
287
|
+
options = dict(value) if isinstance(value, Mapping) else value
|
|
288
|
+
if role == "timeout":
|
|
289
|
+
roles[role] = timeout(**options) if isinstance(options, dict) else timeout(options)
|
|
290
|
+
elif role == "retry":
|
|
291
|
+
roles[role] = retry(**options)
|
|
292
|
+
elif role == "breaker":
|
|
293
|
+
options.setdefault("name", name)
|
|
294
|
+
if sb is not None and "backend" not in options and sb.breaker() is not None:
|
|
295
|
+
options["backend"] = sb.breaker()
|
|
296
|
+
roles[role] = CircuitBreaker(**options)
|
|
297
|
+
elif role == "limiter":
|
|
298
|
+
if "backend" in options:
|
|
299
|
+
backend = options.pop("backend")
|
|
300
|
+
roles[role] = shared_rate_limit(backend, **options)
|
|
301
|
+
else:
|
|
302
|
+
if "rate" in options:
|
|
303
|
+
options["calls"] = options.pop("rate")
|
|
304
|
+
if "per" in options:
|
|
305
|
+
options["period"] = options.pop("per")
|
|
306
|
+
window = (
|
|
307
|
+
None
|
|
308
|
+
if sb is None or "calls" not in options
|
|
309
|
+
else sb.rate_window(
|
|
310
|
+
options.get("name", name), options["calls"], options.get("period", 1.0)
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
roles[role] = RateLimiter(**options, backend=window)
|
|
314
|
+
elif role == "bulkhead":
|
|
315
|
+
options.setdefault("name", name)
|
|
316
|
+
if sb is not None and "backend" not in options:
|
|
317
|
+
options["backend"] = sb.lease_backend()
|
|
318
|
+
roles[role] = Bulkhead(**options)
|
|
319
|
+
elif role == "cache":
|
|
320
|
+
roles[role] = memoize(**options)
|
|
321
|
+
else:
|
|
322
|
+
roles[role] = (
|
|
323
|
+
fallback(**options) if isinstance(options, dict) else fallback(options)
|
|
324
|
+
)
|
|
325
|
+
return policy(name=name, **roles)
|
|
326
|
+
|
|
327
|
+
def resilient(self, name: str) -> Callable[[F], F]:
|
|
328
|
+
"""Decorate with a named policy, resolving configuration at call time."""
|
|
329
|
+
import functools
|
|
330
|
+
|
|
331
|
+
from python_wrap import _core
|
|
332
|
+
|
|
333
|
+
def decorate(func: F) -> F:
|
|
334
|
+
version = -1
|
|
335
|
+
compiled: Any = None
|
|
336
|
+
lock = _fork.ForkSafeLock()
|
|
337
|
+
|
|
338
|
+
def resolve() -> Any:
|
|
339
|
+
nonlocal version, compiled
|
|
340
|
+
with self._lock:
|
|
341
|
+
if name not in self._settings:
|
|
342
|
+
raise KeyError(f"policy {name!r} is not registered")
|
|
343
|
+
current = self._versions[name]
|
|
344
|
+
selected = self._compiled[name]
|
|
345
|
+
with lock:
|
|
346
|
+
if current != version:
|
|
347
|
+
compiled = selected(func)
|
|
348
|
+
version = current
|
|
349
|
+
return compiled
|
|
350
|
+
|
|
351
|
+
if _core.is_async(func):
|
|
352
|
+
|
|
353
|
+
@functools.wraps(func)
|
|
354
|
+
async def aw(*args: Any, **kw: Any) -> Any:
|
|
355
|
+
return await resolve()(*args, **kw)
|
|
356
|
+
|
|
357
|
+
return cast(F, aw)
|
|
358
|
+
|
|
359
|
+
@functools.wraps(func)
|
|
360
|
+
def sw(*args: Any, **kw: Any) -> Any:
|
|
361
|
+
return resolve()(*args, **kw)
|
|
362
|
+
|
|
363
|
+
return cast(F, sw)
|
|
364
|
+
|
|
365
|
+
return decorate
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _carry_state(old: Policy, new: Policy) -> None:
|
|
369
|
+
"""Keep an in-process breaker's state across a reload of the same policy name."""
|
|
370
|
+
from python_wrap.circuit import CircuitBreaker
|
|
371
|
+
|
|
372
|
+
before = old._roles.get("breaker", ())
|
|
373
|
+
after = new._roles.get("breaker", ())
|
|
374
|
+
if (
|
|
375
|
+
before
|
|
376
|
+
and after
|
|
377
|
+
and isinstance(before[0], CircuitBreaker)
|
|
378
|
+
and isinstance(after[0], CircuitBreaker)
|
|
379
|
+
):
|
|
380
|
+
after[0]._adopt(before[0])
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
policies = PolicyRegistry()
|
|
384
|
+
resilient = policies.resilient
|
|
385
|
+
_health_registered = False
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _register_health() -> None:
|
|
389
|
+
"""Report each named policy's generation in `python_wrap.health.health.report()`."""
|
|
390
|
+
global _health_registered
|
|
391
|
+
from python_wrap.health import health
|
|
392
|
+
|
|
393
|
+
_health_registered = True
|
|
394
|
+
health.register_check(
|
|
395
|
+
"policies", lambda: {"healthy": True, "generations": dict(policies._versions)}
|
|
396
|
+
)
|
python_wrap/policy.py
CHANGED
|
@@ -171,6 +171,20 @@ class Policy:
|
|
|
171
171
|
roles=roles,
|
|
172
172
|
)
|
|
173
173
|
|
|
174
|
+
def explain(self, *, idempotent: bool = True) -> Any:
|
|
175
|
+
"""Describe each layer and flag risky combinations; see `python_wrap.doctor.explain`.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
idempotent: False when the protected operation must not run twice (any
|
|
179
|
+
retry is then reported as an error).
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
A `python_wrap.doctor.Report`: ``print()`` it, or check ``.ok`` in a test.
|
|
183
|
+
"""
|
|
184
|
+
from python_wrap.doctor import explain
|
|
185
|
+
|
|
186
|
+
return explain(self, idempotent=idempotent)
|
|
187
|
+
|
|
174
188
|
def __repr__(self) -> str:
|
|
175
189
|
order = " > ".join(self.order) or "(empty)"
|
|
176
190
|
label = f"{self._name!r}, " if self._name else ""
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Composable exception predicates without importing HTTP or database drivers.
|
|
2
|
+
|
|
3
|
+
Besides the building blocks (`sqlstate`, `message_contains`, `in_cause_chain`) this module
|
|
4
|
+
ships ready-made *transient error* predicates for the common database drivers:
|
|
5
|
+
`postgres_transient`, `mysql_transient`, `sqlserver_transient` and `db_transient` (their
|
|
6
|
+
union, also aware of SQLAlchemy's ``connection_invalidated`` flag). They inspect
|
|
7
|
+
attributes and error codes only, so no driver is imported.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"MYSQL_TRANSIENT_CODES",
|
|
18
|
+
"POSTGRES_TRANSIENT_SQLSTATES",
|
|
19
|
+
"SQLSERVER_TRANSIENT_CODES",
|
|
20
|
+
"SQLSERVER_TRANSIENT_SQLSTATES",
|
|
21
|
+
"Predicate",
|
|
22
|
+
"db_transient",
|
|
23
|
+
"error_code",
|
|
24
|
+
"in_cause_chain",
|
|
25
|
+
"message_contains",
|
|
26
|
+
"mysql_transient",
|
|
27
|
+
"postgres_transient",
|
|
28
|
+
"sqlserver_transient",
|
|
29
|
+
"sqlstate",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Predicate:
|
|
34
|
+
"""A callable predicate supporting short-circuit |, &, and ~ composition."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, test: Callable[[Any], bool]) -> None:
|
|
37
|
+
self.test = test
|
|
38
|
+
|
|
39
|
+
def __call__(self, value: Any) -> bool:
|
|
40
|
+
return bool(self.test(value))
|
|
41
|
+
|
|
42
|
+
def __or__(self, other: Callable[[Any], bool]) -> Predicate:
|
|
43
|
+
return Predicate(lambda value: self(value) or other(value))
|
|
44
|
+
|
|
45
|
+
def __and__(self, other: Callable[[Any], bool]) -> Predicate:
|
|
46
|
+
return Predicate(lambda value: self(value) and other(value))
|
|
47
|
+
|
|
48
|
+
def __invert__(self) -> Predicate:
|
|
49
|
+
return Predicate(lambda value: not self(value))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def message_contains(*fragments: str, case_sensitive: bool = False) -> Predicate:
|
|
53
|
+
"""Match any fragment in an exception's message (case-insensitive by default)."""
|
|
54
|
+
if not fragments or any(not text for text in fragments):
|
|
55
|
+
raise ValueError("provide nonempty message fragments")
|
|
56
|
+
needles = fragments if case_sensitive else tuple(text.casefold() for text in fragments)
|
|
57
|
+
return Predicate(
|
|
58
|
+
lambda exc: any(
|
|
59
|
+
text in (str(exc) if case_sensitive else str(exc).casefold()) for text in needles
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def sqlstate(*prefixes: str) -> Predicate:
|
|
65
|
+
"""Match SQLSTATE prefixes on .sqlstate, .pgcode, or DB-API args[0]."""
|
|
66
|
+
if not prefixes or any(not value for value in prefixes):
|
|
67
|
+
raise ValueError("provide SQLSTATE prefixes")
|
|
68
|
+
|
|
69
|
+
def test(exc: Any) -> bool:
|
|
70
|
+
args = getattr(exc, "args", ())
|
|
71
|
+
values = (
|
|
72
|
+
getattr(exc, "sqlstate", None),
|
|
73
|
+
getattr(exc, "pgcode", None),
|
|
74
|
+
args[0] if args else None,
|
|
75
|
+
)
|
|
76
|
+
return any(isinstance(value, str) and value.startswith(prefixes) for value in values)
|
|
77
|
+
|
|
78
|
+
return Predicate(test)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def in_cause_chain(test: Callable[[Any], bool]) -> Predicate:
|
|
82
|
+
"""Walk cause/context and driver .orig links, including cycles, once per exception."""
|
|
83
|
+
|
|
84
|
+
def matches(exc: Any) -> bool:
|
|
85
|
+
seen: set[int] = set()
|
|
86
|
+
queue = [exc]
|
|
87
|
+
while queue:
|
|
88
|
+
current = queue.pop()
|
|
89
|
+
if current is None or id(current) in seen:
|
|
90
|
+
continue
|
|
91
|
+
seen.add(id(current))
|
|
92
|
+
if test(current):
|
|
93
|
+
return True
|
|
94
|
+
queue.extend(
|
|
95
|
+
getattr(current, field, None) for field in ("__cause__", "__context__", "orig")
|
|
96
|
+
)
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
return Predicate(matches)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _codes_of(exc: Any, *, parse_message: bool = False) -> set[int]:
|
|
103
|
+
"""Integer error numbers carried by a DB-API exception.
|
|
104
|
+
|
|
105
|
+
MySQL drivers (PyMySQL, mysqlclient, aiomysql, asyncmy) put the server error number
|
|
106
|
+
in ``args[0]``; pymssql uses ``args[0]`` or ``.number``; pyodbc only has an ODBC
|
|
107
|
+
SQLSTATE in ``args[0]`` and the native SQL Server number in parentheses inside the
|
|
108
|
+
message, as in ``"... Deadlock victim ... (1205) (SQLExecDirectW)"``.
|
|
109
|
+
"""
|
|
110
|
+
found: set[int] = set()
|
|
111
|
+
args = getattr(exc, "args", ())
|
|
112
|
+
if args and isinstance(args[0], int) and not isinstance(args[0], bool):
|
|
113
|
+
found.add(args[0])
|
|
114
|
+
for field in ("errno", "number", "code"):
|
|
115
|
+
value = getattr(exc, field, None)
|
|
116
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
117
|
+
found.add(value)
|
|
118
|
+
if not parse_message:
|
|
119
|
+
return found
|
|
120
|
+
for text in (item for item in args if isinstance(item, str)):
|
|
121
|
+
found.update(int(code) for code in _NATIVE_CODE.findall(text))
|
|
122
|
+
return found
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_NATIVE_CODE = re.compile(r"\((\d{1,6})\)")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def error_code(*codes: int) -> Predicate:
|
|
129
|
+
"""Match driver error numbers (``args[0]``, ``.errno``, ``.number``, ``(1205)`` in text).
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
*codes: Integer server error numbers, such as MySQL 1213 or SQL Server 1205.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
A `Predicate` true when any of the codes is present on the exception itself.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
ValueError: If no code is given.
|
|
139
|
+
|
|
140
|
+
Example:
|
|
141
|
+
>>> class OperationalError(Exception): ...
|
|
142
|
+
>>> error_code(1213)(OperationalError(1213, "Deadlock found"))
|
|
143
|
+
True
|
|
144
|
+
"""
|
|
145
|
+
if not codes:
|
|
146
|
+
raise ValueError("provide at least one error code")
|
|
147
|
+
wanted = frozenset(codes)
|
|
148
|
+
return Predicate(lambda exc: bool(_codes_of(exc, parse_message=_odbc_style(exc)) & wanted))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
#: SQLSTATE prefixes worth retrying on PostgreSQL: connection exceptions (08),
|
|
152
|
+
#: serialization failure and deadlock (40001, 40P01), operator intervention such as
|
|
153
|
+
#: admin shutdown or a server still starting (57P01-57P03), too many connections
|
|
154
|
+
#: (53300) and lock_not_available (55P03).
|
|
155
|
+
POSTGRES_TRANSIENT_SQLSTATES: tuple[str, ...] = (
|
|
156
|
+
"08",
|
|
157
|
+
"40001",
|
|
158
|
+
"40P01",
|
|
159
|
+
"53300",
|
|
160
|
+
"55P03",
|
|
161
|
+
"57P01",
|
|
162
|
+
"57P02",
|
|
163
|
+
"57P03",
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
#: MySQL/MariaDB server and client error numbers worth retrying: lock wait timeout
|
|
167
|
+
#: (1205), deadlock (1213), too many connections (1040), connection/host errors
|
|
168
|
+
#: (2002, 2003, 2006 server gone away, 2013 lost connection, 2055), the 8.0 idle
|
|
169
|
+
#: disconnect (4031), read-only during failover (1290, 1836) and query interrupted by
|
|
170
|
+
#: a killed connection (1927).
|
|
171
|
+
MYSQL_TRANSIENT_CODES: frozenset[int] = frozenset(
|
|
172
|
+
{1040, 1205, 1213, 1290, 1836, 1927, 2002, 2003, 2006, 2013, 2055, 4031}
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
#: ODBC SQLSTATEs reported by pyodbc for SQL Server that are worth retrying:
|
|
176
|
+
#: communication link failures (08xxx), serialization failure / deadlock (40001) and
|
|
177
|
+
#: timeout expired (HYT00, HYT01).
|
|
178
|
+
SQLSERVER_TRANSIENT_SQLSTATES: tuple[str, ...] = ("08", "40001", "HYT00", "HYT01")
|
|
179
|
+
|
|
180
|
+
#: SQL Server and Azure SQL native error numbers documented as transient: deadlock
|
|
181
|
+
#: victim (1205), lock request timeout (1222), Azure SQL database unavailable or
|
|
182
|
+
#: reconfiguring (40613, 40197, 40501, 40540, 40544, 40549, 40550, 40551, 40552,
|
|
183
|
+
#: 40553), resource limits (10928, 10929), elastic pool busy (49918, 49919, 49920),
|
|
184
|
+
#: login failures during failover (4060, 4221) and transport
|
|
185
|
+
#: errors (64, 233, 10053, 10054, 10060, 10061).
|
|
186
|
+
SQLSERVER_TRANSIENT_CODES: frozenset[int] = frozenset(
|
|
187
|
+
{
|
|
188
|
+
64,
|
|
189
|
+
233,
|
|
190
|
+
1205,
|
|
191
|
+
1222,
|
|
192
|
+
4060,
|
|
193
|
+
4221,
|
|
194
|
+
10053,
|
|
195
|
+
10054,
|
|
196
|
+
10060,
|
|
197
|
+
10061,
|
|
198
|
+
10928,
|
|
199
|
+
10929,
|
|
200
|
+
40197,
|
|
201
|
+
40501,
|
|
202
|
+
40540,
|
|
203
|
+
40544,
|
|
204
|
+
40549,
|
|
205
|
+
40550,
|
|
206
|
+
40551,
|
|
207
|
+
40552,
|
|
208
|
+
40553,
|
|
209
|
+
40613,
|
|
210
|
+
49918,
|
|
211
|
+
49919,
|
|
212
|
+
49920,
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _has_sqlstate(exc: Any, prefixes: tuple[str, ...]) -> bool:
|
|
218
|
+
return sqlstate(*prefixes)(exc)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _is_mysql(exc: Any) -> bool:
|
|
222
|
+
module = type(exc).__module__.split(".")[0]
|
|
223
|
+
return module in {"pymysql", "MySQLdb", "aiomysql", "asyncmy", "mysql", "mariadb"}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _is_sqlserver(exc: Any) -> bool:
|
|
227
|
+
module = type(exc).__module__.split(".")[0]
|
|
228
|
+
return module in {"pyodbc", "pymssql", "_mssql", "aioodbc", "mssql_python"}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _pg(exc: Any) -> bool:
|
|
232
|
+
return _has_sqlstate(exc, POSTGRES_TRANSIENT_SQLSTATES) and not _is_sqlserver(exc)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _mysql(exc: Any) -> bool:
|
|
236
|
+
return not _is_sqlserver(exc) and bool(_codes_of(exc) & MYSQL_TRANSIENT_CODES)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _odbc_style(exc: Any) -> bool:
|
|
240
|
+
"""True for SQL Server driver errors, or any error whose args[0] is a SQLSTATE."""
|
|
241
|
+
args = getattr(exc, "args", ())
|
|
242
|
+
first = args[0] if args else None
|
|
243
|
+
return _is_sqlserver(exc) or (
|
|
244
|
+
isinstance(first, str) and len(first) == 5 and first.isalnum() and first.isupper()
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _sqlserver(exc: Any) -> bool:
|
|
249
|
+
if _is_mysql(exc):
|
|
250
|
+
return False
|
|
251
|
+
if _has_sqlstate(exc, SQLSERVER_TRANSIENT_SQLSTATES):
|
|
252
|
+
return True
|
|
253
|
+
codes = _codes_of(exc, parse_message=_odbc_style(exc))
|
|
254
|
+
return bool(codes & SQLSERVER_TRANSIENT_CODES)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _invalidated(exc: Any) -> bool:
|
|
258
|
+
return getattr(exc, "connection_invalidated", False) is True
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
#: Transient PostgreSQL errors (psycopg 2/3 ``.pgcode``/``.sqlstate``, asyncpg
|
|
262
|
+
#: ``.sqlstate``), searched through the cause chain and SQLAlchemy's ``.orig``.
|
|
263
|
+
postgres_transient: Predicate = in_cause_chain(_pg)
|
|
264
|
+
|
|
265
|
+
#: Transient MySQL/MariaDB errors by server error number, through the cause chain and
|
|
266
|
+
#: SQLAlchemy's ``.orig``. Numbers on exceptions from SQL Server drivers are ignored.
|
|
267
|
+
mysql_transient: Predicate = in_cause_chain(_mysql)
|
|
268
|
+
|
|
269
|
+
#: Transient SQL Server / Azure SQL errors (pyodbc SQLSTATE and native numbers in the
|
|
270
|
+
#: message, pymssql numbers), through the cause chain and SQLAlchemy's ``.orig``.
|
|
271
|
+
sqlserver_transient: Predicate = in_cause_chain(_sqlserver)
|
|
272
|
+
|
|
273
|
+
#: Any of the above, or a SQLAlchemy error whose ``connection_invalidated`` is True.
|
|
274
|
+
db_transient: Predicate = in_cause_chain(
|
|
275
|
+
lambda exc: _invalidated(exc) or _pg(exc) or _mysql(exc) or _sqlserver(exc)
|
|
276
|
+
)
|