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.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/chaos.py ADDED
@@ -0,0 +1,519 @@
1
+ """Fault injection for resilience code: latency, errors and canned results on demand.
2
+
3
+ Mark the calls you want to be able to break with `fault_point`, then switch faults on
4
+ from a test (``chaos.inject(...)``) or, for a game day in staging, from an environment
5
+ variable (``chaos.enable_from_env()``). With no rule active a fault point costs one
6
+ truthiness check on a tuple, and nothing is ever injected unless a rule was added, so
7
+ leaving the markers in production code is safe.
8
+
9
+ Latency waits through ``_core.sleep`` / ``_core.async_sleep``: with
10
+ ``python_wrap.testing.fake_clock`` it advances a fake clock; otherwise it sleeps for
11
+ real time.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import builtins
17
+ import fnmatch
18
+ import functools
19
+ import importlib
20
+ import json
21
+ import math
22
+ import os
23
+ import random
24
+ from collections.abc import Callable, Iterator, Mapping
25
+ from contextlib import contextmanager
26
+ from dataclasses import dataclass
27
+ from types import TracebackType
28
+ from typing import Any, TypeVar
29
+
30
+ from python_wrap import _core, _fork
31
+
32
+ __all__ = ["Fault", "FaultInjector", "chaos", "fault_point"]
33
+
34
+ F = TypeVar("F", bound=Callable[..., Any])
35
+
36
+
37
+ class _Unset:
38
+ def __repr__(self) -> str:
39
+ return "UNSET"
40
+
41
+
42
+ _UNSET = _Unset()
43
+
44
+ ExceptionSpec = BaseException | type[BaseException] | Callable[[], BaseException]
45
+
46
+
47
+ def _check_latency(latency: Any) -> float | tuple[float, float] | None:
48
+ if latency is None:
49
+ return None
50
+ if isinstance(latency, (tuple, list)):
51
+ if len(latency) != 2:
52
+ raise ValueError("latency must be seconds or a (min, max) pair")
53
+ low, high = latency
54
+ for v in (low, high):
55
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
56
+ raise ValueError("latency bounds must be finite numbers")
57
+ if low < 0 or high < low:
58
+ raise ValueError("latency (min, max) needs 0 <= min <= max")
59
+ return (float(low), float(high))
60
+ if isinstance(latency, bool) or not isinstance(latency, (int, float)):
61
+ raise ValueError("latency must be seconds or a (min, max) pair")
62
+ if not math.isfinite(latency) or latency < 0:
63
+ raise ValueError("latency must be a finite number >= 0")
64
+ return float(latency)
65
+
66
+
67
+ class Fault:
68
+ """Handle for one injection rule. Also a context manager that removes the rule.
69
+
70
+ Attributes:
71
+ name: The point name or fnmatch-style pattern the rule applies to.
72
+ injected: How many times this rule has fired.
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ injector: FaultInjector,
78
+ name: str,
79
+ latency: float | tuple[float, float] | None,
80
+ exception: ExceptionSpec | None,
81
+ rate: float,
82
+ times: int | None,
83
+ result: Any,
84
+ ) -> None:
85
+ self._injector = injector
86
+ self.name = name
87
+ self.latency = latency
88
+ self.exception = exception
89
+ self.rate = rate
90
+ self.times = times
91
+ self.result = result
92
+ self.injected = 0
93
+
94
+ @property
95
+ def active(self) -> bool:
96
+ """True while the rule is installed and has not used up ``times``."""
97
+ return self in self._injector._rules and (self.times is None or self.injected < self.times)
98
+
99
+ def remove(self) -> None:
100
+ """Remove the rule. Removing twice is harmless."""
101
+ self._injector._remove(self)
102
+
103
+ def __enter__(self) -> Fault:
104
+ return self
105
+
106
+ def __exit__(
107
+ self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
108
+ ) -> None:
109
+ self.remove()
110
+
111
+ def __repr__(self) -> str:
112
+ parts = [repr(self.name)]
113
+ if self.latency is not None:
114
+ parts.append(f"latency={self.latency}")
115
+ if self.exception is not None:
116
+ parts.append(f"exception={self.exception!r}")
117
+ if self.result is not _UNSET:
118
+ parts.append(f"result={self.result!r}")
119
+ parts.append(f"rate={self.rate}")
120
+ if self.times is not None:
121
+ parts.append(f"times={self.times}")
122
+ return f"Fault({', '.join(parts)})"
123
+
124
+ def __reduce__(self) -> Any:
125
+ _core.refuse_pickle(self, "Fault rules belong to one process.")
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class _Action:
130
+ kind: str
131
+ pattern: str
132
+ seconds: float = 0.0
133
+ exception: BaseException | None = None
134
+ result: Any = None
135
+
136
+
137
+ def _make_exception(spec: ExceptionSpec) -> BaseException:
138
+ if isinstance(spec, BaseException):
139
+ return spec
140
+ if isinstance(spec, type):
141
+ exc: BaseException = spec()
142
+ return exc
143
+ made: Any = spec()
144
+ if not isinstance(made, BaseException):
145
+ raise TypeError(f"exception factory returned {made!r}, not an exception")
146
+ return made
147
+
148
+
149
+ class FaultInjector:
150
+ """Holds the active rules and decides, per call, what to inject.
151
+
152
+ Use the process-wide instance `chaos`; create your own for isolated tests.
153
+
154
+ Args:
155
+ seed: Seed for the random source (rate decisions and latency ranges).
156
+ rng: An existing `random.Random` to use instead of ``seed``.
157
+
158
+ Attributes:
159
+ enabled: Global kill switch. While false, nothing is injected and rules are kept.
160
+ """
161
+
162
+ def __init__(self, seed: int | None = None, rng: random.Random | None = None) -> None:
163
+ self._lock = _fork.ForkSafeLock()
164
+ self._rules: tuple[Fault, ...] = () # copy-on-write: readers need no lock
165
+ self._counts: dict[str, int] = {}
166
+ self._rng = rng if rng is not None else random.Random(seed)
167
+ self.enabled = True
168
+ self._llm: Any = None
169
+ self._llm_http: Any = None
170
+
171
+ @property
172
+ def llm(self) -> Any:
173
+ """LLM-specific fault rules (`python_wrap.llm_testing.LLMFaults`) on this injector.
174
+
175
+ Example: ``chaos.llm.rate_limit("llm.*", times=2, retry_after=1)``.
176
+ """
177
+ if self._llm is None:
178
+ from python_wrap.llm_testing import LLMFaults
179
+
180
+ self._llm = LLMFaults(self)
181
+ return self._llm
182
+
183
+ @property
184
+ def llm_http(self) -> Any:
185
+ """HTTP-level LLM faults (`python_wrap.llm_http_chaos.LLMHTTPFaults`) on this injector.
186
+
187
+ Example: ``transport = chaos.llm_http.transport(inner)`` then
188
+ ``chaos.llm_http.rate_limit(times=2)``.
189
+ """
190
+ if self._llm_http is None:
191
+ from python_wrap.llm_http_chaos import LLMHTTPFaults
192
+
193
+ self._llm_http = LLMHTTPFaults(self)
194
+ return self._llm_http
195
+
196
+ def reseed(self, seed: int | None) -> None:
197
+ """Restart the random source from ``seed`` for reproducible runs."""
198
+ with self._lock:
199
+ self._rng = random.Random(seed)
200
+
201
+ def inject(
202
+ self,
203
+ name: str,
204
+ *,
205
+ latency: float | tuple[float, float] | None = None,
206
+ exception: ExceptionSpec | None = None,
207
+ rate: float = 1.0,
208
+ times: int | None = None,
209
+ result: Any = _UNSET,
210
+ ) -> Fault:
211
+ """Add a rule for the fault point(s) matching ``name``.
212
+
213
+ Args:
214
+ name: A point name or fnmatch pattern such as ``"payments.*"``.
215
+ latency: Seconds to wait before the call, or a ``(min, max)`` range.
216
+ exception: Raise this instead of calling: an instance, an exception class,
217
+ or a zero-argument factory returning an exception.
218
+ rate: Probability in ``[0, 1]`` that a matching call is affected.
219
+ times: Inject at most this many times, then the rule goes quiet.
220
+ result: Return this value instead of calling the function.
221
+
222
+ Returns:
223
+ A `Fault` handle; use it as a context manager or call ``remove()``.
224
+
225
+ Raises:
226
+ ValueError: For an empty name, nothing to inject, ``exception`` together with
227
+ ``result``, or out-of-range ``rate``/``times``/``latency``.
228
+
229
+ Example:
230
+ ```python
231
+ from python_wrap.chaos import chaos, fault_point
232
+
233
+ @fault_point("inventory.lookup")
234
+ def lookup() -> str:
235
+ return "real"
236
+
237
+ with chaos.inject("inventory.*", result="canned"):
238
+ assert lookup() == "canned"
239
+ assert lookup() == "real"
240
+ ```
241
+ """
242
+ if not isinstance(name, str) or not name:
243
+ raise ValueError("fault name must be a non-empty string")
244
+ lat = _check_latency(latency)
245
+ if lat is None and exception is None and result is _UNSET:
246
+ raise ValueError("inject() needs at least one of latency, exception, result")
247
+ if exception is not None and result is not _UNSET:
248
+ raise ValueError("exception and result are mutually exclusive")
249
+ if exception is not None and not (
250
+ isinstance(exception, BaseException)
251
+ or (isinstance(exception, type) and issubclass(exception, BaseException))
252
+ or callable(exception)
253
+ ):
254
+ raise ValueError("exception must be an instance, a class or a zero-argument factory")
255
+ if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not 0 <= rate <= 1:
256
+ raise ValueError("rate must be a number between 0 and 1")
257
+ if times is not None and (
258
+ isinstance(times, bool) or not isinstance(times, int) or times < 1
259
+ ):
260
+ raise ValueError("times must be None or an integer >= 1")
261
+ fault = Fault(self, name, lat, exception, float(rate), times, result)
262
+ with self._lock:
263
+ self._rules = (*self._rules, fault)
264
+ return fault
265
+
266
+ def _remove(self, fault: Fault) -> None:
267
+ with self._lock:
268
+ self._rules = tuple(r for r in self._rules if r is not fault)
269
+
270
+ def clear(self) -> None:
271
+ """Remove every rule and reset the injection counts."""
272
+ with self._lock:
273
+ self._rules = ()
274
+ self._counts = {}
275
+
276
+ def active(self) -> list[Fault]:
277
+ """The installed rules that can still fire, in the order they were added."""
278
+ return [f for f in self._rules if f.active]
279
+
280
+ def stats(self, name: str | None = None) -> int | dict[str, int]:
281
+ """Injection counts per fault point.
282
+
283
+ Args:
284
+ name: A point name. Omit for a ``{point: count}`` mapping of all points.
285
+
286
+ Returns:
287
+ The number of injections at ``name`` (0 if none), or the whole mapping.
288
+ """
289
+ with self._lock:
290
+ if name is None:
291
+ return dict(self._counts)
292
+ return self._counts.get(name, 0)
293
+
294
+ @contextmanager
295
+ def open_circuit(self, breaker: Any) -> Iterator[Any]:
296
+ """Force a `CircuitBreaker` open for the block, then put it back.
297
+
298
+ On exit a breaker that was closed (or half-open) is reset to closed; one that
299
+ was already open is left open.
300
+
301
+ Example:
302
+ ```python
303
+ from python_wrap import CircuitBreaker
304
+ from python_wrap.chaos import chaos
305
+
306
+ breaker = CircuitBreaker(name="db")
307
+ with chaos.open_circuit(breaker):
308
+ assert breaker.state.value == "open"
309
+ assert breaker.state.value == "closed"
310
+ ```
311
+ """
312
+ was_open = breaker.state.value == "open"
313
+ breaker.force_open()
314
+ try:
315
+ yield breaker
316
+ finally:
317
+ if not was_open:
318
+ breaker.reset()
319
+
320
+ def enable_from_env(
321
+ self, var: str = "PW_CHAOS", environ: Mapping[str, str] | None = None
322
+ ) -> list[Fault]:
323
+ """Install the rules described by a JSON list in an environment variable.
324
+
325
+ Does nothing (returns ``[]``) when the variable is unset or blank, so it is safe
326
+ to call at startup in every environment. Each rule is an object with ``name``
327
+ and any of ``latency`` (seconds or ``[min, max]``), ``exception`` (a builtin
328
+ name such as ``"ConnectionError"`` or ``"module:Class"``), ``result`` (a JSON
329
+ value), ``rate`` and ``times``. Instead of those, an LLM-shaped rule names a fault
330
+ kind in ``llm`` (``"rate_limit"``, ``"overloaded"``, ``"server_error"``,
331
+ ``"timeout"``, ``"malformed_json"``, ``"slow_first_token"``, ``"stalled_stream"``,
332
+ ``"invalid_tool_call"``, ``"refusal"``) with that kind's options as extra keys.
333
+ Rules are validated first; a bad one installs none.
334
+
335
+ Example value::
336
+
337
+ [{"name": "payments.*", "latency": 0.5, "rate": 0.1},
338
+ {"name": "inventory", "exception": "ConnectionError"},
339
+ {"name": "llm.*", "llm": "rate_limit", "retry_after": 1, "times": 2}]
340
+
341
+ Raises:
342
+ ValueError: On invalid JSON, a non-list, unknown keys, an unknown exception
343
+ or an invalid rule.
344
+ """
345
+ raw = (environ if environ is not None else os.environ).get(var, "")
346
+ if not raw.strip():
347
+ return []
348
+ try:
349
+ data = json.loads(raw)
350
+ except json.JSONDecodeError as exc:
351
+ raise ValueError(f"{var} is not valid JSON: {exc}") from exc
352
+ if not isinstance(data, list):
353
+ raise ValueError(f"{var} must be a JSON list of rule objects")
354
+ allowed = {"name", "latency", "exception", "rate", "times", "result"}
355
+ llm_base = {"name", "llm", "rate", "times"}
356
+ parsed: list[dict[str, Any]] = []
357
+ for i, item in enumerate(data):
358
+ where = f"{var} rule #{i}"
359
+ if not isinstance(item, dict):
360
+ raise ValueError(f"{where} must be an object")
361
+ if "llm" in item:
362
+ from python_wrap.llm_testing import build_rule
363
+
364
+ if "name" not in item:
365
+ raise ValueError(f"{where} is missing 'name'")
366
+ options = {k: v for k, v in item.items() if k not in llm_base}
367
+ if not isinstance(item["llm"], str):
368
+ raise ValueError(f"{where}: 'llm' must be a fault kind string")
369
+ try:
370
+ built = build_rule(item["llm"], options)
371
+ except (ValueError, TypeError) as exc:
372
+ raise ValueError(f"{where}: {exc}") from exc
373
+ shared = {k: item[k] for k in ("rate", "times") if k in item}
374
+ parsed.append({"name": item["name"], **shared, **built})
375
+ continue
376
+ unknown = set(item) - allowed
377
+ if unknown:
378
+ raise ValueError(f"{where} has unknown key(s): {', '.join(sorted(unknown))}")
379
+ if "name" not in item:
380
+ raise ValueError(f"{where} is missing 'name'")
381
+ kwargs = {k: v for k, v in item.items() if k != "name"}
382
+ if "exception" in kwargs:
383
+ kwargs["exception"] = _resolve_exception(kwargs["exception"], where)
384
+ parsed.append({"name": item["name"], **kwargs})
385
+ # Validate everything by building throwaway handles before touching our rules.
386
+ probe = FaultInjector()
387
+ try:
388
+ for kwargs in parsed:
389
+ probe.inject(**kwargs)
390
+ except (ValueError, TypeError) as exc:
391
+ raise ValueError(f"{var}: {exc}") from exc
392
+ return [self.inject(**kwargs) for kwargs in parsed]
393
+
394
+ def point(self, name: str) -> Callable[[F], F]:
395
+ """Alias of `fault_point` bound to this injector (for policy ``inner=``)."""
396
+ return fault_point(name, injector=self)
397
+
398
+ # -- internals -----------------------------------------------------------------
399
+
400
+ def _plan(self, point: str) -> list[_Action]:
401
+ actions: list[_Action] = []
402
+ with self._lock:
403
+ for rule in self._rules:
404
+ if rule.times is not None and rule.injected >= rule.times:
405
+ continue
406
+ if not fnmatch.fnmatchcase(point, rule.name):
407
+ continue
408
+ if rule.rate < 1.0 and self._rng.random() >= rule.rate:
409
+ continue
410
+ rule.injected += 1
411
+ self._counts[point] = self._counts.get(point, 0) + 1
412
+ if rule.latency is not None:
413
+ lat = rule.latency
414
+ secs = lat if isinstance(lat, float) else self._rng.uniform(lat[0], lat[1])
415
+ actions.append(_Action("latency", rule.name, seconds=secs))
416
+ if rule.exception is not None:
417
+ actions.append(
418
+ _Action("exception", rule.name, exception=_make_exception(rule.exception))
419
+ )
420
+ break
421
+ if rule.result is not _UNSET:
422
+ actions.append(_Action("result", rule.name, result=rule.result))
423
+ break
424
+ return actions
425
+
426
+
427
+ def _resolve_exception(spec: Any, where: str) -> type[BaseException]:
428
+ if not isinstance(spec, str) or not spec:
429
+ raise ValueError(f"{where}: 'exception' must be a string")
430
+ if ":" in spec:
431
+ module_name, _, attr = spec.partition(":")
432
+ try:
433
+ obj = getattr(importlib.import_module(module_name), attr)
434
+ except (ImportError, AttributeError) as exc:
435
+ raise ValueError(f"{where}: cannot import exception {spec!r}: {exc}") from exc
436
+ else:
437
+ obj = getattr(builtins, spec, None)
438
+ if not (isinstance(obj, type) and issubclass(obj, BaseException)):
439
+ raise ValueError(
440
+ f"{where}: unknown exception {spec!r} (use a builtin name or 'module:Class')"
441
+ )
442
+ return obj
443
+
444
+
445
+ chaos = FaultInjector()
446
+ """The process-wide injector used by `fault_point` unless given another."""
447
+
448
+
449
+ def _emit(point: str, action: _Action) -> None:
450
+ _core.emit("chaos.injected", point, kind=action.kind, point=point, pattern=action.pattern)
451
+
452
+
453
+ def fault_point(name: str, *, injector: FaultInjector | None = None) -> Callable[[F], F]:
454
+ """Decorator marking a call that chaos rules may slow down, break or replace.
455
+
456
+ Works on sync and async functions and keeps the signature. With no active rule it
457
+ adds a single check. Because it is a plain decorator it can sit under other
458
+ layers, e.g. ``policy(inner=fault_point("x"))``, so retries and timeouts see the
459
+ injected faults.
460
+
461
+ Args:
462
+ name: The point name that rules match (exact or fnmatch pattern).
463
+ injector: Use this injector instead of the global `chaos`.
464
+
465
+ Example:
466
+ ```python
467
+ from python_wrap import retry
468
+ from python_wrap.chaos import chaos, fault_point
469
+
470
+ @retry(max_attempts=3, delay=0, on=ConnectionError)
471
+ @fault_point("db.query")
472
+ def query() -> str:
473
+ return "rows"
474
+
475
+ with chaos.inject("db.query", exception=ConnectionError, times=2):
476
+ assert query() == "rows"
477
+ ```
478
+ """
479
+ if not isinstance(name, str) or not name:
480
+ raise ValueError("fault_point name must be a non-empty string")
481
+
482
+ def decorate(func: F) -> F:
483
+ if _core.is_async(func):
484
+
485
+ @functools.wraps(func)
486
+ async def awrapper(*args: Any, **kwargs: Any) -> Any:
487
+ inj = injector or chaos
488
+ if inj._rules and inj.enabled:
489
+ for action in inj._plan(name):
490
+ _emit(name, action)
491
+ if action.kind == "latency":
492
+ await _core.async_sleep(action.seconds)
493
+ elif action.kind == "exception":
494
+ assert action.exception is not None
495
+ raise action.exception
496
+ else:
497
+ return action.result
498
+ return await func(*args, **kwargs)
499
+
500
+ return awrapper # type: ignore[return-value]
501
+
502
+ @functools.wraps(func)
503
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
504
+ inj = injector or chaos
505
+ if inj._rules and inj.enabled:
506
+ for action in inj._plan(name):
507
+ _emit(name, action)
508
+ if action.kind == "latency":
509
+ _core.sleep(action.seconds)
510
+ elif action.kind == "exception":
511
+ assert action.exception is not None
512
+ raise action.exception
513
+ else:
514
+ return action.result
515
+ return func(*args, **kwargs)
516
+
517
+ return wrapper # type: ignore[return-value]
518
+
519
+ return decorate