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/alerts.py ADDED
@@ -0,0 +1,293 @@
1
+ """Alert a chat webhook when a circuit breaker opens.
2
+
3
+ `WebhookAlerter` listens for circuit state changes and posts a short message to a
4
+ webhook (Slack, Microsoft Teams, or a generic JSON endpoint). Delivery happens on a
5
+ background daemon thread so the code path that tripped the breaker never waits on the
6
+ network, and a failed delivery is logged, never raised. Each breaker is rate limited by
7
+ a cooldown so a flapping dependency produces one alert, not hundreds.
8
+
9
+ Payloads contain only the breaker name, the states, a timestamp and the static
10
+ ``context`` you supply. Exception messages, URLs and credentials are never included.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import logging
17
+ import threading
18
+ from collections.abc import Callable, Iterable, Mapping
19
+ from datetime import datetime, timezone
20
+ from typing import Any, cast
21
+ from urllib.parse import urlsplit
22
+
23
+ from python_wrap import _core, _fork
24
+ from python_wrap._core import Event
25
+ from python_wrap.circuit import CircuitBreaker, CircuitState
26
+ from python_wrap.events import subscribe
27
+
28
+ __all__ = ["Sender", "WebhookAlerter"]
29
+
30
+ Sender = Callable[[str, bytes, Mapping[str, str]], None]
31
+ """Signature of ``sender``: ``sender(url, body_bytes, headers)``. Raise to signal failure."""
32
+
33
+ _FORMATS = ("json", "teams", "slack")
34
+ _STATES = ("closed", "open", "half_open")
35
+ _log = logging.getLogger("python_wrap")
36
+
37
+
38
+ def _redact(url: str) -> str:
39
+ """Keep only scheme and host: webhook paths and query strings are secrets."""
40
+ parts = urlsplit(url)
41
+ return f"{parts.scheme}://{parts.hostname or '?'}/..."
42
+
43
+
44
+ def _state_name(state: object) -> str:
45
+ return str(getattr(state, "value", state))
46
+
47
+
48
+ class WebhookAlerter:
49
+ """Post a chat message when a circuit breaker reaches a chosen state.
50
+
51
+ Use it as an ``on_state_change`` listener, or call `install` to receive every
52
+ breaker's ``circuit.state_changed`` event in the process. After an alert for a
53
+ breaker was sent, its return to ``closed`` sends a recovery message (unless
54
+ ``include_recovery=False``).
55
+
56
+ Args:
57
+ url: Webhook URL (``http`` or ``https``). Never logged in full.
58
+ format: ``"json"`` (plain dict), ``"teams"`` (Adaptive Card message) or
59
+ ``"slack"`` (``{"text": ...}``).
60
+ on: States that trigger an alert, as strings or `CircuitState` values.
61
+ cooldown: Minimum seconds between alerts for the same breaker.
62
+ timeout: Network timeout in seconds for the default sender.
63
+ sender: Replacement delivery function ``sender(url, body_bytes, headers)``,
64
+ mainly for tests. It runs on a background thread. The default POSTs with
65
+ `urllib.request`.
66
+ include_recovery: Send a "closed again" message after an alerted open.
67
+ context: Static key/values (service, environment, ...) added to every message.
68
+
69
+ Raises:
70
+ ValueError: For an unknown ``format`` or state, a non-http URL, or a
71
+ negative ``cooldown`` / non-positive ``timeout``.
72
+
73
+ Example:
74
+ ```python
75
+ from python_wrap import CircuitBreaker
76
+ from python_wrap.alerts import WebhookAlerter
77
+
78
+ sent = []
79
+ alerter = WebhookAlerter(
80
+ "https://chat.example.com/hooks/abc",
81
+ format="slack",
82
+ sender=lambda url, body, headers: sent.append(body),
83
+ context={"service": "billing", "env": "prod"},
84
+ )
85
+ breaker = CircuitBreaker(failure_threshold=1, name="payments", on_state_change=alerter)
86
+
87
+ @breaker
88
+ def charge() -> None:
89
+ raise ConnectionError("down")
90
+
91
+ try:
92
+ charge()
93
+ except ConnectionError:
94
+ pass
95
+ assert alerter.flush(2)
96
+ assert len(sent) == 1 and b"payments" in sent[0]
97
+ ```
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ url: str,
103
+ *,
104
+ format: str = "json",
105
+ on: Iterable[str | CircuitState] = ("open",),
106
+ cooldown: float = 300.0,
107
+ timeout: float = 5.0,
108
+ sender: Sender | None = None,
109
+ include_recovery: bool = True,
110
+ context: Mapping[str, Any] | None = None,
111
+ ) -> None:
112
+ if urlsplit(url).scheme not in ("http", "https"):
113
+ raise ValueError("url must be an http or https URL")
114
+ if format not in _FORMATS:
115
+ raise ValueError(f"format must be one of {_FORMATS}")
116
+ states = frozenset(_state_name(s) for s in on)
117
+ if not states <= set(_STATES):
118
+ raise ValueError(f"on must contain only {_STATES}")
119
+ if cooldown < 0:
120
+ raise ValueError("cooldown must be >= 0")
121
+ if timeout <= 0:
122
+ raise ValueError("timeout must be > 0")
123
+ self._url, self.format, self.on = url, format, states
124
+ self.cooldown, self.timeout = float(cooldown), float(timeout)
125
+ self.include_recovery = include_recovery
126
+ self.context: dict[str, Any] = dict(context or {})
127
+ self._sender: Sender = sender if sender is not None else self._post
128
+ self._lock = _fork.ForkSafeLock()
129
+ self._idle = threading.Condition(cast(Any, self._lock))
130
+ self._last_alert: dict[str, float] = {}
131
+ self._alerted: set[str] = set()
132
+ self._pending = 0
133
+ self._unsubscribe: Callable[[], None] | None = None
134
+ _fork.register(self)
135
+
136
+ def _reset_after_fork(self) -> None:
137
+ self._pending = 0
138
+ self._unsubscribe = None
139
+
140
+ # -- wiring ------------------------------------------------------------------------
141
+ def __call__(self, breaker: CircuitBreaker, old: CircuitState, new: CircuitState) -> None:
142
+ """``on_state_change`` listener entry point."""
143
+ self.notify(breaker.name, _state_name(old), _state_name(new))
144
+
145
+ def install(self) -> WebhookAlerter:
146
+ """Subscribe to ``circuit.state_changed`` events for every breaker. Idempotent."""
147
+ with self._lock:
148
+ if self._unsubscribe is None:
149
+ self._unsubscribe = subscribe(self._on_event)
150
+ return self
151
+
152
+ def close(self) -> None:
153
+ """Unsubscribe from events. Pending deliveries still complete."""
154
+ with self._lock:
155
+ unsubscribe, self._unsubscribe = self._unsubscribe, None
156
+ if unsubscribe is not None:
157
+ unsubscribe()
158
+
159
+ def _on_event(self, event: Event) -> None:
160
+ if event.name == "circuit.state_changed":
161
+ self.notify(
162
+ event.function, _state_name(event.fields["old"]), _state_name(event.fields["new"])
163
+ )
164
+
165
+ # -- decision ----------------------------------------------------------------------
166
+ def notify(self, name: str, old: str, new: str) -> bool:
167
+ """Decide whether a transition warrants a message, and queue it.
168
+
169
+ Args:
170
+ name: Breaker name.
171
+ old: Previous state (``"closed"``, ``"open"`` or ``"half_open"``).
172
+ new: New state.
173
+
174
+ Returns:
175
+ True if a message was queued.
176
+ """
177
+ kind: str | None = None
178
+ with self._lock:
179
+ now = _core.monotonic()
180
+ if new in self.on:
181
+ last = self._last_alert.get(name)
182
+ if last is None or now - last >= self.cooldown:
183
+ self._last_alert[name] = now
184
+ self._alerted.add(name)
185
+ kind = "alert"
186
+ elif new == "closed" and self.include_recovery and name in self._alerted:
187
+ self._alerted.discard(name)
188
+ kind = "recovery"
189
+ if kind is None:
190
+ return False
191
+ self._dispatch(self._payload(kind, name, old, new))
192
+ return True
193
+
194
+ # -- payloads ----------------------------------------------------------------------
195
+ def _payload(self, kind: str, name: str, old: str, new: str) -> dict[str, Any]:
196
+ stamp = datetime.fromtimestamp(_core.wall_time(), tz=timezone.utc).strftime(
197
+ "%Y-%m-%dT%H:%M:%SZ"
198
+ )
199
+ if kind == "recovery":
200
+ text = f"Circuit breaker '{name}' is closed again"
201
+ else:
202
+ text = f"Circuit breaker '{name}' is now {new.upper()}"
203
+ if self.format == "slack":
204
+ lines = [text, f"time: {stamp}"]
205
+ lines += [f"{k}: {v}" for k, v in self.context.items()]
206
+ # Slack treats <...> as links and mentions (<!channel>); escape so a breaker
207
+ # name or context value can never ping a channel or render a link.
208
+ return {"text": _slack_escape("\n".join(lines))}
209
+ if self.format == "teams":
210
+ facts = [
211
+ {"title": "Breaker", "value": name},
212
+ {"title": "State", "value": new},
213
+ {"title": "Time", "value": stamp},
214
+ *({"title": str(k), "value": str(v)} for k, v in self.context.items()),
215
+ ]
216
+ card = {
217
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
218
+ "type": "AdaptiveCard",
219
+ "version": "1.4",
220
+ "body": [
221
+ {"type": "TextBlock", "text": text, "weight": "Bolder", "wrap": True},
222
+ {"type": "FactSet", "facts": facts},
223
+ ],
224
+ }
225
+ return {
226
+ "type": "message",
227
+ "attachments": [
228
+ {"contentType": "application/vnd.microsoft.card.adaptive", "content": card}
229
+ ],
230
+ }
231
+ return {
232
+ "text": text,
233
+ "kind": kind,
234
+ "breaker": name,
235
+ "state": new,
236
+ "previous_state": old,
237
+ "time": stamp,
238
+ "context": dict(self.context),
239
+ }
240
+
241
+ # -- delivery ----------------------------------------------------------------------
242
+ def _dispatch(self, payload: dict[str, Any]) -> None:
243
+ body = json.dumps(payload, default=str).encode()
244
+ with self._lock:
245
+ self._pending += 1
246
+ try:
247
+ threading.Thread(
248
+ target=self._deliver, args=(body,), daemon=True, name="python-wrap-alert"
249
+ ).start()
250
+ except BaseException:
251
+ self._done()
252
+ raise
253
+
254
+ def _done(self) -> None:
255
+ with self._idle:
256
+ self._pending -= 1
257
+ self._idle.notify_all()
258
+
259
+ def _deliver(self, body: bytes) -> None:
260
+ try:
261
+ self._sender(self._url, body, {"Content-Type": "application/json"})
262
+ except Exception as exc:
263
+ # Only the exception type: messages from HTTP clients often embed the URL.
264
+ _log.warning(
265
+ "circuit alert delivery to %s failed (%s)", _redact(self._url), type(exc).__name__
266
+ )
267
+ finally:
268
+ self._done()
269
+
270
+ def _post(self, url: str, body: bytes, headers: Mapping[str, str]) -> None:
271
+ import urllib.request
272
+
273
+ request = urllib.request.Request(url, data=body, headers=dict(headers), method="POST")
274
+ # The scheme is validated as http/https in __init__.
275
+ with urllib.request.urlopen(request, timeout=self.timeout) as response: # nosec B310
276
+ response.read()
277
+
278
+ def flush(self, timeout: float | None = None) -> bool:
279
+ """Wait until queued deliveries finish.
280
+
281
+ Args:
282
+ timeout: Seconds to wait (real time); ``None`` waits indefinitely.
283
+
284
+ Returns:
285
+ True if nothing is pending any more.
286
+ """
287
+ with self._idle:
288
+ return self._idle.wait_for(lambda: self._pending == 0, timeout)
289
+
290
+
291
+ def _slack_escape(text: str) -> str:
292
+ """Escape the three characters Slack's message formatting treats as control."""
293
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")