async_utils.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Async/sync bridging helpers.
  2. ``asyncio.run_coroutine_threadsafe`` can raise ``RuntimeError`` (loop closed during a
  3. shutdown race); the coroutine is then never awaited or closed, which triggers a
  4. "coroutine was never awaited" RuntimeWarning and leaks its frame. The helpers here
  5. close the coroutine on scheduling failure. ``future.result()`` failures are deliberately
  6. NOT handled: once the loop accepts the coroutine its lifecycle belongs to the loop.
  7. """
  8. from __future__ import annotations
  9. import asyncio
  10. import logging
  11. from concurrent.futures import Future
  12. from typing import Any, Coroutine, Optional
  13. _DEFAULT_LOGGER = logging.getLogger(__name__)
  14. def safe_schedule_threadsafe(
  15. coro: Coroutine[Any, Any, Any], loop: Optional[asyncio.AbstractEventLoop], *,
  16. logger: Optional[logging.Logger] = None,
  17. log_message: str = "Failed to schedule coroutine on loop", log_level: int = logging.DEBUG,
  18. ) -> Optional[Future]:
  19. """Schedule ``coro`` on ``loop`` from a sync context, leak-safe.
  20. Returns the Future on success, or ``None`` if the loop is missing or scheduling
  21. raised; in every failure path the coroutine is closed. Callers keep full control
  22. over the returned future (``.result(timeout=...)``, callbacks, fire-and-forget).
  23. """
  24. log = logger if logger is not None else _DEFAULT_LOGGER
  25. try:
  26. if loop is None:
  27. raise RuntimeError("loop is None")
  28. return asyncio.run_coroutine_threadsafe(coro, loop)
  29. except Exception as exc:
  30. if asyncio.iscoroutine(coro):
  31. coro.close()
  32. log.log(log_level, "%s: %s", log_message, exc)
  33. return None
  34. def consume_detached_task_result(task: asyncio.Future[Any]) -> None:
  35. """``add_done_callback`` for cancelled-and-detached tasks: observe the exception so the
  36. loop does not log "exception was never retrieved"; cancellation and terminal errors
  37. are swallowed because the task's owner already gave up on it."""
  38. try:
  39. task.exception()
  40. except (asyncio.CancelledError, Exception):
  41. pass