Debian Codegraph @

Lib/asyncio/timeouts.py

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