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/compat.py ADDED
@@ -0,0 +1,267 @@
1
+ """Drop-in helpers for code that uses a hand-rolled Redis lock helper.
2
+
3
+ Many codebases carry a small module shaped like this::
4
+
5
+ with named_lock(name, suffix): ...
6
+ if acquire_lock(name): ...
7
+ release_lock(name)
8
+
9
+ This module offers the same call shapes on top of python-wrap's owner-checked,
10
+ auto-renewing leases, so migrating is usually a one-line import change plus a single
11
+ `configure_locks` call at start-up.
12
+
13
+ Improvement over a plain ``SET NX`` / ``DEL`` helper: every acquisition has a unique
14
+ token, and release only removes the lock if that token still owns it. A helper that
15
+ issues a bare ``DEL`` can release a lock that expired and was taken over by another
16
+ worker; here that release is a no-op that returns ``False``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import os
23
+ import uuid
24
+ from collections.abc import Iterator
25
+ from typing import Any, Literal, overload
26
+
27
+ from python_wrap import _core, _fork
28
+ from python_wrap._runtime import seconds
29
+ from python_wrap.coordination import _LOCAL, AlreadyRunning, Lease
30
+
31
+ __all__ = [
32
+ "RunLocks",
33
+ "acquire_lock",
34
+ "configure_locks",
35
+ "named_lock",
36
+ "release_lock",
37
+ ]
38
+
39
+ _default_backend: Any = None
40
+
41
+
42
+ def configure_locks(backend: Any) -> None:
43
+ """Set the default lease backend used when none is passed explicitly.
44
+
45
+ Args:
46
+ backend: A lease backend such as `RedisLock`, or ``None`` to go back to the
47
+ in-process default.
48
+
49
+ Example:
50
+ ```python
51
+ from python_wrap import LocalLease
52
+ from python_wrap.compat import configure_locks, named_lock
53
+
54
+ configure_locks(LocalLease())
55
+ with named_lock("nightly-import", "tenant-7") as lease:
56
+ assert lease.key == "lock:nightly-import:tenant-7"
57
+ configure_locks(None)
58
+ ```
59
+ """
60
+ global _default_backend
61
+ _default_backend = backend
62
+
63
+
64
+ def _resolve(backend: Any) -> Any:
65
+ if backend is not None:
66
+ return backend
67
+ return _default_backend if _default_backend is not None else _LOCAL
68
+
69
+
70
+ def _key(prefix: str, name: str, suffix: object | None = None) -> str:
71
+ if not name:
72
+ raise ValueError("lock name must not be empty")
73
+ key = prefix + name
74
+ return key if suffix is None else f"{key}:{suffix}"
75
+
76
+
77
+ @contextlib.contextmanager
78
+ def _named_lock(
79
+ key: str, backend: Any, ttl: float, wait: bool, timeout: float | None, skip: bool
80
+ ) -> Iterator[Lease | Literal[False]]:
81
+ lease = Lease(key, backend=_resolve(backend), ttl=ttl, wait=wait, timeout=timeout)
82
+ try:
83
+ lease.__enter__()
84
+ except AlreadyRunning:
85
+ if not skip:
86
+ raise
87
+ yield False
88
+ return
89
+ try:
90
+ yield lease
91
+ except BaseException as exc:
92
+ lease.__exit__(type(exc), exc, exc.__traceback__)
93
+ raise
94
+ else:
95
+ lease.__exit__(None, None, None)
96
+
97
+
98
+ @overload
99
+ def named_lock(
100
+ name: str,
101
+ suffix: object | None = ...,
102
+ *,
103
+ backend: Any = ...,
104
+ ttl: float | str = ...,
105
+ wait: bool = ...,
106
+ timeout: float | None = ...,
107
+ prefix: str = ...,
108
+ skip: Literal[False] = ...,
109
+ ) -> contextlib.AbstractContextManager[Lease]: ...
110
+
111
+
112
+ @overload
113
+ def named_lock(
114
+ name: str,
115
+ suffix: object | None = ...,
116
+ *,
117
+ backend: Any = ...,
118
+ ttl: float | str = ...,
119
+ wait: bool = ...,
120
+ timeout: float | None = ...,
121
+ prefix: str = ...,
122
+ skip: bool,
123
+ ) -> contextlib.AbstractContextManager[Lease | Literal[False]]: ...
124
+
125
+
126
+ def named_lock(
127
+ name: str,
128
+ suffix: object | None = None,
129
+ *,
130
+ backend: Any = None,
131
+ ttl: float | str = 600,
132
+ wait: bool = False,
133
+ timeout: float | None = None,
134
+ prefix: str = "lock:",
135
+ skip: bool = False,
136
+ ) -> contextlib.AbstractContextManager[Lease | Literal[False]]:
137
+ """Hold an auto-renewing lease named ``prefix + name [+ ":" + suffix]``.
138
+
139
+ Args:
140
+ name: Lock name.
141
+ suffix: Optional discriminator appended after a colon (a tenant id, say).
142
+ backend: Lease backend; defaults to the one set by `configure_locks`, else an
143
+ in-process backend.
144
+ ttl: Lease lifetime in seconds; the lease is renewed while the block runs.
145
+ wait: Wait for the lock instead of failing at once.
146
+ timeout: Longest wait in seconds when ``wait=True``.
147
+ prefix: Key prefix.
148
+ skip: Yield ``False`` instead of raising when the lock is held elsewhere.
149
+
150
+ Returns:
151
+ A context manager yielding the active `Lease` (or ``False`` when ``skip`` and
152
+ the lock is held).
153
+
154
+ Raises:
155
+ AlreadyRunning: On entering the block, if the lock is held and ``skip`` is false.
156
+ LeaseLost: On leaving the block, if the lease was lost while it ran.
157
+
158
+ Example:
159
+ ```python
160
+ from python_wrap.compat import named_lock
161
+
162
+ def import_tenant(tenant: str) -> str:
163
+ with named_lock("import", tenant, skip=True) as acquired:
164
+ if not acquired:
165
+ return "skipped"
166
+ return "imported"
167
+
168
+ assert import_tenant("t1") == "imported"
169
+ ```
170
+ """
171
+ return _named_lock(_key(prefix, name, suffix), backend, seconds(ttl), wait, timeout, skip)
172
+
173
+
174
+ class RunLocks:
175
+ """``acquire(name) -> bool`` / ``release(name) -> bool`` locks with owner checks.
176
+
177
+ The process remembers the token of each lock it acquired, so `release` only
178
+ removes a lock this process still owns. Locks are not auto-renewed: like a
179
+ ``SET NX EX`` helper they expire after ``ttl`` seconds unless you call `renew`.
180
+ Tokens belong to the process that created them and are forgotten in a forked child.
181
+
182
+ Args:
183
+ backend: Lease backend; ``None`` follows `configure_locks` at call time.
184
+ ttl: Lock lifetime in seconds.
185
+ prefix: Key prefix.
186
+
187
+ Example:
188
+ ```python
189
+ from python_wrap import LocalLease
190
+ from python_wrap.compat import RunLocks
191
+
192
+ locks = RunLocks(LocalLease(), ttl=30)
193
+ assert locks.acquire("report")
194
+ assert not locks.acquire("report")
195
+ assert locks.held("report")
196
+ assert locks.release("report")
197
+ assert not locks.release("report")
198
+ ```
199
+ """
200
+
201
+ def __init__(self, backend: Any = None, ttl: float | str = 600, prefix: str = "lock:") -> None:
202
+ self.backend = backend
203
+ self.ttl = seconds(ttl)
204
+ self.prefix = prefix
205
+ self._lock = _fork.ForkSafeLock()
206
+ self._tokens: dict[str, tuple[str, float]] = {}
207
+ self._pid = os.getpid()
208
+ _fork.register(self)
209
+
210
+ def _reset_after_fork(self) -> None:
211
+ self._tokens.clear()
212
+
213
+ def acquire(self, name: str) -> bool:
214
+ """Try to take the lock. Returns ``False`` if anyone (including us) holds it."""
215
+ key, token = _key(self.prefix, name), uuid.uuid4().hex
216
+ if not _resolve(self.backend).acquire(key, token, self.ttl):
217
+ return False
218
+ with self._lock:
219
+ self._tokens[name] = (token, _core.monotonic() + self.ttl)
220
+ return True
221
+
222
+ def release(self, name: str) -> bool:
223
+ """Release a lock this process acquired.
224
+
225
+ Returns:
226
+ ``True`` if the lock was still ours and is now free. ``False`` if we never
227
+ held it, or it expired (and may belong to someone else now): it is left alone.
228
+ """
229
+ with self._lock:
230
+ entry = self._tokens.pop(name, None)
231
+ if entry is None:
232
+ return False
233
+ return bool(_resolve(self.backend).release(_key(self.prefix, name), entry[0]))
234
+
235
+ def renew(self, name: str) -> bool:
236
+ """Extend a lock we hold by another ``ttl``. ``False`` if it is no longer ours."""
237
+ with self._lock:
238
+ entry = self._tokens.get(name)
239
+ if entry is None:
240
+ return False
241
+ if not _resolve(self.backend).renew(_key(self.prefix, name), entry[0], self.ttl):
242
+ return False
243
+ with self._lock:
244
+ self._tokens[name] = (entry[0], _core.monotonic() + self.ttl)
245
+ return True
246
+
247
+ def held(self, name: str) -> bool:
248
+ """True if this process acquired the lock and its ttl has not yet elapsed.
249
+
250
+ This is a local estimate with no backend call and no side effects.
251
+ """
252
+ with self._lock:
253
+ entry = self._tokens.get(name)
254
+ return entry is not None and _core.monotonic() < entry[1]
255
+
256
+
257
+ _runlocks = RunLocks()
258
+
259
+
260
+ def acquire_lock(name: str) -> bool:
261
+ """Module-level `RunLocks.acquire` using the `configure_locks` backend."""
262
+ return _runlocks.acquire(name)
263
+
264
+
265
+ def release_lock(name: str) -> bool:
266
+ """Module-level `RunLocks.release` using the `configure_locks` backend."""
267
+ return _runlocks.release(name)