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,620 @@
1
+ """Graceful shutdown: stop, flush and drain everything in one ordered pass.
2
+
3
+ Register the things that must be wound down (periodic tasks, buffered writers, batchers,
4
+ debouncers, bulkheads, or any callable), then call `shutdown.drain()` from your
5
+ framework's shutdown hook, or let `install_signal_handlers()` / `install_atexit()` do it.
6
+
7
+ * `ShutdownManager` — the registry and the drain logic; `shutdown` is the shared instance.
8
+ * `ShutdownReport` / `ItemReport` — what happened to each item.
9
+ * `ShutdownError` — raised by `drain(strict=True)` when something failed.
10
+
11
+ Draining never raises by default: a failing item is recorded and the rest still run.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import atexit
18
+ import inspect
19
+ import signal
20
+ import sys
21
+ import threading
22
+ import time
23
+ from collections.abc import Awaitable, Callable, Iterable
24
+ from dataclasses import dataclass, field
25
+ from types import FrameType
26
+ from typing import Any, Literal, NoReturn
27
+
28
+ from python_wrap import _core, _fork
29
+ from python_wrap.adaptive import AdaptiveLimiter
30
+ from python_wrap.buffering import AsyncBuffered, Buffered
31
+ from python_wrap.bulkhead import Bulkhead
32
+ from python_wrap.errors import PythonWrapError
33
+ from python_wrap.periodic import AsyncPeriodic, Periodic
34
+
35
+ __all__ = ["ItemReport", "ShutdownError", "ShutdownManager", "ShutdownReport", "shutdown"]
36
+
37
+ Status = Literal["ok", "error", "timeout"]
38
+ _POLL = 0.01
39
+
40
+
41
+ class ShutdownError(PythonWrapError):
42
+ """`drain(strict=True)` finished with at least one failed or timed-out item.
43
+
44
+ Attributes:
45
+ report: The full `ShutdownReport`.
46
+ """
47
+
48
+ def __init__(self, message: str, *, report: ShutdownReport) -> None:
49
+ super().__init__(message)
50
+ self.report = report
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ItemReport:
55
+ """The outcome for one registered item.
56
+
57
+ Attributes:
58
+ name: The registered name.
59
+ status: `"ok"`, `"error"` (it raised) or `"timeout"` (the budget ran out).
60
+ error: The exception, for `"error"` (and a note for a skipped `"timeout"`).
61
+ seconds: How long it took.
62
+ """
63
+
64
+ name: str
65
+ status: Status
66
+ error: BaseException | None = None
67
+ seconds: float = 0.0
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ShutdownReport:
72
+ """What a drain did, in the order it ran.
73
+
74
+ Attributes:
75
+ items: One `ItemReport` per registered item.
76
+ seconds: Total time spent.
77
+ """
78
+
79
+ items: tuple[ItemReport, ...] = ()
80
+ seconds: float = 0.0
81
+
82
+ @property
83
+ def ok(self) -> bool:
84
+ """True if every item finished cleanly."""
85
+ return all(item.status == "ok" for item in self.items)
86
+
87
+ @property
88
+ def failed(self) -> list[ItemReport]:
89
+ """Items that raised."""
90
+ return [item for item in self.items if item.status == "error"]
91
+
92
+ @property
93
+ def timed_out(self) -> list[ItemReport]:
94
+ """Items that did not finish within the budget."""
95
+ return [item for item in self.items if item.status == "timeout"]
96
+
97
+ def __str__(self) -> str:
98
+ parts = ", ".join(f"{i.name}={i.status}" for i in self.items)
99
+ return f"ShutdownReport({parts or 'empty'}; {self.seconds:.2f}s)"
100
+
101
+
102
+ Kind = Literal["periodic", "buffered", "idle", "async_only", "callable"]
103
+
104
+
105
+ @dataclass
106
+ class _Item:
107
+ name: str
108
+ priority: int
109
+ seq: int
110
+ target: Any
111
+ kind: Kind
112
+ fn: Callable[[], Any] | None = field(default=None)
113
+
114
+
115
+ def _classify(target: Any) -> tuple[Kind, Callable[[], Any] | None]:
116
+ if isinstance(target, Periodic):
117
+ return "periodic", None
118
+ if isinstance(target, AsyncPeriodic):
119
+ return "async_only", None
120
+ if isinstance(target, Buffered):
121
+ return "buffered", None
122
+ if isinstance(target, AsyncBuffered):
123
+ return "async_only", None
124
+ if isinstance(target, (Bulkhead, AdaptiveLimiter)):
125
+ return "idle", None
126
+ aflush = getattr(target, "aflush", None)
127
+ if callable(aflush):
128
+ return "callable", aflush
129
+ flush = getattr(target, "flush", None)
130
+ if callable(flush):
131
+ return "callable", flush
132
+ if callable(target):
133
+ return "callable", target
134
+ raise TypeError(
135
+ f"cannot register {target!r}: expected a python-wrap object (periodic, buffered, "
136
+ "batcher, debouncer, bulkhead, limiter) or a callable"
137
+ )
138
+
139
+
140
+ def _busy(target: Any) -> int:
141
+ if isinstance(target, Bulkhead):
142
+ return target.active + target.waiting
143
+ return int(target.in_flight)
144
+
145
+
146
+ def _remaining(deadline: float | None) -> float | None:
147
+ return None if deadline is None else max(0.0, deadline - time.monotonic())
148
+
149
+
150
+ async def _await_value(awaitable: Awaitable[Any]) -> Any:
151
+ return await awaitable
152
+
153
+
154
+ def _call_in_thread(fn: Callable[[], Any], remaining: float | None) -> bool:
155
+ """Run ``fn`` (awaiting an awaitable result) in a daemon thread; False on timeout."""
156
+ outcome: list[BaseException] = []
157
+ deadline = None if remaining is None else time.monotonic() + remaining
158
+
159
+ if deadline is not None and _remaining(deadline) == 0:
160
+ return False
161
+
162
+ def target() -> None:
163
+ try:
164
+ result = fn()
165
+ if inspect.isawaitable(result):
166
+ asyncio.run(_await_value(result))
167
+ except BaseException as exc:
168
+ outcome.append(exc)
169
+
170
+ thread = threading.Thread(target=target, name="python-wrap-shutdown", daemon=True)
171
+ thread.start()
172
+ while thread.is_alive():
173
+ left = _remaining(deadline)
174
+ if left == 0:
175
+ break
176
+ thread.join(left)
177
+ if thread.is_alive():
178
+ return False
179
+ if outcome:
180
+ raise outcome[0]
181
+ return True
182
+
183
+
184
+ def _wait_idle_sync(target: Any, remaining: float | None) -> bool:
185
+ deadline = None if remaining is None else time.monotonic() + remaining
186
+ while _busy(target) > 0:
187
+ left = _remaining(deadline)
188
+ if left is not None and left <= 0:
189
+ return False
190
+ time.sleep(_POLL if left is None else min(_POLL, left))
191
+ return True
192
+
193
+
194
+ async def _wait_idle_async(target: Any, remaining: float | None) -> bool:
195
+ deadline = None if remaining is None else time.monotonic() + remaining
196
+ while _busy(target) > 0:
197
+ left = _remaining(deadline)
198
+ if left is not None and left <= 0:
199
+ return False
200
+ await asyncio.sleep(_POLL if left is None else min(_POLL, left))
201
+ return True
202
+
203
+
204
+ def _retrieve(task: asyncio.Future[Any]) -> None:
205
+ if not task.cancelled():
206
+ task.exception()
207
+
208
+
209
+ async def _within(awaitable: Awaitable[Any], remaining: float | None) -> tuple[bool, Any]:
210
+ """Await with a real-time budget. Returns (finished, result); re-raises its error."""
211
+ task = asyncio.ensure_future(awaitable)
212
+ done, _ = await asyncio.wait({task}, timeout=remaining)
213
+ if not done:
214
+ task.cancel()
215
+ task.add_done_callback(_retrieve)
216
+ return False, None
217
+ return True, task.result()
218
+
219
+
220
+ class ShutdownManager:
221
+ """A registry of things to wind down, drained once and in order.
222
+
223
+ `register` accepts python-wrap objects and plain callables:
224
+
225
+ * `Periodic` / `AsyncPeriodic`: the loop is stopped (no new runs start);
226
+ * `Buffered` / `AsyncBuffered`: closed, which flushes queued records first;
227
+ * batchers (`batch_calls`) and debouncers (`debounce`): flushed;
228
+ * `Bulkhead` / `AdaptiveLimiter`: waited on until no call is running or waiting;
229
+ * any other callable (sync or `async def`): called.
230
+
231
+ `drain` runs the items by ascending `priority` (ties in registration order) within a
232
+ single time budget, records ok / error / timeout per item and never raises unless
233
+ `strict=True`. Draining is idempotent: later calls return the first report. Register
234
+ producers (periodic tasks) before consumers (buffers), e.g. periodic at `priority=0`,
235
+ buffers at `10`, connection pools at `20`, and bulkheads at `5` so in-flight work
236
+ finishes before writers close.
237
+
238
+ Items that live on an event loop (`AsyncPeriodic`, `AsyncBuffered`) need `adrain()`;
239
+ in a sync `drain()` they are reported as errors.
240
+
241
+ A forked child starts with an empty registry (the parent's resources are not the
242
+ child's to stop).
243
+
244
+ Example:
245
+ ```python
246
+ from python_wrap.lifecycle import ShutdownManager
247
+
248
+ manager = ShutdownManager()
249
+ order: list[str] = []
250
+ manager.register(lambda: order.append("close db"), name="db", priority=20)
251
+ manager.register(lambda: order.append("stop jobs"), name="jobs", priority=0)
252
+
253
+ report = manager.drain(timeout=5)
254
+ assert report.ok and order == ["stop jobs", "close db"]
255
+ assert manager.drain() is report # second call is a no-op
256
+ ```
257
+ """
258
+
259
+ def __init__(self) -> None:
260
+ self._lock = _fork.ForkSafeLock()
261
+ self._items: list[_Item] = []
262
+ self._seq = 0
263
+ self._state: Literal["idle", "draining", "done"] = "idle"
264
+ self._report: ShutdownReport | None = None
265
+ self._finished = threading.Event()
266
+ self._drain_thread: int | None = None
267
+ self._previous: dict[int, Any] = {}
268
+ self._handlers: dict[int, Callable[[int, FrameType | None], None]] = {}
269
+ self._tasks: set[asyncio.Task[None]] = set()
270
+ self._atexit_installed = False
271
+ self._atexit_timeout: float | None = 30
272
+ _fork.register(self)
273
+
274
+ def __reduce__(self) -> NoReturn:
275
+ _core.refuse_pickle(self)
276
+
277
+ def _reset_after_fork(self) -> None:
278
+ self._items = []
279
+ self._seq = 0
280
+ self._state = "idle"
281
+ self._report = None
282
+ self._finished = threading.Event()
283
+ self._drain_thread = None
284
+ self._tasks = set()
285
+
286
+ # -- registry -----------------------------------------------------------------------
287
+
288
+ def register(self, target: Any, *, name: str | None = None, priority: int = 0) -> Any:
289
+ """Add something to wind down. Returns `target`, so it can wrap a constructor.
290
+
291
+ Args:
292
+ target: A python-wrap object or a callable (sync or async).
293
+ name: Label for the report; defaults to the object's name.
294
+ priority: Lower runs first.
295
+
296
+ Returns:
297
+ `target`, unchanged.
298
+
299
+ Raises:
300
+ TypeError: `target` is neither a known object nor callable.
301
+ RuntimeError: Draining already started.
302
+ """
303
+ kind, fn = _classify(target)
304
+ label = name or getattr(target, "_name", None) or getattr(target, "name", None)
305
+ label = label if isinstance(label, str) and label else _core.qualname(target)
306
+ with self._lock:
307
+ if self._state != "idle":
308
+ raise RuntimeError("cannot register: shutdown has already started")
309
+ self._seq += 1
310
+ self._items.append(_Item(label, priority, self._seq, target, kind, fn))
311
+ return target
312
+
313
+ def unregister(self, target: Any) -> bool:
314
+ """Remove a registered object (by identity) or name. Returns True if found."""
315
+ with self._lock:
316
+ before = len(self._items)
317
+ self._items = [i for i in self._items if i.target is not target and i.name != target]
318
+ return len(self._items) != before
319
+
320
+ @property
321
+ def names(self) -> list[str]:
322
+ """Registered names in the order they would run."""
323
+ with self._lock:
324
+ return [i.name for i in self._ordered()]
325
+
326
+ @property
327
+ def shutting_down(self) -> bool:
328
+ """True once a drain has started (use it for readiness checks)."""
329
+ return self._state != "idle"
330
+
331
+ @property
332
+ def report(self) -> ShutdownReport | None:
333
+ """The report of the finished drain, or `None`."""
334
+ return self._report
335
+
336
+ def reset(self) -> None:
337
+ """Forget everything and allow a new drain. Meant for tests."""
338
+ with self._lock:
339
+ self._reset_after_fork()
340
+
341
+ def _ordered(self) -> list[_Item]:
342
+ return sorted(self._items, key=lambda i: (i.priority, i.seq))
343
+
344
+ # -- drain --------------------------------------------------------------------------
345
+
346
+ def _begin(self) -> list[_Item] | None:
347
+ with self._lock:
348
+ if self._state != "idle":
349
+ return None
350
+ self._state = "draining"
351
+ self._drain_thread = threading.get_ident()
352
+ items = self._ordered()
353
+ _core.emit("lifecycle.drain_started", "shutdown", items=len(items))
354
+ return items
355
+
356
+ def _record(
357
+ self, name: str, status: Status, error: BaseException | None, start: float
358
+ ) -> ItemReport:
359
+ seconds = time.monotonic() - start
360
+ _core.emit("lifecycle.item_done", name, status=status, seconds=seconds)
361
+ if status == "error":
362
+ _core.get_logger().warning("shutdown: %s failed", name, exc_info=error)
363
+ elif status == "timeout":
364
+ _core.get_logger().warning("shutdown: %s did not finish in time", name)
365
+ return ItemReport(name, status, error, seconds)
366
+
367
+ def _complete(self, reports: list[ItemReport], start: float) -> ShutdownReport:
368
+ report = ShutdownReport(tuple(reports), time.monotonic() - start)
369
+ with self._lock:
370
+ self._report = report
371
+ self._state = "done"
372
+ self._drain_thread = None
373
+ self._finished.set()
374
+ _core.emit("lifecycle.drain_finished", "shutdown", ok=report.ok, seconds=report.seconds)
375
+ return report
376
+
377
+ def _existing(self, timeout: float | None) -> ShutdownReport:
378
+ if self._state == "draining" and self._drain_thread != threading.get_ident():
379
+ self._finished.wait(timeout)
380
+ return self._report or ShutdownReport()
381
+
382
+ def _finish_strict(self, report: ShutdownReport, strict: bool) -> ShutdownReport:
383
+ if strict and not report.ok:
384
+ raise ShutdownError(f"shutdown incomplete: {report}", report=report)
385
+ return report
386
+
387
+ def drain(self, timeout: float | None = 30, *, strict: bool = False) -> ShutdownReport:
388
+ """Wind everything down, blocking the calling thread.
389
+
390
+ Args:
391
+ timeout: Total seconds for the whole drain (real time); `None` waits forever.
392
+ Items that would start after the budget is spent are skipped and
393
+ reported as `"timeout"`.
394
+ strict: Raise `ShutdownError` if any item failed or timed out.
395
+
396
+ Returns:
397
+ The `ShutdownReport`. A second call returns the first report unchanged.
398
+
399
+ Raises:
400
+ ShutdownError: `strict=True` and the drain was not clean.
401
+ """
402
+ items = self._begin()
403
+ if items is None:
404
+ return self._finish_strict(self._existing(timeout), strict)
405
+ start = time.monotonic()
406
+ deadline = None if timeout is None else start + timeout
407
+ reports: list[ItemReport] = []
408
+ for item in items:
409
+ began = time.monotonic()
410
+ left = _remaining(deadline)
411
+ if left is not None and left <= 0:
412
+ reports.append(self._record(item.name, "timeout", None, began))
413
+ continue
414
+ try:
415
+ finished = self._run_sync(item, left)
416
+ except Exception as exc:
417
+ reports.append(self._record(item.name, "error", exc, began))
418
+ else:
419
+ reports.append(
420
+ self._record(item.name, "ok" if finished else "timeout", None, began)
421
+ )
422
+ if item.kind == "callable" and left is not None and not finished:
423
+ # `_call_in_thread` can return just after the deadline while a
424
+ # coarse clock still reports a sliver left. Count it as spent.
425
+ deadline = time.monotonic()
426
+ return self._finish_strict(self._complete(reports, start), strict)
427
+
428
+ def _run_sync(self, item: _Item, remaining: float | None) -> bool:
429
+ target = item.target
430
+ if item.kind == "periodic":
431
+ return bool(target.stop(remaining))
432
+ if item.kind == "buffered":
433
+ return bool(target.close(remaining))
434
+ if item.kind == "idle":
435
+ return _wait_idle_sync(target, remaining)
436
+ if item.kind == "async_only":
437
+ raise RuntimeError(f"{item.name} runs on an event loop: use adrain()")
438
+ assert item.fn is not None
439
+ return _call_in_thread(item.fn, remaining)
440
+
441
+ async def adrain(self, timeout: float | None = 30, *, strict: bool = False) -> ShutdownReport:
442
+ """Async variant of `drain`: runs on the event loop, blocking work in threads.
443
+
444
+ Same semantics, ordering and idempotence as `drain`. Use it in async framework
445
+ hooks (FastAPI lifespan, aiohttp `on_cleanup`).
446
+ """
447
+ items = self._begin()
448
+ if items is None:
449
+ deadline = None if timeout is None else time.monotonic() + timeout
450
+ while self._state == "draining" and (left := _remaining(deadline)) != 0:
451
+ await asyncio.sleep(_POLL if left is None else min(_POLL, left))
452
+ return self._finish_strict(self._report or ShutdownReport(), strict)
453
+ start = time.monotonic()
454
+ deadline = None if timeout is None else start + timeout
455
+ reports: list[ItemReport] = []
456
+ for item in items:
457
+ began = time.monotonic()
458
+ left = _remaining(deadline)
459
+ if left is not None and left <= 0:
460
+ reports.append(self._record(item.name, "timeout", None, began))
461
+ continue
462
+ try:
463
+ finished = await self._run_async(item, left)
464
+ except Exception as exc:
465
+ reports.append(self._record(item.name, "error", exc, began))
466
+ else:
467
+ reports.append(
468
+ self._record(item.name, "ok" if finished else "timeout", None, began)
469
+ )
470
+ return self._finish_strict(self._complete(reports, start), strict)
471
+
472
+ async def _run_async(self, item: _Item, remaining: float | None) -> bool:
473
+ target = item.target
474
+ if item.kind == "periodic":
475
+ return bool(await asyncio.to_thread(target.stop, remaining))
476
+ if item.kind == "async_only" and isinstance(target, AsyncPeriodic):
477
+ return (await _within(target.stop(), remaining))[0]
478
+ if item.kind == "buffered":
479
+ return bool(await asyncio.to_thread(target.close, remaining))
480
+ if item.kind == "async_only":
481
+ finished, result = await _within(target.close(remaining), remaining)
482
+ return finished and bool(result)
483
+ if item.kind == "idle":
484
+ return await _wait_idle_async(target, remaining)
485
+ fn = item.fn
486
+ assert fn is not None
487
+ deadline = None if remaining is None else time.monotonic() + remaining
488
+ if _core.is_async(fn):
489
+ return (await _within(fn(), remaining))[0]
490
+ finished, result = await _within(asyncio.to_thread(fn), remaining)
491
+ if finished and inspect.isawaitable(result):
492
+ finished, _ = await _within(result, _remaining(deadline))
493
+ return finished
494
+
495
+ # -- atexit -------------------------------------------------------------------------
496
+
497
+ def install_atexit(self, timeout: float | None = 30) -> None:
498
+ """Drain when the interpreter exits normally. Safe to call repeatedly."""
499
+ with self._lock:
500
+ if self._atexit_installed:
501
+ return
502
+ self._atexit_installed = True
503
+ self._atexit_timeout = timeout
504
+ atexit.register(self._on_atexit)
505
+
506
+ def uninstall_atexit(self) -> None:
507
+ """Undo `install_atexit`."""
508
+ with self._lock:
509
+ if not self._atexit_installed:
510
+ return
511
+ self._atexit_installed = False
512
+ atexit.unregister(self._on_atexit)
513
+
514
+ def _on_atexit(self) -> None:
515
+ try:
516
+ self.drain(self._atexit_timeout)
517
+ except Exception: # pragma: no cover - drain does not raise unless strict
518
+ _core.get_logger().exception("shutdown at exit failed")
519
+
520
+ # -- signals ------------------------------------------------------------------------
521
+
522
+ def install_signal_handlers(
523
+ self,
524
+ signals: Iterable[int] = (signal.SIGTERM, signal.SIGINT),
525
+ *,
526
+ timeout: float | None = 30,
527
+ exit: bool = True,
528
+ chain: bool = True,
529
+ ) -> list[int]:
530
+ """Drain when one of `signals` arrives.
531
+
532
+ Inside a running event loop the handler schedules `adrain()` on it; otherwise it
533
+ runs `drain()` right in the handler. Afterwards the previous handler is called
534
+ (`chain`), and the process exits with status `128 + signum` (`exit`) unless the
535
+ previous handler already ended it (the default `SIGINT` handler raises
536
+ `KeyboardInterrupt`). A second signal while draining skips straight to the
537
+ exit step, so a second Ctrl-C forces the exit.
538
+
539
+ Args:
540
+ signals: Signal numbers to handle.
541
+ timeout: Drain budget in seconds.
542
+ exit: Exit the process after draining.
543
+ chain: Call the handler that was installed before.
544
+
545
+ Returns:
546
+ The signals that were installed (already-installed ones are skipped).
547
+
548
+ Raises:
549
+ RuntimeError: Not called from the main thread.
550
+ """
551
+ if threading.current_thread() is not threading.main_thread():
552
+ raise RuntimeError("signal handlers can only be installed from the main thread")
553
+ installed: list[int] = []
554
+ for signum in signals:
555
+ signum = int(signum)
556
+ if signum in self._handlers:
557
+ continue
558
+
559
+ def handler(
560
+ received: int,
561
+ frame: FrameType | None,
562
+ _t: float | None = timeout,
563
+ _e: bool = exit,
564
+ _c: bool = chain,
565
+ ) -> None:
566
+ self._on_signal(received, frame, _t, _e, _c)
567
+
568
+ self._previous[signum] = signal.signal(signum, handler)
569
+ self._handlers[signum] = handler
570
+ installed.append(signum)
571
+ return installed
572
+
573
+ def restore_signal_handlers(self) -> list[int]:
574
+ """Put back the handlers that were replaced. Returns the signals restored.
575
+
576
+ A handler someone installed on top of ours is left alone.
577
+ """
578
+ if threading.current_thread() is not threading.main_thread():
579
+ raise RuntimeError("signal handlers can only be restored from the main thread")
580
+ restored: list[int] = []
581
+ for signum, ours in list(self._handlers.items()):
582
+ if signal.getsignal(signum) is ours:
583
+ previous = self._previous.get(signum)
584
+ signal.signal(signum, signal.SIG_DFL if previous is None else previous)
585
+ restored.append(signum)
586
+ del self._handlers[signum]
587
+ self._previous.pop(signum, None)
588
+ return restored
589
+
590
+ def _on_signal(
591
+ self, signum: int, frame: FrameType | None, timeout: float | None, exit: bool, chain: bool
592
+ ) -> None:
593
+ try:
594
+ loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()
595
+ except RuntimeError:
596
+ loop = None
597
+ if loop is not None:
598
+ task = loop.create_task(self._signal_async(signum, frame, timeout, exit, chain))
599
+ self._tasks.add(task)
600
+ task.add_done_callback(self._tasks.discard)
601
+ return
602
+ self.drain(timeout)
603
+ self._after_signal(signum, frame, exit, chain)
604
+
605
+ async def _signal_async(
606
+ self, signum: int, frame: FrameType | None, timeout: float | None, exit: bool, chain: bool
607
+ ) -> None:
608
+ await self.adrain(timeout)
609
+ self._after_signal(signum, frame, exit, chain)
610
+
611
+ def _after_signal(self, signum: int, frame: FrameType | None, exit: bool, chain: bool) -> None:
612
+ previous = self._previous.get(signum)
613
+ if chain and callable(previous):
614
+ previous(signum, frame)
615
+ if exit:
616
+ sys.exit(128 + signum)
617
+
618
+
619
+ shutdown = ShutdownManager()
620
+ """The shared process-wide manager."""