_asyncio_timeout.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Copyright © 2001 Python Software Foundation. All rights reserved.
  2. # SPDX-License-Identifier: PSF-2.0
  3. # Backport of asyncio.timeout for Python 3.10
  4. from __future__ import annotations
  5. import enum
  6. import sys
  7. from asyncio import events, exceptions, tasks
  8. from typing import TYPE_CHECKING
  9. if TYPE_CHECKING:
  10. from types import TracebackType
  11. _HAX_EXCEPTION_GROUP = sys.version_info >= (3, 11)
  12. class _State(enum.Enum):
  13. CREATED = "created"
  14. ENTERED = "active"
  15. EXPIRING = "expiring"
  16. EXPIRED = "expired"
  17. EXITED = "finished"
  18. # Modifications - we don't track task cancellation on enter.
  19. class Timeout:
  20. """Asynchronous context manager for cancelling overdue coroutines.
  21. Use `timeout()` or `timeout_at()` rather than instantiating this class directly.
  22. """
  23. def __init__(self, when: float | None) -> None:
  24. """Schedule a timeout that will trigger at a given loop time.
  25. - If `when` is `None`, the timeout will never trigger.
  26. - If `when < loop.time()`, the timeout will trigger on the next
  27. iteration of the event loop.
  28. """
  29. self._state = _State.CREATED
  30. self._timeout_handler: events.Handle | None = None
  31. self._task: tasks.Task | None = None
  32. self._when = when
  33. def when(self) -> float | None:
  34. """Return the current deadline."""
  35. return self._when
  36. def reschedule(self, when: float | None) -> None:
  37. """Reschedule the timeout."""
  38. if self._state is not _State.ENTERED:
  39. if self._state is _State.CREATED:
  40. msg = "Timeout has not been entered"
  41. raise RuntimeError(msg)
  42. msg = f"Cannot change state of {self._state.value} Timeout"
  43. raise RuntimeError(msg)
  44. self._when = when
  45. if self._timeout_handler is not None:
  46. self._timeout_handler.cancel()
  47. if when is None:
  48. self._timeout_handler = None
  49. else:
  50. loop = events.get_running_loop()
  51. if when <= loop.time():
  52. self._timeout_handler = loop.call_soon(self._on_timeout)
  53. else:
  54. self._timeout_handler = loop.call_at(when, self._on_timeout)
  55. def expired(self) -> bool:
  56. """Is timeout expired during execution?"""
  57. return self._state in (_State.EXPIRING, _State.EXPIRED)
  58. def __repr__(self) -> str:
  59. info = [""]
  60. if self._state is _State.ENTERED:
  61. when = round(self._when, 3) if self._when is not None else None
  62. info.append(f"when={when}")
  63. info_str = " ".join(info)
  64. return f"<Timeout [{self._state.value}]{info_str}>"
  65. async def __aenter__(self) -> Timeout:
  66. if self._state is not _State.CREATED:
  67. msg = "Timeout has already been entered"
  68. raise RuntimeError(msg)
  69. task = tasks.current_task()
  70. if task is None:
  71. msg = "Timeout should be used inside a task"
  72. raise RuntimeError(msg)
  73. self._state = _State.ENTERED
  74. self._task = task
  75. self.reschedule(self._when)
  76. return self
  77. async def __aexit__(
  78. self,
  79. exc_type: type[BaseException] | None,
  80. exc_val: BaseException | None,
  81. exc_tb: TracebackType | None,
  82. ) -> bool | None:
  83. assert self._state in (_State.ENTERED, _State.EXPIRING) # noqa: S101
  84. if self._timeout_handler is not None:
  85. self._timeout_handler.cancel()
  86. self._timeout_handler = None
  87. if self._state is _State.EXPIRING:
  88. self._state = _State.EXPIRED
  89. if exc_type is not None:
  90. # Since there are no new cancel requests, we're
  91. # handling this.
  92. if issubclass(exc_type, exceptions.CancelledError):
  93. raise TimeoutError from exc_val
  94. if exc_val is not None:
  95. self._insert_timeout_error(exc_val)
  96. if _HAX_EXCEPTION_GROUP and isinstance(exc_val, ExceptionGroup): # noqa: F821
  97. for exc in exc_val.exceptions:
  98. self._insert_timeout_error(exc)
  99. elif self._state is _State.ENTERED:
  100. self._state = _State.EXITED
  101. return None
  102. def _on_timeout(self) -> None:
  103. assert self._state is _State.ENTERED # noqa: S101
  104. assert self._task is not None # noqa: S101
  105. self._task.cancel()
  106. self._state = _State.EXPIRING
  107. # drop the reference early
  108. self._timeout_handler = None
  109. @staticmethod
  110. def _insert_timeout_error(exc_val: BaseException) -> None:
  111. while exc_val.__context__ is not None:
  112. if isinstance(exc_val.__context__, exceptions.CancelledError):
  113. te = TimeoutError()
  114. te.__context__ = te.__cause__ = exc_val.__context__
  115. exc_val.__context__ = te
  116. break
  117. exc_val = exc_val.__context__
  118. def timeout(delay: float | None) -> Timeout:
  119. """Timeout async context manager.
  120. Useful in cases when you want to apply timeout logic around block
  121. of code or in cases when asyncio.wait_for is not suitable. For example:
  122. >>> async with asyncio.timeout(10): # 10 seconds timeout
  123. ... await long_running_task()
  124. delay - value in seconds or None to disable timeout logic
  125. long_running_task() is interrupted by raising asyncio.CancelledError,
  126. the top-most affected timeout() context manager converts CancelledError
  127. into TimeoutError.
  128. """
  129. loop = events.get_running_loop()
  130. return Timeout(loop.time() + delay if delay is not None else None)