| 1 |
import enum |
| 2 |
|
| 3 |
from types import TracebackType |
| 4 |
from typing import final, Optional, Type |
| 5 |
|
| 6 |
from . import events |
| 7 |
from . import exceptions |
| 8 |
from . import tasks |
| 9 |
|
| 10 |
|
| 11 |
__all__ = ( |
| 12 |
"Timeout", |
| 13 |
"timeout", |
| 14 |
"timeout_at", |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
class _State(enum.Enum): |
| 19 |
CREATED = "created" |
| 20 |
ENTERED = "active" |
| 21 |
EXPIRING = "expiring" |
| 22 |
EXPIRED = "expired" |
| 23 |
EXITED = "finished" |
| 24 |
|
| 25 |
|
| 26 |
@final |
| 27 |
class Timeout: |
| 28 |
"""Asynchronous context manager for cancelling overdue coroutines. |
| 29 |
|
| 30 |
Use `timeout()` or `timeout_at()` rather than instantiating this class |
| 31 |
directly. |
| 32 |
""" |
| 33 |
|
| 34 |
def __init__(self, when: Optional[float]) -> None: |
| 35 |
"""Schedule a timeout that will trigger at a given loop time. |
| 36 |
|
| 37 |
- If `when` is `None`, the timeout will never trigger. |
| 38 |
- If `when < loop.time()`, the timeout will trigger on the next |
| 39 |
iteration of the event loop. |
| 40 |
""" |
| 41 |
self._state = _State.CREATED |
| 42 |
|
| 43 |
self._timeout_handler: Optional[events.TimerHandle] = None |
| 44 |
self._task: Optional[tasks.Task] = None |
| 45 |
self._when = when |
| 46 |
|
| 47 |
def when(self) -> Optional[float]: |
| 48 |
"""Return the current deadline.""" |
| 49 |
return self._when |
| 50 |
|
| 51 |
def reschedule(self, when: Optional[float]) -> None: |
| 52 |
"""Reschedule the timeout.""" |
| 53 |
if self._state is not _State.ENTERED: |
| 54 |
if self._state is _State.CREATED: |
| 55 |
raise RuntimeError("Timeout has not been entered") |
| 56 |
raise RuntimeError( |
| 57 |
f"Cannot change state of {self._state.value} Timeout", |
| 58 |
) |
| 59 |
|
| 60 |
self._when = when |
| 61 |
|
| 62 |
if self._timeout_handler is not None: |
| 63 |
self._timeout_handler.cancel() |
| 64 |
|
| 65 |
if when is None: |
| 66 |
self._timeout_handler = None |
| 67 |
else: |
| 68 |
loop = events.get_running_loop() |
| 69 |
if when <= loop.time(): |
| 70 |
self._timeout_handler = loop.call_soon(self._on_timeout) |
| 71 |
else: |
| 72 |
self._timeout_handler = loop.call_at(when, self._on_timeout) |
| 73 |
|
| 74 |
def expired(self) -> bool: |
| 75 |
"""Is timeout expired during execution?""" |
| 76 |
return self._state in (_State.EXPIRING, _State.EXPIRED) |
| 77 |
|
| 78 |
def __repr__(self) -> str: |
| 79 |
info = [''] |
| 80 |
if self._state is _State.ENTERED: |
| 81 |
when = round(self._when, 3) if self._when is not None else None |
| 82 |
info.append(f"when={when}") |
| 83 |
info_str = ' '.join(info) |
| 84 |
return f"<Timeout [{self._state.value}]{info_str}>" |
| 85 |
|
| 86 |
async def __aenter__(self) -> "Timeout": |
| 87 |
if self._state is not _State.CREATED: |
| 88 |
raise RuntimeError("Timeout has already been entered") |
| 89 |
task = tasks.current_task() |
| 90 |
if task is None: |
| 91 |
raise RuntimeError("Timeout should be used inside a task") |
| 92 |
self._state = _State.ENTERED |
| 93 |
self._task = task |
| 94 |
self._cancelling = self._task.cancelling() |
| 95 |
self.reschedule(self._when) |
| 96 |
return self |
| 97 |
|
| 98 |
async def __aexit__( |
| 99 |
self, |
| 100 |
exc_type: Optional[Type[BaseException]], |
| 101 |
exc_val: Optional[BaseException], |
| 102 |
exc_tb: Optional[TracebackType], |
| 103 |
) -> Optional[bool]: |
| 104 |
assert self._state in (_State.ENTERED, _State.EXPIRING) |
| 105 |
|
| 106 |
if self._timeout_handler is not None: |
| 107 |
self._timeout_handler.cancel() |
| 108 |
self._timeout_handler = None |
| 109 |
|
| 110 |
if self._state is _State.EXPIRING: |
| 111 |
self._state = _State.EXPIRED |
| 112 |
|
| 113 |
if self._task.uncancel() <= self._cancelling and exc_type is not None: |
| 114 |
# Since there are no new cancel requests, we're |
| 115 |
# handling this. |
| 116 |
if issubclass(exc_type, exceptions.CancelledError): |
| 117 |
raise TimeoutError from exc_val |
| 118 |
elif exc_val is not None: |
| 119 |
self._insert_timeout_error(exc_val) |
| 120 |
if isinstance(exc_val, ExceptionGroup): |
| 121 |
for exc in exc_val.exceptions: |
| 122 |
self._insert_timeout_error(exc) |
| 123 |
elif self._state is _State.ENTERED: |
| 124 |
self._state = _State.EXITED |
| 125 |
|
| 126 |
return None |
| 127 |
|
| 128 |
def _on_timeout(self) -> None: |
| 129 |
assert self._state is _State.ENTERED |
| 130 |
self._task.cancel() |
| 131 |
self._state = _State.EXPIRING |
| 132 |
# drop the reference early |
| 133 |
self._timeout_handler = None |
| 134 |
|
| 135 |
@staticmethod |
| 136 |
def _insert_timeout_error(exc_val: BaseException) -> None: |
| 137 |
while exc_val.__context__ is not None: |
| 138 |
if isinstance(exc_val.__context__, exceptions.CancelledError): |
| 139 |
te = TimeoutError() |
| 140 |
te.__context__ = te.__cause__ = exc_val.__context__ |
| 141 |
exc_val.__context__ = te |
| 142 |
break |
| 143 |
exc_val = exc_val.__context__ |
| 144 |
|
| 145 |
|
| 146 |
def timeout(delay: Optional[float]) -> Timeout: |
| 147 |
"""Timeout async context manager. |
| 148 |
|
| 149 |
Useful in cases when you want to apply timeout logic around block |
| 150 |
of code or in cases when asyncio.wait_for is not suitable. For example: |
| 151 |
|
| 152 |
>>> async with asyncio.timeout(10): # 10 seconds timeout |
| 153 |
... await long_running_task() |
| 154 |
|
| 155 |
|
| 156 |
delay - value in seconds or None to disable timeout logic |
| 157 |
|
| 158 |
long_running_task() is interrupted by raising asyncio.CancelledError, |
| 159 |
the top-most affected timeout() context manager converts CancelledError |
| 160 |
into TimeoutError. |
| 161 |
""" |
| 162 |
loop = events.get_running_loop() |
| 163 |
return Timeout(loop.time() + delay if delay is not None else None) |
| 164 |
|
| 165 |
|
| 166 |
def timeout_at(when: Optional[float]) -> Timeout: |
| 167 |
"""Schedule the timeout at absolute time. |
| 168 |
|
| 169 |
Like timeout() but argument gives absolute time in the same clock system |
| 170 |
as loop.time(). |
| 171 |
|
| 172 |
Please note: it is not POSIX time but a time with |
| 173 |
undefined starting base, e.g. the time of the system power on. |
| 174 |
|
| 175 |
>>> async with asyncio.timeout_at(loop.time() + 10): |
| 176 |
... await long_running_task() |
| 177 |
|
| 178 |
|
| 179 |
when - a deadline when timeout occurs or None to disable timeout logic |
| 180 |
|
| 181 |
long_running_task() is interrupted by raising asyncio.CancelledError, |
| 182 |
the top-most affected timeout() context manager converts CancelledError |
| 183 |
into TimeoutError. |
| 184 |
""" |
| 185 |
return Timeout(when) |