Debian Codegraph @

src/trio/_core/_traps.py

raw
1 """These are the only functions that ever yield back to the task runner."""
2
3 from __future__ import annotations
4
5 import enum
6 import types
7
8 # typing.Callable is necessary because collections.abc.Callable breaks
9 # test_static_tool_sees_all_symbols in 3.10.
10 from typing import ( # noqa: UP035
11 TYPE_CHECKING,
12 Any,
13 Callable,
14 NoReturn,
15 TypeAlias,
16 cast,
17 )
18
19 import attrs
20 import outcome
21
22 from . import _run
23
24 if TYPE_CHECKING:
25 from collections.abc import Awaitable, Generator
26
27 from ._run import Task
28
29 RaiseCancelT: TypeAlias = Callable[[], NoReturn]
30
31
32 # This class object is used as a singleton.
33 # Not exported in the trio._core namespace, but imported directly by _run.
34 class CancelShieldedCheckpoint:
35 __slots__ = ()
36
37
38 # Not exported in the trio._core namespace, but imported directly by _run.
39 @attrs.frozen(slots=False)
40 class WaitTaskRescheduled:
41 abort_func: Callable[[RaiseCancelT], Abort]
42
43
44 # Not exported in the trio._core namespace, but imported directly by _run.
45 @attrs.frozen(slots=False)
46 class PermanentlyDetachCoroutineObject:
47 final_outcome: outcome.Outcome[object]
48
49
50 MessageType: TypeAlias = (
51 type[CancelShieldedCheckpoint]
52 | WaitTaskRescheduled
53 | PermanentlyDetachCoroutineObject
54 | object
55 )
56
57
58 # Helper for the bottommost 'yield'. You can't use 'yield' inside an async
59 # function, but you can inside a generator, and if you decorate your generator
60 # with @types.coroutine, then it's even awaitable. However, it's still not a
61 # real async function: in particular, it isn't recognized by
62 # inspect.iscoroutinefunction, and it doesn't trigger the unawaited coroutine
63 # tracking machinery. Since our traps are public APIs, we make them real async
64 # functions, and then this helper takes care of the actual yield:
65 @types.coroutine
66 def _real_async_yield(
67 obj: MessageType,
68 ) -> Generator[MessageType, None, None]:
69 # "Using `yield` and `return {value}` in a generator function can
70 # lead to confusing behavior"
71 return (yield obj) # noqa: B901
72
73
74 # Real yield value is from trio's main loop, but type checkers can't
75 # understand that, so we cast it to make type checkers understand.
76 _async_yield = cast(
77 "Callable[[MessageType], Awaitable[outcome.Outcome[object]]]",
78 _real_async_yield,
79 )
80
81
82 async def cancel_shielded_checkpoint() -> None:
83 """Introduce a schedule point, but not a cancel point.
84
85 This is *not* a :ref:`checkpoint <checkpoints>`, but it is half of a
86 checkpoint, and when combined with :func:`checkpoint_if_cancelled` it can
87 make a full checkpoint.
88
89 Equivalent to (but potentially more efficient than)::
90
91 with trio.CancelScope(shield=True):
92 await trio.lowlevel.checkpoint()
93
94 """
95 (await _async_yield(CancelShieldedCheckpoint)).unwrap()
96
97
98 # Return values for abort functions
99 class Abort(enum.Enum):
100 """:class:`enum.Enum` used as the return value from abort functions.
101
102 See :func:`wait_task_rescheduled` for details.
103
104 .. data:: SUCCEEDED
105 FAILED
106
107 """
108
109 SUCCEEDED = 1
110 FAILED = 2
111
112
113 # Should always return the type a Task "expects", unless you willfully reschedule it
114 # with a bad value.
115 async def wait_task_rescheduled( # type: ignore[explicit-any]
116 abort_func: Callable[[RaiseCancelT], Abort],
117 ) -> Any:
118 """Put the current task to sleep, with cancellation support.
119
120 This is the lowest-level API for blocking in Trio. Every time a
121 :class:`~trio.lowlevel.Task` blocks, it does so by calling this function
122 (usually indirectly via some higher-level API).
123
124 This is a tricky interface with no guard rails. If you can use
125 :class:`ParkingLot` or the built-in I/O wait functions instead, then you
126 should.
127
128 Generally the way it works is that before calling this function, you make
129 arrangements for "someone" to call :func:`reschedule` on the current task
130 at some later point.
131
132 Then you call :func:`wait_task_rescheduled`, passing in ``abort_func``, an
133 "abort callback".
134
135 (Terminology: in Trio, "aborting" is the process of attempting to
136 interrupt a blocked task to deliver a cancellation.)
137
138 There are two possibilities for what happens next:
139
140 1. "Someone" calls :func:`reschedule` on the current task, and
141 :func:`wait_task_rescheduled` returns or raises whatever value or error
142 was passed to :func:`reschedule`.
143
144 2. The call's context transitions to a cancelled state (e.g. due to a
145 timeout expiring). When this happens, the ``abort_func`` is called. Its
146 interface looks like::
147
148 def abort_func(raise_cancel):
149 ...
150 return trio.lowlevel.Abort.SUCCEEDED # or FAILED
151
152 It should attempt to clean up any state associated with this call, and
153 in particular, arrange that :func:`reschedule` will *not* be called
154 later. If (and only if!) it is successful, then it should return
155 :data:`Abort.SUCCEEDED`, in which case the task will automatically be
156 rescheduled with an appropriate :exc:`~trio.Cancelled` error.
157
158 Otherwise, it should return :data:`Abort.FAILED`. This means that the
159 task can't be cancelled at this time, and still has to make sure that
160 "someone" eventually calls :func:`reschedule`.
161
162 At that point there are again two possibilities. You can simply ignore
163 the cancellation altogether: wait for the operation to complete and
164 then reschedule and continue as normal. (For example, this is what
165 :func:`trio.to_thread.run_sync` does if cancellation is disabled.)
166 The other possibility is that the ``abort_func`` does succeed in
167 cancelling the operation, but for some reason isn't able to report that
168 right away. (Example: on Windows, it's possible to request that an
169 async ("overlapped") I/O operation be cancelled, but this request is
170 *also* asynchronous – you don't find out until later whether the
171 operation was actually cancelled or not.) To report a delayed
172 cancellation, then you should reschedule the task yourself, and call
173 the ``raise_cancel`` callback passed to ``abort_func`` to raise a
174 :exc:`~trio.Cancelled` (or possibly :exc:`KeyboardInterrupt`) exception
175 into this task. Either of the approaches sketched below can work::
176
177 # Option 1:
178 # Catch the exception from raise_cancel and inject it into the task.
179 # (This is what Trio does automatically for you if you return
180 # Abort.SUCCEEDED.)
181 trio.lowlevel.reschedule(task, outcome.capture(raise_cancel))
182
183 # Option 2:
184 # wait to be woken by "someone", and then decide whether to raise
185 # the error from inside the task.
186 outer_raise_cancel = None
187 def abort(inner_raise_cancel):
188 nonlocal outer_raise_cancel
189 outer_raise_cancel = inner_raise_cancel
190 TRY_TO_CANCEL_OPERATION()
191 return trio.lowlevel.Abort.FAILED
192 await wait_task_rescheduled(abort)
193 if OPERATION_WAS_SUCCESSFULLY_CANCELLED:
194 # raises the error
195 outer_raise_cancel()
196
197 In any case it's guaranteed that we only call the ``abort_func`` at most
198 once per call to :func:`wait_task_rescheduled`.
199
200 Sometimes, it's useful to be able to share some mutable sleep-related data
201 between the sleeping task, the abort function, and the waking task. You
202 can use the sleeping task's :data:`~Task.custom_sleep_data` attribute to
203 store this data, and Trio won't touch it, except to make sure that it gets
204 cleared when the task is rescheduled.
205
206 .. warning::
207
208 If your ``abort_func`` raises an error, or returns any value other than
209 :data:`Abort.SUCCEEDED` or :data:`Abort.FAILED`, then Trio will crash
210 violently. Be careful! Similarly, it is entirely possible to deadlock a
211 Trio program by failing to reschedule a blocked task, or cause havoc by
212 calling :func:`reschedule` too many times. Remember what we said up
213 above about how you should use a higher-level API if at all possible?
214
215 """
216 return (await _async_yield(WaitTaskRescheduled(abort_func))).unwrap()
217
218
219 async def permanently_detach_coroutine_object(
220 final_outcome: outcome.Outcome[object],
221 ) -> object:
222 """Permanently detach the current task from the Trio scheduler.
223
224 Normally, a Trio task doesn't exit until its coroutine object exits. When
225 you call this function, Trio acts like the coroutine object just exited
226 and the task terminates with the given outcome. This is useful if you want
227 to permanently switch the coroutine object over to a different coroutine
228 runner.
229
230 When the calling coroutine enters this function it's running under Trio,
231 and when the function returns it's running under the foreign coroutine
232 runner.
233
234 You should make sure that the coroutine object has released any
235 Trio-specific resources it has acquired (e.g. nurseries).
236
237 Args:
238 final_outcome (outcome.Outcome): Trio acts as if the current task exited
239 with the given return value or exception.
240
241 Returns or raises whatever value or exception the new coroutine runner
242 uses to resume the coroutine.
243
244 """
245 if _run.current_task().child_nurseries:
246 raise RuntimeError(
247 "can't permanently detach a coroutine object with open nurseries",
248 )
249 return await _async_yield(PermanentlyDetachCoroutineObject(final_outcome))
250
251
252 async def temporarily_detach_coroutine_object(
253 abort_func: Callable[[RaiseCancelT], Abort],
254 ) -> object:
255 """Temporarily detach the current coroutine object from the Trio
256 scheduler.
257
258 When the calling coroutine enters this function it's running under Trio,
259 and when the function returns it's running under the foreign coroutine
260 runner.
261
262 The Trio :class:`Task` will continue to exist, but will be suspended until
263 you use :func:`reattach_detached_coroutine_object` to resume it. In the
264 mean time, you can use another coroutine runner to schedule the coroutine
265 object. In fact, you have to – the function doesn't return until the
266 coroutine is advanced from outside.
267
268 Note that you'll need to save the current :class:`Task` object to later
269 resume; you can retrieve it with :func:`current_task`. You can also use
270 this :class:`Task` object to retrieve the coroutine object – see
271 :data:`Task.coro`.
272
273 Args:
274 abort_func: Same as for :func:`wait_task_rescheduled`, except that it
275 must return :data:`Abort.FAILED`. (If it returned
276 :data:`Abort.SUCCEEDED`, then Trio would attempt to reschedule the
277 detached task directly without going through
278 :func:`reattach_detached_coroutine_object`, which would be bad.)
279 Your ``abort_func`` should still arrange for whatever the coroutine
280 object is doing to be cancelled, and then reattach to Trio and call
281 the ``raise_cancel`` callback, if possible.
282
283 Returns or raises whatever value or exception the new coroutine runner
284 uses to resume the coroutine.
285
286 """
287 return await _async_yield(WaitTaskRescheduled(abort_func))
288
289
290 async def reattach_detached_coroutine_object(task: Task, yield_value: object) -> None:
291 """Reattach a coroutine object that was detached using
292 :func:`temporarily_detach_coroutine_object`.
293
294 When the calling coroutine enters this function it's running under the
295 foreign coroutine runner, and when the function returns it's running under
296 Trio.
297
298 This must be called from inside the coroutine being resumed, and yields
299 whatever value you pass in. (Presumably you'll pass a value that will
300 cause the current coroutine runner to stop scheduling this task.) Then the
301 coroutine is resumed by the Trio scheduler at the next opportunity.
302
303 Args:
304 task (Task): The Trio task object that the current coroutine was
305 detached from.
306 yield_value (object): The object to yield to the current coroutine
307 runner.
308
309 """
310 # This is a kind of crude check – in particular, it can fail if the
311 # passed-in task is where the coroutine *runner* is running. But this is
312 # an experts-only interface, and there's no easy way to do a more accurate
313 # check, so I guess that's OK.
314 if not task.coro.cr_running:
315 raise RuntimeError("given task does not match calling coroutine")
316 _run.reschedule(task, outcome.Value("reattaching"))
317 value = await _async_yield(yield_value)
318 assert value == outcome.Value("reattaching")