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,638 @@
1
+ """Local and distributed owner-checked leases and single-instance decorators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import hashlib
8
+ import logging
9
+ import math
10
+ import os
11
+ import threading
12
+ import uuid
13
+ from collections.abc import Callable
14
+ from typing import Any, TypeVar, cast
15
+
16
+ from python_wrap import _core, _fork
17
+ from python_wrap._runtime import call_key, seconds
18
+
19
+ __all__ = [
20
+ "AlreadyRunning",
21
+ "AsyncRedisLock",
22
+ "AsyncRedisSemaphore",
23
+ "Lease",
24
+ "LeaseLost",
25
+ "LocalLease",
26
+ "PgAdvisoryLock",
27
+ "RedisLock",
28
+ "RedisSemaphore",
29
+ "SqlAppLock",
30
+ "single_instance",
31
+ ]
32
+ F = TypeVar("F", bound=Callable[..., Any])
33
+
34
+
35
+ class AlreadyRunning(RuntimeError):
36
+ """The requested lease could not be acquired."""
37
+
38
+
39
+ class LeaseLost(RuntimeError):
40
+ """A lease expired or could not be renewed while work was running."""
41
+
42
+
43
+ class LocalLease:
44
+ """In-process leases; concurrent acquisition and renewal are owner-checked."""
45
+
46
+ def __init__(self) -> None:
47
+ self._lock = _fork.ForkSafeLock()
48
+ self._entries: dict[str, dict[str, float]] = {}
49
+ _fork.register(self)
50
+
51
+ def _reset_after_fork(self) -> None:
52
+ self._entries.clear()
53
+
54
+ def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool:
55
+ _validate_request(key, token, ttl, limit)
56
+ with self._lock:
57
+ now = _core.monotonic()
58
+ entries = self._entries.setdefault(key, {})
59
+ for old in list(entries):
60
+ if entries[old] <= now:
61
+ del entries[old]
62
+ if token not in entries and len(entries) >= limit:
63
+ return False
64
+ entries[token] = now + ttl
65
+ return True
66
+
67
+ def renew(self, key: str, token: str, ttl: float) -> bool:
68
+ _validate_request(key, token, ttl, 1)
69
+ with self._lock:
70
+ entries = self._entries.get(key, {})
71
+ if entries.get(token, 0) <= _core.monotonic():
72
+ return False
73
+ entries[token] = _core.monotonic() + ttl
74
+ return True
75
+
76
+ def release(self, key: str, token: str) -> bool:
77
+ with self._lock:
78
+ entries = self._entries.get(key, {})
79
+ expires = entries.pop(token, None)
80
+ if not entries:
81
+ self._entries.pop(key, None)
82
+ return expires is not None and expires > _core.monotonic()
83
+
84
+
85
+ def _validate_request(key: str, token: str, ttl: float, limit: int) -> None:
86
+ if not isinstance(key, str) or not key or not isinstance(token, str) or not token:
87
+ raise ValueError("lease key and token must be nonempty strings")
88
+ seconds(ttl)
89
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
90
+ raise ValueError("lease capacity must be a positive integer")
91
+
92
+
93
+ _LEASE = """
94
+ local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000)
95
+ redis.call('ZREMRANGEBYSCORE',KEYS[1],'-inf',now)
96
+ local op=ARGV[1]; local token=ARGV[2]; local ttl=tonumber(ARGV[3]); local limit=tonumber(ARGV[4])
97
+ if op=='release' then return redis.call('ZREM',KEYS[1],token) end
98
+ if op=='renew' then
99
+ if not redis.call('ZSCORE',KEYS[1],token) then return 0 end
100
+ elseif not redis.call('ZSCORE',KEYS[1],token) and redis.call('ZCARD',KEYS[1])>=limit then
101
+ return 0 end
102
+ redis.call('ZADD',KEYS[1],now+ttl,token)
103
+ local last=redis.call('ZRANGE',KEYS[1],-1,-1,'WITHSCORES')
104
+ redis.call('PEXPIRE',KEYS[1],math.max(1,tonumber(last[2])-now))
105
+ return 1
106
+ """
107
+
108
+
109
+ class RedisLock:
110
+ """Redis-server-clock leases, acquired/renewed/released atomically with Lua.
111
+
112
+ Each acquisition has a unique token. Expired owners cannot release a successor's
113
+ lease. A finite lease cannot guarantee exactly-once side effects after expiry.
114
+ """
115
+
116
+ def __init__(self, client: Any, prefix: str = "python-wrap:lease:") -> None:
117
+ if not prefix:
118
+ raise ValueError("prefix must not be empty")
119
+ self.client, self.prefix = client, prefix
120
+
121
+ def _call(self, op: str, key: str, token: str, ttl: float, limit: int = 1) -> bool:
122
+ _validate_request(key, token, ttl, limit)
123
+ return bool(
124
+ self.client.eval(
125
+ _LEASE, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit
126
+ )
127
+ )
128
+
129
+ def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool:
130
+ return self._call("acquire", key, token, ttl, limit)
131
+
132
+ def renew(self, key: str, token: str, ttl: float) -> bool:
133
+ return self._call("renew", key, token, ttl)
134
+
135
+ def release(self, key: str, token: str) -> bool:
136
+ return self._call("release", key, token, 1)
137
+
138
+
139
+ class RedisSemaphore(RedisLock):
140
+ """The same atomic lease backend, with capacity supplied by Lease(limit=...)."""
141
+
142
+
143
+ class AsyncRedisLock(RedisLock):
144
+ """`RedisLock` for ``redis.asyncio`` clients: every round trip is awaited, not threaded.
145
+
146
+ Same Lua script and keys as `RedisLock`, so sync and async processes contend for one
147
+ lease. Use it from ``async with Lease(...)``; a synchronous ``with`` raises TypeError.
148
+ """
149
+
150
+ async def _call( # type: ignore[override]
151
+ self, op: str, key: str, token: str, ttl: float, limit: int = 1
152
+ ) -> bool:
153
+ _validate_request(key, token, ttl, limit)
154
+ return bool(
155
+ await self.client.eval(
156
+ _LEASE, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit
157
+ )
158
+ )
159
+
160
+ async def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool: # type: ignore[override]
161
+ return await self._call("acquire", key, token, ttl, limit)
162
+
163
+ async def renew(self, key: str, token: str, ttl: float) -> bool: # type: ignore[override]
164
+ return await self._call("renew", key, token, ttl)
165
+
166
+ async def release(self, key: str, token: str) -> bool: # type: ignore[override]
167
+ return await self._call("release", key, token, 1)
168
+
169
+
170
+ class AsyncRedisSemaphore(AsyncRedisLock):
171
+ """`AsyncRedisLock` with capacity supplied by Lease(limit=...)."""
172
+
173
+
174
+ class _SQLLock:
175
+ dialect: str
176
+
177
+ def __init__(self, engine: Any) -> None:
178
+ self.engine = engine
179
+ self._connections: dict[str, tuple[str, Any, Any]] = {}
180
+ self._lock = _fork.ForkSafeLock()
181
+ self._pid = os.getpid()
182
+
183
+ def _process(self) -> None:
184
+ if os.getpid() != self._pid:
185
+ raise RuntimeError("create SQL lock engines and backends after fork")
186
+
187
+ def _resource(self, key: str) -> Any:
188
+ if self.dialect == "postgresql":
189
+ return int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "big", signed=True)
190
+ # SQL Server truncates applock resource names to 255 characters. Hashing
191
+ # avoids unrelated long application keys silently sharing one lock.
192
+ return hashlib.sha256(key.encode()).hexdigest()
193
+
194
+ def _placeholder(self) -> str:
195
+ dialect = getattr(self.engine, "dialect", None)
196
+ style = getattr(dialect, "paramstyle", "qmark")
197
+ return "%s" if style in {"format", "pyformat"} else "?"
198
+
199
+ @staticmethod
200
+ def _discard(conn: Any) -> None:
201
+ # Closing a SQLAlchemy Connection normally returns its session to the pool.
202
+ # On uncertain unlock/acquire outcomes that session must instead be destroyed.
203
+ try:
204
+ invalidate = getattr(conn, "invalidate", None)
205
+ if invalidate is not None:
206
+ invalidate()
207
+ finally:
208
+ conn.close()
209
+
210
+ def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool:
211
+ self._process()
212
+ _validate_request(key, token, ttl, limit)
213
+ if limit != 1:
214
+ raise ValueError("SQL session locks support capacity one only")
215
+ # A backend owns each connection until its matching key/token releases it.
216
+ # Sessions must never be shared with unrelated application transactions.
217
+ with self._lock:
218
+ if token in self._connections:
219
+ raise RuntimeError("a SQL lease token is already active")
220
+ conn = self.engine.connect()
221
+ try:
222
+ if self.dialect == "postgresql":
223
+ ok = bool(
224
+ conn.exec_driver_sql(
225
+ "SELECT pg_try_advisory_lock(%s)", (self._resource(key),)
226
+ ).scalar()
227
+ )
228
+ else:
229
+ sql = (
230
+ f"DECLARE @r int; EXEC @r = sp_getapplock @Resource={self._placeholder()}, "
231
+ "@LockMode='Exclusive', @LockOwner='Session', @LockTimeout=0; SELECT @r"
232
+ )
233
+ ok = int(conn.exec_driver_sql(sql, (self._resource(key),)).scalar()) >= 0
234
+ if ok:
235
+ with self._lock:
236
+ if token in self._connections:
237
+ raise RuntimeError("a SQL lease token was acquired concurrently")
238
+ self._connections[token] = (key, conn, threading.Lock())
239
+ return True
240
+ except BaseException:
241
+ try:
242
+ self._discard(conn)
243
+ except Exception:
244
+ logging.getLogger("python_wrap").exception("SQL lease acquire cleanup failed")
245
+ raise
246
+ conn.close()
247
+ return False
248
+
249
+ def renew(self, key: str, token: str, ttl: float) -> bool:
250
+ self._process()
251
+ _validate_request(key, token, ttl, 1)
252
+ with self._lock:
253
+ slot = self._connections.get(token)
254
+ if slot is None or slot[0] != key:
255
+ return False
256
+ _, conn, operation_lock = slot
257
+ with operation_lock:
258
+ with self._lock:
259
+ if self._connections.get(token) is not slot:
260
+ return False
261
+ if getattr(conn, "invalidated", False) or getattr(conn, "closed", False):
262
+ return False
263
+ try:
264
+ conn.exec_driver_sql("SELECT 1")
265
+ return True
266
+ except Exception:
267
+ return False
268
+
269
+ def release(self, key: str, token: str) -> bool:
270
+ self._process()
271
+ with self._lock:
272
+ slot = self._connections.get(token)
273
+ if slot is None or slot[0] != key:
274
+ return False
275
+ del self._connections[token]
276
+ _, conn, operation_lock = slot
277
+ with operation_lock:
278
+ try:
279
+ if getattr(conn, "invalidated", False) or getattr(conn, "closed", False):
280
+ self._discard(conn)
281
+ return False
282
+ if self.dialect == "postgresql":
283
+ released = bool(
284
+ conn.exec_driver_sql(
285
+ "SELECT pg_advisory_unlock(%s)", (self._resource(key),)
286
+ ).scalar()
287
+ )
288
+ else:
289
+ sql = (
290
+ "DECLARE @r int; EXEC @r = sp_releaseapplock "
291
+ f"@Resource={self._placeholder()}, @LockOwner='Session'; SELECT @r"
292
+ )
293
+ released = int(conn.exec_driver_sql(sql, (self._resource(key),)).scalar()) >= 0
294
+ except BaseException:
295
+ try:
296
+ self._discard(conn)
297
+ except Exception:
298
+ logging.getLogger("python_wrap").exception("SQL lease release cleanup failed")
299
+ raise
300
+ if released:
301
+ conn.close()
302
+ else:
303
+ self._discard(conn)
304
+ return released
305
+
306
+
307
+ class PgAdvisoryLock(_SQLLock):
308
+ """SQLAlchemy PostgreSQL session advisory locks; TTL is session lifetime.
309
+
310
+ Use a dedicated, non-multiplexed connection pool and create engines after fork.
311
+ """
312
+
313
+ dialect = "postgresql"
314
+
315
+
316
+ class SqlAppLock(_SQLLock):
317
+ """SQLAlchemy SQL Server session locks (pyodbc/pymssql); TTL is session lifetime.
318
+
319
+ Resource names are SHA-256 hashes to avoid the server's 255-character truncation.
320
+ """
321
+
322
+ dialect = "mssql"
323
+
324
+
325
+ _LOCAL = LocalLease()
326
+
327
+
328
+ async def _inline(fn: Callable[..., Any], *args: Any) -> Any:
329
+ return fn(*args)
330
+
331
+
332
+ async def _drain(task: asyncio.Task[Any]) -> tuple[Any, BaseException | None, bool]:
333
+ """Settle cleanup even under repeated outside cancellation; remember cancellation."""
334
+ cancelled = False
335
+ while not task.done():
336
+ try:
337
+ await asyncio.shield(task)
338
+ except asyncio.CancelledError:
339
+ cancelled = True
340
+ except BaseException:
341
+ break
342
+ try:
343
+ return task.result(), None, cancelled
344
+ except BaseException as error:
345
+ return None, error, cancelled
346
+
347
+
348
+ class Lease:
349
+ """Single-use sync/async lease context with renewal and bounded acquisition wait.
350
+
351
+ Backend operations need client-level I/O timeouts. Cancellation waits for an
352
+ outstanding acquisition/renewal to settle before owner-checked release. The
353
+ caller's exception/cancellation wins over cleanup errors. A lease cannot cross
354
+ a fork and is not a substitute for fencing tokens for strict write exclusion.
355
+ """
356
+
357
+ def __init__(
358
+ self,
359
+ key: str,
360
+ *,
361
+ backend: Any = None,
362
+ ttl: float | str = 60,
363
+ limit: int = 1,
364
+ wait: bool = False,
365
+ timeout: float | None = None,
366
+ renew: bool = True,
367
+ ) -> None:
368
+ self.key = key
369
+ self.backend: Any = backend if backend is not None else _LOCAL
370
+ self.ttl = seconds(ttl)
371
+ self.token = uuid.uuid4().hex
372
+ _validate_request(key, self.token, self.ttl, limit)
373
+ if timeout is not None:
374
+ timeout = seconds(timeout, positive=False)
375
+ self.limit, self.wait, self.timeout, self.auto_renew = limit, wait, timeout, renew
376
+ self.lost = False
377
+ self._async = _core.is_async(self.backend.acquire)
378
+ self._inline = type(self.backend) is LocalLease # built-in, in memory: nothing blocks
379
+ self._stop = threading.Event()
380
+ self._thread: threading.Thread | None = None
381
+ self._task: asyncio.Task[None] | None = None
382
+ self._lifecycle = threading.Lock()
383
+ self._entering = self._active = self._finished = False
384
+ self._pid = os.getpid()
385
+
386
+ def _prepare(self) -> None:
387
+ if os.getpid() != self._pid:
388
+ raise RuntimeError("lease contexts cannot cross a fork")
389
+ with self._lifecycle:
390
+ if self._entering or self._active or self._finished:
391
+ raise RuntimeError(
392
+ "Lease contexts are single-use and cannot be entered concurrently"
393
+ )
394
+ self._entering = True
395
+
396
+ def _try(self) -> bool:
397
+ try:
398
+ return bool(self.backend.acquire(self.key, self.token, self.ttl, self.limit))
399
+ except BaseException:
400
+ # An acquire may succeed server-side before its response is lost.
401
+ try:
402
+ self.backend.release(self.key, self.token)
403
+ except Exception:
404
+ logging.getLogger("python_wrap").exception("lease acquire cleanup failed")
405
+ raise
406
+
407
+ def _renew(self) -> None:
408
+ try:
409
+ self.lost = self.lost or not self.backend.renew(self.key, self.token, self.ttl)
410
+ except Exception:
411
+ self.lost = True
412
+
413
+ async def _try_async(self) -> bool:
414
+ try:
415
+ return bool(await self.backend.acquire(self.key, self.token, self.ttl, self.limit))
416
+ except BaseException:
417
+ try:
418
+ await self.backend.release(self.key, self.token)
419
+ except Exception:
420
+ logging.getLogger("python_wrap").exception("lease acquire cleanup failed")
421
+ raise
422
+
423
+ async def _renew_async(self) -> None:
424
+ try:
425
+ self.lost = self.lost or not await self.backend.renew(self.key, self.token, self.ttl)
426
+ except Exception:
427
+ self.lost = True
428
+
429
+ def _io(self, sync: Callable[..., Any], native: Callable[..., Any], *args: Any) -> Any:
430
+ """Awaitable backend step: native for async backends, inline for local, else threaded."""
431
+ if self._async:
432
+ return native(*args)
433
+ return _inline(sync, *args) if self._inline else asyncio.to_thread(sync, *args)
434
+
435
+ def _sync_only(self) -> None:
436
+ if self._async:
437
+ raise TypeError("this lease backend is async; use 'async with', not 'with'")
438
+
439
+ def check(self) -> None:
440
+ """Check and extend this active lease, raising LeaseLost if ownership is gone."""
441
+ self._sync_only()
442
+ if os.getpid() != self._pid or not self._active:
443
+ raise RuntimeError("lease is not active in this process")
444
+ self._renew()
445
+ if self.lost:
446
+ raise LeaseLost(self.key)
447
+
448
+ async def check_async(self) -> None:
449
+ """Async counterpart of check(); synchronous backend I/O runs in a thread."""
450
+ if self._async:
451
+ if os.getpid() != self._pid or not self._active:
452
+ raise RuntimeError("lease is not active in this process")
453
+ await self._renew_async()
454
+ if self.lost:
455
+ raise LeaseLost(self.key)
456
+ return
457
+ task = asyncio.ensure_future(self._io(self.check, self.check))
458
+ _, error, cancelled = await _drain(task)
459
+ if cancelled:
460
+ raise asyncio.CancelledError
461
+ if error is not None:
462
+ raise error
463
+
464
+ def __enter__(self) -> Lease:
465
+ import time
466
+
467
+ self._sync_only()
468
+ self._prepare()
469
+ try:
470
+ start = time.monotonic()
471
+ while not self._try():
472
+ left = None if self.timeout is None else self.timeout - (time.monotonic() - start)
473
+ if not self.wait or (left is not None and left <= 0):
474
+ raise AlreadyRunning(self.key)
475
+ time.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl))
476
+ self._active = True
477
+ if self.auto_renew:
478
+
479
+ def beat() -> None:
480
+ while not self._stop.wait(self.ttl / 3):
481
+ self._renew()
482
+ if self.lost:
483
+ return
484
+
485
+ self._thread = threading.Thread(target=beat, daemon=True, name="python-wrap-lease")
486
+ try:
487
+ self._thread.start()
488
+ except BaseException:
489
+ try:
490
+ self.backend.release(self.key, self.token)
491
+ except Exception:
492
+ logging.getLogger("python_wrap").exception("lease start cleanup failed")
493
+ self._active, self._finished = False, True
494
+ raise
495
+ return self
496
+ finally:
497
+ self._entering = False
498
+
499
+ def __exit__(self, typ: Any, exc: Any, tb: Any) -> None:
500
+ if os.getpid() != self._pid:
501
+ if exc is None:
502
+ raise RuntimeError("lease contexts cannot cross a fork")
503
+ return
504
+ if not self._active:
505
+ raise RuntimeError("lease exited without an acquisition")
506
+ self._stop.set()
507
+ if self._thread is not None:
508
+ self._thread.join()
509
+ try:
510
+ released = self.backend.release(self.key, self.token)
511
+ except Exception:
512
+ if exc is None:
513
+ raise
514
+ logging.getLogger("python_wrap").exception("lease release failed during error cleanup")
515
+ return
516
+ finally:
517
+ self._active, self._finished = False, True
518
+ if exc is None and (self.lost or not released):
519
+ raise LeaseLost(self.key)
520
+
521
+ async def _atry(self) -> bool:
522
+ task = asyncio.ensure_future(self._io(self._try, self._try_async))
523
+ try:
524
+ return await asyncio.shield(task)
525
+ except asyncio.CancelledError:
526
+ acquired, error, _ = await _drain(task)
527
+ if error is None and acquired:
528
+ release = self.backend.release
529
+ cleanup = asyncio.ensure_future(self._io(release, release, self.key, self.token))
530
+ _, cleanup_error, _ = await _drain(cleanup)
531
+ if cleanup_error is not None:
532
+ logging.getLogger("python_wrap").warning("cancelled lease cleanup failed")
533
+ raise
534
+
535
+ async def __aenter__(self) -> Lease:
536
+ self._prepare()
537
+ try:
538
+ loop = asyncio.get_running_loop()
539
+ start = loop.time()
540
+ while not await self._atry():
541
+ left = None if self.timeout is None else self.timeout - (loop.time() - start)
542
+ if not self.wait or (left is not None and left <= 0):
543
+ raise AlreadyRunning(self.key)
544
+ await asyncio.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl))
545
+ self._active = True
546
+ if self.auto_renew:
547
+
548
+ async def beat() -> None:
549
+ while True:
550
+ await asyncio.sleep(self.ttl / 3)
551
+ renewal = asyncio.ensure_future(self._io(self._renew, self._renew_async))
552
+ try:
553
+ await asyncio.shield(renewal)
554
+ except asyncio.CancelledError:
555
+ await _drain(renewal)
556
+ raise
557
+ if self.lost:
558
+ return
559
+
560
+ self._task = asyncio.create_task(beat())
561
+ return self
562
+ finally:
563
+ self._entering = False
564
+
565
+ async def __aexit__(self, typ: Any, exc: Any, tb: Any) -> None:
566
+ if os.getpid() != self._pid:
567
+ if exc is None:
568
+ raise RuntimeError("lease contexts cannot cross a fork")
569
+ return
570
+ if not self._active:
571
+ raise RuntimeError("lease exited without an acquisition")
572
+
573
+ async def finish() -> bool:
574
+ if self._task is not None:
575
+ self._task.cancel()
576
+ with contextlib.suppress(asyncio.CancelledError):
577
+ await self._task
578
+ release = self.backend.release
579
+ return bool(await self._io(release, release, self.key, self.token))
580
+
581
+ cleanup = asyncio.create_task(finish())
582
+ try:
583
+ released, error, cancelled = await _drain(cleanup)
584
+ finally:
585
+ self._active, self._finished = False, True
586
+ if cancelled:
587
+ raise asyncio.CancelledError
588
+ if error is not None:
589
+ if exc is None:
590
+ raise error
591
+ logging.getLogger("python_wrap").warning("lease release failed during error cleanup")
592
+ return
593
+ if exc is None and (self.lost or not released):
594
+ raise LeaseLost(self.key)
595
+
596
+
597
+ def single_instance(
598
+ *,
599
+ key: str | Callable[..., Any] | None = None,
600
+ backend: Any = None,
601
+ ttl: float | str = 60,
602
+ wait: bool = False,
603
+ timeout: float | None = None,
604
+ renew: bool = True,
605
+ ) -> Callable[[F], F]:
606
+ """Run one call per key under an owner-checked local or distributed lease."""
607
+ ttl = seconds(ttl)
608
+
609
+ def decorate(func: F) -> F:
610
+ import functools
611
+
612
+ def scope(args: tuple[Any, ...], kw: dict[str, Any]) -> Lease:
613
+ return Lease(
614
+ call_key(func, key, args, kw),
615
+ backend=backend,
616
+ ttl=ttl,
617
+ wait=wait,
618
+ timeout=timeout,
619
+ renew=renew,
620
+ )
621
+
622
+ if _core.is_async(func):
623
+
624
+ @functools.wraps(func)
625
+ async def aw(*args: Any, **kw: Any) -> Any:
626
+ async with scope(args, kw):
627
+ return await func(*args, **kw)
628
+
629
+ return cast(F, aw)
630
+
631
+ @functools.wraps(func)
632
+ def sw(*args: Any, **kw: Any) -> Any:
633
+ with scope(args, kw):
634
+ return func(*args, **kw)
635
+
636
+ return cast(F, sw)
637
+
638
+ return decorate