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/health.py ADDED
@@ -0,0 +1,187 @@
1
+ """An explicit, weakly held registry of dependency state and optional health checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ import weakref
8
+ from collections.abc import Callable, Iterable
9
+ from typing import Any
10
+
11
+ from python_wrap import _fork
12
+
13
+ __all__ = ["HealthRegistry", "health"]
14
+
15
+
16
+ class HealthRegistry:
17
+ """Register named components; report structural state without calling user functions.
18
+
19
+ Backend checks are opt-in through register_check. Reports omit exception messages,
20
+ endpoints and credentials. Applications choose whether to expose a health route.
21
+ """
22
+
23
+ def __init__(self) -> None:
24
+ self._lock = _fork.ForkSafeLock()
25
+ self._objects: dict[str, weakref.ref[Any]] = {}
26
+ self._checks: dict[str, Callable[[], Any]] = {}
27
+
28
+ def register(self, name: str, component: Any) -> None:
29
+ if not name:
30
+ raise ValueError("health name must not be empty")
31
+ ref = weakref.ref(component)
32
+ with self._lock:
33
+ self._objects[name] = ref
34
+ self._checks.pop(name, None)
35
+
36
+ def register_check(self, name: str, check: Callable[[], Any]) -> None:
37
+ """Register a synchronous checker returning bool or a dict with a healthy bool."""
38
+ if not name or inspect.iscoroutinefunction(check):
39
+ raise ValueError("health checks need a name and a synchronous checker")
40
+ with self._lock:
41
+ self._checks[name] = check
42
+ self._objects.pop(name, None)
43
+
44
+ def unregister(self, name: str) -> None:
45
+ with self._lock:
46
+ self._objects.pop(name, None)
47
+ self._checks.pop(name, None)
48
+
49
+ def report(self) -> dict[str, Any]:
50
+ with self._lock:
51
+ objects = list(self._objects.items())
52
+ checks = list(self._checks.items())
53
+ result: dict[str, Any] = {}
54
+ for name, ref in objects:
55
+ obj = ref()
56
+ if obj is None:
57
+ continue
58
+ try:
59
+ state = getattr(obj, "state", None)
60
+ if hasattr(obj, "degraded"):
61
+ result[name] = {"healthy": True, "degraded": bool(obj.degraded)}
62
+ elif state is not None:
63
+ value = getattr(state, "value", state)
64
+ result[name] = {"healthy": value == "closed", "state": value}
65
+ elif hasattr(obj, "active") and hasattr(obj, "waiting"):
66
+ result[name] = {"healthy": True, "active": obj.active, "waiting": obj.waiting}
67
+ elif hasattr(obj, "cache_info"):
68
+ info = obj.cache_info()
69
+ result[name] = {
70
+ "healthy": True,
71
+ "hits": info.hits,
72
+ "misses": info.misses,
73
+ "size": info.currsize,
74
+ }
75
+ else:
76
+ result[name] = {"healthy": True, "status": "registered", "checked": False}
77
+ except Exception as exc:
78
+ result[name] = {"healthy": False, "error": type(exc).__name__}
79
+ for name, check in checks:
80
+ try:
81
+ value = check()
82
+ if inspect.iscoroutine(value):
83
+ value.close()
84
+ raise TypeError("health check returned a coroutine")
85
+ if isinstance(value, dict) and isinstance(value.get("healthy"), bool):
86
+ result[name] = value
87
+ elif isinstance(value, bool):
88
+ result[name] = {"healthy": value}
89
+ else:
90
+ raise TypeError("health checks must return bool or a dict with healthy: bool")
91
+ except Exception as exc:
92
+ result[name] = {"healthy": False, "error": type(exc).__name__}
93
+ return result
94
+
95
+ def summary(self, *, critical: Iterable[str] | None = None) -> dict[str, Any]:
96
+ """An overall status for load balancers and dashboards.
97
+
98
+ ``status`` is ``"ok"`` when every component is healthy (``"degraded"`` too while a shared
99
+ backend runs on its local fallback), ``"down"`` when a
100
+ *critical* component is unhealthy, otherwise ``"degraded"``. With
101
+ ``critical=None`` every component is critical. ``http_status`` is 200 for
102
+ ``ok``/``degraded`` and 503 for ``down`` (so an optional dependency with an
103
+ open breaker does not take the instance out of rotation).
104
+
105
+ Args:
106
+ critical: Component names whose failure means the service is down.
107
+
108
+ Returns:
109
+ ``{"status", "http_status", "healthy", "unhealthy", "components"}``.
110
+
111
+ Example:
112
+ >>> registry = HealthRegistry()
113
+ >>> registry.register_check("db", lambda: True)
114
+ >>> registry.register_check("cache", lambda: False)
115
+ >>> registry.summary(critical=["db"])["status"]
116
+ 'degraded'
117
+ """
118
+ components = self.report()
119
+ unhealthy = sorted(name for name, data in components.items() if not data["healthy"])
120
+ required = set(components) if critical is None else set(critical)
121
+ if not unhealthy:
122
+ status = "degraded" if any(d.get("degraded") for d in components.values()) else "ok"
123
+ elif required & set(unhealthy):
124
+ status = "down"
125
+ else:
126
+ status = "degraded"
127
+ return {
128
+ "status": status,
129
+ "http_status": 503 if status == "down" else 200,
130
+ "healthy": len(components) - len(unhealthy),
131
+ "unhealthy": unhealthy,
132
+ "components": components,
133
+ }
134
+
135
+ def _response(self, critical: Iterable[str] | None) -> tuple[int, bytes]:
136
+ summary = self.summary(critical=critical)
137
+ return summary["http_status"], json.dumps(summary, default=str).encode()
138
+
139
+ def wsgi_app(self, *, critical: Iterable[str] | None = None) -> Callable[..., Any]:
140
+ """A WSGI app answering every request with `summary` as JSON (200 or 503).
141
+
142
+ Mount it at ``/health`` (Flask: ``DispatcherMiddleware``; Django: call it from a
143
+ view). Do not expose it publicly if component names are sensitive.
144
+ """
145
+ names = None if critical is None else tuple(critical)
146
+
147
+ def app(environ: Any, start_response: Callable[..., Any]) -> list[bytes]:
148
+ status, body = self._response(names)
149
+ start_response(
150
+ f"{status} {'OK' if status == 200 else 'Service Unavailable'}",
151
+ [("Content-Type", "application/json"), ("Cache-Control", "no-store")],
152
+ )
153
+ return [body]
154
+
155
+ return app
156
+
157
+ def asgi_app(self, *, critical: Iterable[str] | None = None) -> Callable[..., Any]:
158
+ """An ASGI app answering HTTP requests with `summary` as JSON (200 or 503).
159
+
160
+ Mount it in FastAPI/Starlette with ``app.mount("/health", health.asgi_app())``.
161
+ Checks are synchronous and run in a worker thread, so slow checks never block
162
+ the event loop.
163
+ """
164
+ import asyncio
165
+
166
+ names = None if critical is None else tuple(critical)
167
+
168
+ async def app(scope: Any, receive: Any, send: Any) -> None:
169
+ if scope.get("type") != "http":
170
+ return
171
+ status, body = await asyncio.to_thread(self._response, names)
172
+ await send(
173
+ {
174
+ "type": "http.response.start",
175
+ "status": status,
176
+ "headers": [
177
+ (b"content-type", b"application/json"),
178
+ (b"cache-control", b"no-store"),
179
+ ],
180
+ }
181
+ )
182
+ await send({"type": "http.response.body", "body": body})
183
+
184
+ return app
185
+
186
+
187
+ health = HealthRegistry()