Debian Codegraph @

src/trio/_core/_entry_queue.py

raw
1 from __future__ import annotations
2
3 import threading
4 from collections import deque
5 from collections.abc import Callable
6 from typing import TYPE_CHECKING, NoReturn
7
8 import attrs
9
10 from .. import _core
11 from .._util import NoPublicConstructor, final
12 from ._wakeup_socketpair import WakeupSocketpair
13
14 if TYPE_CHECKING:
15 from typing_extensions import TypeVarTuple, Unpack
16
17 PosArgsT = TypeVarTuple("PosArgsT")
18
19 Function = Callable[..., object] # type: ignore[explicit-any]
20 Job = tuple[Function, tuple[object, ...]]
21
22
23 @attrs.define
24 class EntryQueue:
25 # This used to use a queue.Queue. but that was broken, because Queues are
26 # implemented in Python, and not reentrant -- so it was thread-safe, but
27 # not signal-safe. deque is implemented in C, so each operation is atomic
28 # WRT threads (and this is guaranteed in the docs), AND each operation is
29 # atomic WRT signal delivery (signal handlers can run on either side, but
30 # not *during* a deque operation). dict makes similar guarantees - and
31 # it's even ordered!
32 queue: deque[Job] = attrs.Factory(deque)
33 idempotent_queue: dict[Job, None] = attrs.Factory(dict)
34
35 wakeup: WakeupSocketpair = attrs.Factory(WakeupSocketpair)
36 done: bool = False
37 # Must be a reentrant lock, because it's acquired from signal handlers.
38 # RLock is signal-safe as of cpython 3.2. NB that this does mean that the
39 # lock is effectively *disabled* when we enter from signal context. The
40 # way we use the lock this is OK though, because when
41 # run_sync_soon is called from a signal it's atomic WRT the
42 # main thread -- it just might happen at some inconvenient place. But if
43 # you look at the one place where the main thread holds the lock, it's
44 # just to make 1 assignment, so that's atomic WRT a signal anyway.
45 lock: threading.RLock = attrs.Factory(threading.RLock)
46
47 async def task(self) -> None:
48 assert _core.currently_ki_protected()
49 # RLock has two implementations: a signal-safe version in _thread, and
50 # and signal-UNsafe version in threading. We need the signal safe
51 # version. Python 3.2 and later should always use this anyway, but,
52 # since the symptoms if this goes wrong are just "weird rare
53 # deadlocks", then let's make a little check.
54 # See:
55 # https://bugs.python.org/issue13697#msg237140
56 assert self.lock.__class__.__module__ == "_thread"
57
58 def run_cb(job: Job) -> None:
59 # We run this with KI protection enabled; it's the callback's
60 # job to disable it if it wants it disabled. Exceptions are
61 # treated like system task exceptions (i.e., converted into
62 # TrioInternalError and cause everything to shut down).
63 sync_fn, args = job
64 try:
65 sync_fn(*args)
66 except BaseException as exc:
67
68 async def kill_everything( # noqa: RUF029 # await not used
69 exc: BaseException,
70 ) -> NoReturn:
71 raise exc
72
73 try:
74 _core.spawn_system_task(kill_everything, exc)
75 except RuntimeError:
76 # We're quite late in the shutdown process and the
77 # system nursery is already closed.
78 # TODO(2020-06): this is a gross hack and should
79 # be fixed soon when we address #1607.
80 parent_nursery = _core.current_task().parent_nursery
81 if parent_nursery is None:
82 raise AssertionError(
83 "Internal error: `parent_nursery` should never be `None`",
84 ) from exc # pragma: no cover
85 parent_nursery.start_soon(kill_everything, exc)
86
87 # This has to be carefully written to be safe in the face of new items
88 # being queued while we iterate, and to do a bounded amount of work on
89 # each pass:
90 def run_all_bounded() -> None:
91 for _ in range(len(self.queue)):
92 run_cb(self.queue.popleft())
93 for job in list(self.idempotent_queue):
94 del self.idempotent_queue[job]
95 run_cb(job)
96
97 try:
98 while True:
99 run_all_bounded()
100 if not self.queue and not self.idempotent_queue:
101 await self.wakeup.wait_woken()
102 else:
103 await _core.checkpoint()
104 except _core.Cancelled:
105 # Keep the work done with this lock held as minimal as possible,
106 # because it doesn't protect us against concurrent signal delivery
107 # (see the comment above). Notice that this code would still be
108 # correct if written like:
109 # self.done = True
110 # with self.lock:
111 # pass
112 # because all we want is to force run_sync_soon
113 # to either be completely before or completely after the write to
114 # done. That's why we don't need the lock to protect
115 # against signal handlers.
116 with self.lock:
117 self.done = True
118 # No more jobs will be submitted, so just clear out any residual
119 # ones:
120 run_all_bounded()
121 assert not self.queue
122 assert not self.idempotent_queue
123
124 def close(self) -> None:
125 self.wakeup.close()
126
127 def size(self) -> int:
128 return len(self.queue) + len(self.idempotent_queue)
129
130 def run_sync_soon(
131 self,
132 sync_fn: Callable[[Unpack[PosArgsT]], object],
133 *args: Unpack[PosArgsT],
134 idempotent: bool = False,
135 ) -> None:
136 with self.lock:
137 if self.done:
138 raise _core.RunFinishedError("run() has exited")
139 # We have to hold the lock all the way through here, because
140 # otherwise the main thread might exit *while* we're doing these
141 # calls, and then our queue item might not be processed, or the
142 # wakeup call might trigger an OSError b/c the IO manager has
143 # already been shut down.
144 if idempotent:
145 self.idempotent_queue[sync_fn, args] = None
146 else:
147 self.queue.append((sync_fn, args))
148 self.wakeup.wakeup_thread_and_signal_safe()
149
150
151 @final
152 @attrs.define(eq=False)
153 class TrioToken(metaclass=NoPublicConstructor):
154 """An opaque object representing a single call to :func:`trio.run`.
155
156 It has no public constructor; instead, see :func:`current_trio_token`.
157
158 This object has two uses:
159
160 1. It lets you re-enter the Trio run loop from external threads or signal
161 handlers. This is the low-level primitive that :func:`trio.to_thread`
162 and `trio.from_thread` use to communicate with worker threads, that
163 `trio.open_signal_receiver` uses to receive notifications about
164 signals, and so forth.
165
166 2. Each call to :func:`trio.run` has exactly one associated
167 :class:`TrioToken` object, so you can use it to identify a particular
168 call.
169
170 """
171
172 _reentry_queue: EntryQueue
173
174 def run_sync_soon(
175 self,
176 sync_fn: Callable[[Unpack[PosArgsT]], object],
177 *args: Unpack[PosArgsT],
178 idempotent: bool = False,
179 ) -> None:
180 """Schedule a call to ``sync_fn(*args)`` to occur in the context of a
181 Trio task.
182
183 This is safe to call from the main thread, from other threads, and
184 from signal handlers. This is the fundamental primitive used to
185 re-enter the Trio run loop from outside of it.
186
187 The call will happen "soon", but there's no guarantee about exactly
188 when, and no mechanism provided for finding out when it's happened.
189 If you need this, you'll have to build your own.
190
191 The call is effectively run as part of a system task (see
192 :func:`~trio.lowlevel.spawn_system_task`). In particular this means
193 that:
194
195 * :exc:`KeyboardInterrupt` protection is *enabled* by default; if
196 you want ``sync_fn`` to be interruptible by control-C, then you
197 need to use :func:`~trio.lowlevel.disable_ki_protection`
198 explicitly.
199
200 * If ``sync_fn`` raises an exception, then it's converted into a
201 :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. You
202 should be careful that ``sync_fn`` doesn't crash.
203
204 All calls with ``idempotent=False`` are processed in strict
205 first-in first-out order.
206
207 If ``idempotent=True``, then ``sync_fn`` and ``args`` must be
208 hashable, and Trio will make a best-effort attempt to discard any
209 call submission which is equal to an already-pending call. Trio
210 will process these in first-in first-out order.
211
212 Any ordering guarantees apply separately to ``idempotent=False``
213 and ``idempotent=True`` calls; there's no rule for how calls in the
214 different categories are ordered with respect to each other.
215
216 :raises trio.RunFinishedError:
217 if the associated call to :func:`trio.run`
218 has already exited. (Any call that *doesn't* raise this error
219 is guaranteed to be fully processed before :func:`trio.run`
220 exits.)
221
222 """
223 self._reentry_queue.run_sync_soon(sync_fn, *args, idempotent=idempotent)