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
@@ -0,0 +1,663 @@
1
+ """Export the event stream as Prometheus text, prometheus_client collectors or StatsD.
2
+
3
+ `PrometheusExporter` subscribes to the process-wide event stream
4
+ (`python_wrap.events`), aggregates it into counters, gauges and histograms with bounded
5
+ label cardinality, and renders the Prometheus text exposition format 0.0.4 using only the
6
+ standard library. It can also serve itself as a WSGI or ASGI app, or register as a
7
+ collector with the optional ``prometheus_client`` package. `StatsDExporter` sends the same
8
+ events as fire-and-forget UDP datagrams.
9
+
10
+ Labels never include exception messages, arguments, cache keys or other payloads: only
11
+ event names, function names, breaker names and fixed kinds.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import importlib
17
+ import itertools
18
+ import random
19
+ import re
20
+ import socket
21
+ from collections.abc import Callable, Iterable, Mapping
22
+ from dataclasses import dataclass
23
+ from typing import Any, Literal
24
+
25
+ from python_wrap import _fork
26
+ from python_wrap.events import Event, subscribe
27
+ from python_wrap.health import HealthRegistry, health
28
+
29
+ __all__ = ["CONTENT_TYPE", "PrometheusExporter", "StatsDExporter"]
30
+
31
+ #: Content type of the Prometheus text exposition format served by the exporter.
32
+ CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
33
+
34
+ DEFAULT_BUCKETS: tuple[float, ...] = (
35
+ 0.005,
36
+ 0.01,
37
+ 0.025,
38
+ 0.05,
39
+ 0.1,
40
+ 0.25,
41
+ 0.5,
42
+ 1.0,
43
+ 2.5,
44
+ 5.0,
45
+ 10.0,
46
+ 30.0,
47
+ 60.0,
48
+ )
49
+
50
+ _STATE_VALUES = {"closed": 0, "half_open": 1, "open": 2}
51
+ _REJECTION_KINDS = {
52
+ "circuit.rejected": "circuit",
53
+ "rate_limit.rejected": "rate_limit",
54
+ "bulkhead.rejected": "bulkhead",
55
+ }
56
+ _NAMESPACE_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
57
+
58
+ Labels = tuple[tuple[str, str], ...]
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class _Hist:
63
+ """A histogram value: finite upper bounds, cumulative counts (incl. +Inf), sum."""
64
+
65
+ bounds: tuple[float, ...]
66
+ cumulative: tuple[int, ...]
67
+ total: float
68
+
69
+
70
+ @dataclass
71
+ class _Family:
72
+ name: str
73
+ kind: str # counter | gauge | histogram
74
+ help: str
75
+ series: list[tuple[Labels, float | _Hist]]
76
+
77
+
78
+ class _Meta:
79
+ """Static description of one metric family and its live series."""
80
+
81
+ def __init__(self, kind: str, help_text: str, label_names: tuple[str, ...]) -> None:
82
+ self.kind = kind
83
+ self.help = help_text
84
+ self.label_names = label_names
85
+ self.values: dict[tuple[str, ...], Any] = {}
86
+
87
+
88
+ def _num(value: float) -> str:
89
+ if value != value:
90
+ return "NaN"
91
+ if value in (float("inf"), float("-inf")):
92
+ return "+Inf" if value > 0 else "-Inf"
93
+ if float(value).is_integer() and abs(value) < 1e15:
94
+ return str(int(value))
95
+ return repr(float(value))
96
+
97
+
98
+ def _escape_label(value: str) -> str:
99
+ return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
100
+
101
+
102
+ def _escape_help(value: str) -> str:
103
+ return value.replace("\\", "\\\\").replace("\n", "\\n")
104
+
105
+
106
+ def _fmt_labels(labels: Labels, extra: tuple[tuple[str, str], ...] = ()) -> str:
107
+ items = labels + extra
108
+ if not items:
109
+ return ""
110
+ return "{" + ",".join(f'{k}="{_escape_label(v)}"' for k, v in items) + "}"
111
+
112
+
113
+ def _state_name(value: Any) -> str:
114
+ return str(getattr(value, "value", value))
115
+
116
+
117
+ def _number(value: Any) -> float | None:
118
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
119
+ return None
120
+ return float(value)
121
+
122
+
123
+ class PrometheusExporter:
124
+ """Aggregate decorator events into Prometheus metrics.
125
+
126
+ Metric reference (``{ns}`` is the namespace):
127
+
128
+ * ``{ns}_events_total{event,function}`` counter of every event.
129
+ * ``{ns}_retry_attempts_total{function}``, ``{ns}_retry_gave_up_total{function}``,
130
+ ``{ns}_timeouts_total{function}`` counters.
131
+ * ``{ns}_rejections_total{kind,function}`` counter; kind is ``circuit``,
132
+ ``rate_limit`` or ``bulkhead``.
133
+ * ``{ns}_cache_hits_total{function}`` and ``{ns}_cache_misses_total{function}``.
134
+ * ``{ns}_circuit_state{breaker}`` gauge: 0 closed, 1 half_open, 2 open.
135
+ * ``{ns}_retry_wait_seconds`` histogram of delays before a retry.
136
+ * ``{ns}_periodic_run_seconds{function}`` histogram of periodic run durations.
137
+ * ``{ns}_health_up{component}``, ``{ns}_bulkhead_active{component}`` and
138
+ ``{ns}_bulkhead_waiting{component}`` gauges, read from ``registry`` at render time.
139
+ * ``{ns}_dropped_series_total`` counter of label sets dropped by ``max_series``.
140
+
141
+ Args:
142
+ namespace: Metric name prefix.
143
+ registry: `HealthRegistry` read at render time; ``None`` disables live gauges.
144
+ buckets: Upper bounds (seconds) of the histograms, ascending.
145
+ max_series: Maximum number of distinct label sets kept across all metrics. New
146
+ label sets beyond it are dropped and counted.
147
+
148
+ Raises:
149
+ ValueError: If ``namespace`` is not a valid metric prefix, ``buckets`` is empty or
150
+ not strictly ascending, or ``max_series`` is below 1.
151
+
152
+ Example:
153
+ >>> from python_wrap import _core
154
+ >>> with PrometheusExporter(registry=None) as exporter:
155
+ ... _core.emit("cache.hit", "load")
156
+ ... "python_wrap_cache_hits_total" in exporter.render()
157
+ True
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ *,
163
+ namespace: str = "python_wrap",
164
+ registry: HealthRegistry | None = health,
165
+ buckets: Iterable[float] = DEFAULT_BUCKETS,
166
+ max_series: int = 10_000,
167
+ ) -> None:
168
+ if not _NAMESPACE_RE.match(namespace):
169
+ raise ValueError("namespace must match [a-zA-Z_][a-zA-Z0-9_]*")
170
+ bounds = tuple(float(b) for b in buckets)
171
+ if not bounds or any(a >= b for a, b in itertools.pairwise(bounds)):
172
+ raise ValueError("buckets must be non-empty and strictly ascending")
173
+ if max_series < 1:
174
+ raise ValueError("max_series must be at least 1")
175
+ self.namespace = namespace
176
+ self.registry = registry
177
+ self.buckets = bounds
178
+ self.max_series = max_series
179
+ self._lock = _fork.ForkSafeLock()
180
+ self._series = 0
181
+ self._dropped = 0
182
+ self._unsubscribe: Callable[[], None] | None = None
183
+ ns = namespace
184
+ self._meta: dict[str, _Meta] = {
185
+ f"{ns}_events_total": _Meta(
186
+ "counter", "Events published by python_wrap decorators.", ("event", "function")
187
+ ),
188
+ f"{ns}_retry_attempts_total": _Meta(
189
+ "counter", "Failed attempts that were followed by a retry.", ("function",)
190
+ ),
191
+ f"{ns}_retry_gave_up_total": _Meta(
192
+ "counter", "Calls whose retries were exhausted.", ("function",)
193
+ ),
194
+ f"{ns}_timeouts_total": _Meta(
195
+ "counter", "Calls that exceeded their time limit.", ("function",)
196
+ ),
197
+ f"{ns}_rejections_total": _Meta(
198
+ "counter",
199
+ "Calls refused by a circuit breaker, rate limiter or bulkhead.",
200
+ ("kind", "function"),
201
+ ),
202
+ f"{ns}_cache_hits_total": _Meta("counter", "Cache hits.", ("function",)),
203
+ f"{ns}_cache_misses_total": _Meta("counter", "Cache misses.", ("function",)),
204
+ f"{ns}_circuit_state": _Meta(
205
+ "gauge", "Circuit breaker state: 0 closed, 1 half_open, 2 open.", ("breaker",)
206
+ ),
207
+ f"{ns}_retry_wait_seconds": _Meta(
208
+ "histogram", "Delay before the next retry attempt in seconds.", ()
209
+ ),
210
+ f"{ns}_periodic_run_seconds": _Meta(
211
+ "histogram", "Duration of periodic function runs in seconds.", ("function",)
212
+ ),
213
+ }
214
+
215
+ # ------------------------------------------------------------------ lifecycle
216
+
217
+ def install(self) -> PrometheusExporter:
218
+ """Subscribe to the event stream. Calling it twice has no extra effect.
219
+
220
+ Returns:
221
+ This exporter.
222
+ """
223
+ with self._lock:
224
+ if self._unsubscribe is None:
225
+ self._unsubscribe = subscribe(self._on_event)
226
+ return self
227
+
228
+ def close(self) -> None:
229
+ """Unsubscribe. Collected values stay available to `render`."""
230
+ with self._lock:
231
+ unsubscribe, self._unsubscribe = self._unsubscribe, None
232
+ if unsubscribe is not None:
233
+ unsubscribe()
234
+
235
+ def __enter__(self) -> PrometheusExporter:
236
+ return self.install()
237
+
238
+ def __exit__(self, *exc: object) -> None:
239
+ self.close()
240
+
241
+ # ------------------------------------------------------------------ recording
242
+
243
+ def _slot(self, name: str, labels: tuple[str, ...]) -> tuple[_Meta, bool]:
244
+ """Return (meta, ok); ok is False when the series was dropped. Lock held."""
245
+ meta = self._meta[name]
246
+ if labels in meta.values:
247
+ return meta, True
248
+ if self._series >= self.max_series:
249
+ self._dropped += 1
250
+ return meta, False
251
+ self._series += 1
252
+ return meta, True
253
+
254
+ def _inc(self, name: str, labels: tuple[str, ...]) -> None:
255
+ meta, ok = self._slot(name, labels)
256
+ if ok:
257
+ meta.values[labels] = meta.values.get(labels, 0) + 1
258
+
259
+ def _set(self, name: str, labels: tuple[str, ...], value: float) -> None:
260
+ meta, ok = self._slot(name, labels)
261
+ if ok:
262
+ meta.values[labels] = value
263
+
264
+ def _observe(self, name: str, labels: tuple[str, ...], value: float) -> None:
265
+ meta, ok = self._slot(name, labels)
266
+ if not ok:
267
+ return
268
+ state = meta.values.get(labels)
269
+ if state is None:
270
+ state = [[0] * (len(self.buckets) + 1), 0.0]
271
+ meta.values[labels] = state
272
+ counts: list[int] = state[0]
273
+ for i, bound in enumerate(self.buckets):
274
+ if value <= bound:
275
+ counts[i] += 1
276
+ break
277
+ else:
278
+ counts[-1] += 1
279
+ state[1] += value
280
+
281
+ def _on_event(self, event: Event) -> None:
282
+ ns = self.namespace
283
+ name, fn, fields = event.name, event.function, event.fields
284
+ with self._lock:
285
+ self._inc(f"{ns}_events_total", (name, fn))
286
+ if name == "retry.attempt_failed":
287
+ self._inc(f"{ns}_retry_attempts_total", (fn,))
288
+ delay = _number(fields.get("next_delay"))
289
+ if delay is not None and delay >= 0:
290
+ self._observe(f"{ns}_retry_wait_seconds", (), delay)
291
+ elif name == "retry.gave_up":
292
+ self._inc(f"{ns}_retry_gave_up_total", (fn,))
293
+ elif name == "timeout.expired":
294
+ self._inc(f"{ns}_timeouts_total", (fn,))
295
+ elif name in _REJECTION_KINDS:
296
+ self._inc(f"{ns}_rejections_total", (_REJECTION_KINDS[name], fn))
297
+ elif name == "cache.hit":
298
+ self._inc(f"{ns}_cache_hits_total", (fn,))
299
+ elif name == "cache.miss":
300
+ self._inc(f"{ns}_cache_misses_total", (fn,))
301
+ elif name == "circuit.state_changed":
302
+ state = _STATE_VALUES.get(_state_name(fields.get("new")))
303
+ if state is not None:
304
+ self._set(f"{ns}_circuit_state", (fn,), state)
305
+ elif name == "periodic.run":
306
+ seconds = _number(fields.get("seconds"))
307
+ if seconds is not None and seconds >= 0:
308
+ self._observe(f"{ns}_periodic_run_seconds", (fn,), seconds)
309
+
310
+ # ------------------------------------------------------------------ reading
311
+
312
+ def _collect(self) -> list[_Family]:
313
+ families: list[_Family] = []
314
+ with self._lock:
315
+ for name, meta in self._meta.items():
316
+ series: list[tuple[Labels, float | _Hist]] = []
317
+ for values in sorted(meta.values):
318
+ labels: Labels = tuple(zip(meta.label_names, values, strict=True))
319
+ raw = meta.values[values]
320
+ if meta.kind == "histogram":
321
+ running = 0
322
+ cumulative: list[int] = []
323
+ for count in raw[0]:
324
+ running += count
325
+ cumulative.append(running)
326
+ series.append((labels, _Hist(self.buckets, tuple(cumulative), raw[1])))
327
+ else:
328
+ series.append((labels, raw))
329
+ if series:
330
+ families.append(_Family(name, meta.kind, meta.help, series))
331
+ dropped = self._dropped
332
+ families.append(
333
+ _Family(
334
+ f"{self.namespace}_dropped_series_total",
335
+ "counter",
336
+ "Label sets dropped because max_series was reached.",
337
+ [((), dropped)],
338
+ )
339
+ )
340
+ families.extend(self._health_families())
341
+ families.sort(key=lambda f: f.name)
342
+ return families
343
+
344
+ def _health_families(self) -> list[_Family]:
345
+ if self.registry is None:
346
+ return []
347
+ report = self.registry.report()
348
+ ns = self.namespace
349
+ up: list[tuple[Labels, float | _Hist]] = []
350
+ active: list[tuple[Labels, float | _Hist]] = []
351
+ waiting: list[tuple[Labels, float | _Hist]] = []
352
+ for component in sorted(report):
353
+ info = report[component]
354
+ labels: Labels = (("component", component),)
355
+ up.append((labels, 1 if info.get("healthy") else 0))
356
+ a, w = _number(info.get("active")), _number(info.get("waiting"))
357
+ if a is not None and w is not None:
358
+ active.append((labels, a))
359
+ waiting.append((labels, w))
360
+ out: list[_Family] = []
361
+ if up:
362
+ out.append(
363
+ _Family(
364
+ f"{ns}_health_up", "gauge", "1 when the registered component is healthy.", up
365
+ )
366
+ )
367
+ if active:
368
+ out.append(
369
+ _Family(f"{ns}_bulkhead_active", "gauge", "Calls running in a bulkhead.", active)
370
+ )
371
+ out.append(
372
+ _Family(
373
+ f"{ns}_bulkhead_waiting", "gauge", "Calls waiting for a bulkhead slot.", waiting
374
+ )
375
+ )
376
+ return out
377
+
378
+ def render(self) -> str:
379
+ """Return the metrics in Prometheus text exposition format 0.0.4.
380
+
381
+ Output is deterministic: families sorted by name, series by label values.
382
+
383
+ Returns:
384
+ The exposition text, ending with a newline.
385
+ """
386
+ lines: list[str] = []
387
+ for fam in self._collect():
388
+ lines.append(f"# HELP {fam.name} {_escape_help(fam.help)}")
389
+ lines.append(f"# TYPE {fam.name} {fam.kind}")
390
+ for labels, value in fam.series:
391
+ if isinstance(value, _Hist):
392
+ for bound, count in zip(value.bounds, value.cumulative, strict=False):
393
+ le = (("le", _num(bound)),)
394
+ lines.append(f"{fam.name}_bucket{_fmt_labels(labels, le)} {count}")
395
+ inf = (("le", "+Inf"),)
396
+ lines.append(
397
+ f"{fam.name}_bucket{_fmt_labels(labels, inf)} {value.cumulative[-1]}"
398
+ )
399
+ lines.append(f"{fam.name}_sum{_fmt_labels(labels)} {_num(value.total)}")
400
+ lines.append(f"{fam.name}_count{_fmt_labels(labels)} {value.cumulative[-1]}")
401
+ else:
402
+ lines.append(f"{fam.name}{_fmt_labels(labels)} {_num(value)}")
403
+ return "\n".join(lines) + "\n"
404
+
405
+ def snapshot(self) -> dict[str, list[dict[str, Any]]]:
406
+ """Return the metric values as JSON-serialisable data (histograms as count/sum)."""
407
+ out: dict[str, list[dict[str, Any]]] = {}
408
+ for fam in self._collect():
409
+ rows: list[dict[str, Any]] = []
410
+ for labels, value in fam.series:
411
+ row: dict[str, Any] = {"labels": dict(labels)}
412
+ if isinstance(value, _Hist):
413
+ row["count"] = value.cumulative[-1]
414
+ row["sum"] = value.total
415
+ else:
416
+ row["value"] = value
417
+ rows.append(row)
418
+ out[fam.name] = rows
419
+ return out
420
+
421
+ # ------------------------------------------------------------------ serving
422
+
423
+ def wsgi_app(
424
+ self, environ: Mapping[str, Any], start_response: Callable[..., Any]
425
+ ) -> list[bytes]:
426
+ """WSGI application serving the metrics on ``/metrics`` (or ``/`` when mounted).
427
+
428
+ Args:
429
+ environ: The WSGI environ.
430
+ start_response: The WSGI start_response callable.
431
+
432
+ Returns:
433
+ The response body chunks.
434
+ """
435
+ path = str(environ.get("PATH_INFO", ""))
436
+ method = str(environ.get("REQUEST_METHOD", "GET")).upper()
437
+ status, body = self._respond(method, path)
438
+ headers = [("Content-Type", CONTENT_TYPE), ("Content-Length", str(len(body)))]
439
+ start_response(status, headers)
440
+ return [] if method == "HEAD" else [body]
441
+
442
+ async def asgi_app(
443
+ self, scope: Mapping[str, Any], receive: Callable[..., Any], send: Callable[..., Any]
444
+ ) -> None:
445
+ """ASGI application serving the metrics on ``/metrics`` (or ``/`` when mounted).
446
+
447
+ Args:
448
+ scope: The ASGI scope.
449
+ receive: The ASGI receive callable.
450
+ send: The ASGI send callable.
451
+ """
452
+ if scope.get("type") == "lifespan":
453
+ while True:
454
+ message = await receive()
455
+ if message["type"] == "lifespan.startup":
456
+ await send({"type": "lifespan.startup.complete"})
457
+ else:
458
+ await send({"type": "lifespan.shutdown.complete"})
459
+ return
460
+ if scope.get("type") != "http":
461
+ return
462
+ method = str(scope.get("method", "GET")).upper()
463
+ status, body = self._respond(method, str(scope.get("path", "")))
464
+ code = int(status.split(" ", 1)[0])
465
+ headers = [
466
+ (b"content-type", CONTENT_TYPE.encode("ascii")),
467
+ (b"content-length", str(len(body)).encode("ascii")),
468
+ ]
469
+ await send({"type": "http.response.start", "status": code, "headers": headers})
470
+ await send({"type": "http.response.body", "body": b"" if method == "HEAD" else body})
471
+
472
+ def _respond(self, method: str, path: str) -> tuple[str, bytes]:
473
+ if path not in ("", "/", "/metrics"):
474
+ return "404 Not Found", b"not found\n"
475
+ if method not in ("GET", "HEAD"):
476
+ return "405 Method Not Allowed", b"method not allowed\n"
477
+ return "200 OK", self.render().encode("utf-8")
478
+
479
+ # ------------------------------------------------------------------ bridge
480
+
481
+ def register_with_prometheus_client(self, registry: Any = None) -> Any:
482
+ """Register a collector yielding these metrics with ``prometheus_client``.
483
+
484
+ The package is imported lazily; it is not a dependency of python-wrap.
485
+
486
+ Args:
487
+ registry: A ``CollectorRegistry``; defaults to ``prometheus_client.REGISTRY``.
488
+
489
+ Returns:
490
+ The registered collector (pass it to ``registry.unregister`` to remove it).
491
+
492
+ Raises:
493
+ ImportError: If ``prometheus_client`` is not installed.
494
+ """
495
+ try:
496
+ client = importlib.import_module("prometheus_client")
497
+ core = importlib.import_module("prometheus_client.core")
498
+ except ImportError as exc:
499
+ raise ImportError(
500
+ "register_with_prometheus_client needs the prometheus_client package"
501
+ ) from exc
502
+ exporter = self
503
+
504
+ class _Collector:
505
+ def collect(self) -> Iterable[Any]:
506
+ for fam in exporter._collect():
507
+ yield _to_client_family(core, fam)
508
+
509
+ collector = _Collector()
510
+ target = registry if registry is not None else client.REGISTRY
511
+ target.register(collector)
512
+ return collector
513
+
514
+
515
+ def _to_client_family(core: Any, fam: _Family) -> Any:
516
+ label_names = [k for k, _ in fam.series[0][0]] if fam.series else []
517
+ if fam.kind == "counter":
518
+ metric = core.CounterMetricFamily(
519
+ fam.name.removesuffix("_total"), fam.help, labels=label_names
520
+ )
521
+ for labels, value in fam.series:
522
+ metric.add_metric([v for _, v in labels], value)
523
+ elif fam.kind == "gauge":
524
+ metric = core.GaugeMetricFamily(fam.name, fam.help, labels=label_names)
525
+ for labels, value in fam.series:
526
+ metric.add_metric([v for _, v in labels], value)
527
+ else:
528
+ metric = core.HistogramMetricFamily(fam.name, fam.help, labels=label_names)
529
+ for labels, value in fam.series:
530
+ assert isinstance(value, _Hist)
531
+ buckets = [(_num(b), c) for b, c in zip(value.bounds, value.cumulative, strict=False)]
532
+ buckets.append(("+Inf", value.cumulative[-1]))
533
+ metric.add_metric([v for _, v in labels], buckets, value.total)
534
+ return metric
535
+
536
+
537
+ _TAG_UNSAFE = re.compile(r"[,|#:\n@]")
538
+
539
+
540
+ def _tag(value: str) -> str:
541
+ return _TAG_UNSAFE.sub("_", value)
542
+
543
+
544
+ class StatsDExporter:
545
+ """Send events to a StatsD or DogStatsD agent over UDP, fire-and-forget.
546
+
547
+ Each event becomes a counter ``<prefix>.<event>:1|c``. Durations are also sent as
548
+ timings in milliseconds (``<prefix>.retry.wait``, ``<prefix>.periodic.run``,
549
+ ``<prefix>.rate_limit.wait``, ``<prefix>.timing.slow``) and circuit breaker states as a
550
+ gauge ``<prefix>.circuit.state`` (0 closed, 1 half_open, 2 open). Sending never blocks
551
+ and never raises; failures increase `errors`.
552
+
553
+ Args:
554
+ host: Agent host.
555
+ port: Agent UDP port.
556
+ prefix: Metric name prefix.
557
+ tags: ``"dogstatsd"`` appends ``|#function:<name>`` tags; ``"none"`` omits them.
558
+ sample_rate: Fraction of datagrams to send, in (0, 1]. Sampled datagrams carry
559
+ ``|@rate`` so the agent can scale them; gauges are never sampled.
560
+
561
+ Raises:
562
+ ValueError: If ``tags`` or ``sample_rate`` is invalid.
563
+
564
+ Example:
565
+ >>> exporter = StatsDExporter(port=9, tags="none")
566
+ >>> exporter.close()
567
+ """
568
+
569
+ def __init__(
570
+ self,
571
+ host: str = "127.0.0.1",
572
+ port: int = 8125,
573
+ *,
574
+ prefix: str = "python_wrap",
575
+ tags: Literal["dogstatsd", "none"] = "dogstatsd",
576
+ sample_rate: float = 1.0,
577
+ ) -> None:
578
+ if tags not in ("dogstatsd", "none"):
579
+ raise ValueError("tags must be 'dogstatsd' or 'none'")
580
+ if not 0 < sample_rate <= 1:
581
+ raise ValueError("sample_rate must be in (0, 1]")
582
+ self.host = host
583
+ self.port = port
584
+ self.prefix = prefix
585
+ self.tags = tags
586
+ self.sample_rate = sample_rate
587
+ self.sent = 0
588
+ self.errors = 0
589
+ self._lock = _fork.ForkSafeLock()
590
+ self._sock: socket.socket | None = None
591
+ self._unsubscribe: Callable[[], None] | None = None
592
+
593
+ def install(self) -> StatsDExporter:
594
+ """Subscribe to the event stream. Returns this exporter."""
595
+ with self._lock:
596
+ if self._unsubscribe is None:
597
+ self._unsubscribe = subscribe(self._on_event)
598
+ return self
599
+
600
+ def close(self) -> None:
601
+ """Unsubscribe and close the socket."""
602
+ with self._lock:
603
+ unsubscribe, self._unsubscribe = self._unsubscribe, None
604
+ sock, self._sock = self._sock, None
605
+ if unsubscribe is not None:
606
+ unsubscribe()
607
+ if sock is not None:
608
+ sock.close()
609
+
610
+ def __enter__(self) -> StatsDExporter:
611
+ return self.install()
612
+
613
+ def __exit__(self, *exc: object) -> None:
614
+ self.close()
615
+
616
+ def _send(self, payload: str) -> None:
617
+ try:
618
+ with self._lock:
619
+ if self._sock is None:
620
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
621
+ sock.setblocking(False)
622
+ self._sock = sock
623
+ sock = self._sock
624
+ sock.sendto(payload.encode("utf-8"), (self.host, self.port))
625
+ self.sent += 1
626
+ except Exception:
627
+ self.errors += 1
628
+
629
+ def _line(
630
+ self, name: str, value: str, kind: str, tag: tuple[str, str] | None, sampled: bool
631
+ ) -> str:
632
+ line = f"{self.prefix}.{name}:{value}|{kind}"
633
+ if sampled and self.sample_rate < 1:
634
+ line += f"|@{self.sample_rate:g}"
635
+ if tag is not None and self.tags == "dogstatsd":
636
+ line += f"|#{tag[0]}:{_tag(tag[1])}"
637
+ return line
638
+
639
+ def _on_event(self, event: Event) -> None:
640
+ name, fn, fields = event.name, event.function, event.fields
641
+ function_tag = ("function", fn)
642
+ keep = self.sample_rate >= 1 or random.random() < self.sample_rate
643
+ if keep:
644
+ self._send(self._line(name, "1", "c", function_tag, True))
645
+ timing: tuple[str, Any] | None = None
646
+ if name == "retry.attempt_failed":
647
+ timing = ("retry.wait", fields.get("next_delay"))
648
+ elif name == "periodic.run":
649
+ timing = ("periodic.run", fields.get("seconds"))
650
+ elif name == "rate_limit.waited":
651
+ timing = ("rate_limit.wait", fields.get("seconds"))
652
+ elif name == "timing.slow":
653
+ timing = ("timing.slow", fields.get("seconds"))
654
+ if timing is not None and keep:
655
+ seconds = _number(timing[1])
656
+ if seconds is not None and seconds >= 0:
657
+ self._send(
658
+ self._line(timing[0], _num(round(seconds * 1000, 3)), "ms", function_tag, True)
659
+ )
660
+ if name == "circuit.state_changed":
661
+ state = _STATE_VALUES.get(_state_name(fields.get("new")))
662
+ if state is not None:
663
+ self._send(self._line("circuit.state", str(state), "g", ("breaker", fn), False))