Debian Codegraph @

src/trio/_core/_generated_run.py

raw
1 # ***********************************************************
2 # ******* WARNING: AUTOGENERATED! ALL EDITS WILL BE LOST ******
3 # *************************************************************
4 from __future__ import annotations
5
6 from typing import TYPE_CHECKING
7
8 from ._ki import enable_ki_protection
9 from ._run import _NO_SEND, GLOBAL_RUN_CONTEXT, RunStatistics, Task
10
11 if TYPE_CHECKING:
12 import contextvars
13 from collections.abc import Awaitable, Callable
14
15 import outcome
16 from typing_extensions import Unpack
17
18 from .._abc import Clock
19 from ._entry_queue import TrioToken
20 from ._run import PosArgT
21
22
23 __all__ = [
24 "current_clock",
25 "current_root_task",
26 "current_statistics",
27 "current_time",
28 "current_trio_token",
29 "reschedule",
30 "spawn_system_task",
31 "wait_all_tasks_blocked",
32 ]
33
34
35 @enable_ki_protection
36 def current_statistics() -> RunStatistics:
37 """Returns ``RunStatistics``, which contains run-loop-level debugging information.
38
39 Currently, the following fields are defined:
40
41 * ``tasks_living`` (int): The number of tasks that have been spawned
42 and not yet exited.
43 * ``tasks_runnable`` (int): The number of tasks that are currently
44 queued on the run queue (as opposed to blocked waiting for something
45 to happen).
46 * ``seconds_to_next_deadline`` (float): The time until the next
47 pending cancel scope deadline. May be negative if the deadline has
48 expired but we haven't yet processed cancellations. May be
49 :data:`~math.inf` if there are no pending deadlines.
50 * ``run_sync_soon_queue_size`` (int): The number of
51 unprocessed callbacks queued via
52 :meth:`trio.lowlevel.TrioToken.run_sync_soon`.
53 * ``io_statistics`` (object): Some statistics from Trio's I/O
54 backend. This always has an attribute ``backend`` which is a string
55 naming which operating-system-specific I/O backend is in use; the
56 other attributes vary between backends.
57
58 """
59 try:
60 return GLOBAL_RUN_CONTEXT.runner.current_statistics()
61 except AttributeError:
62 raise RuntimeError("must be called from async context") from None
63
64
65 @enable_ki_protection
66 def current_time() -> float:
67 """Returns the current time according to Trio's internal clock.
68
69 Returns:
70 float: The current time.
71
72 Raises:
73 RuntimeError: if not inside a call to :func:`trio.run`.
74
75 """
76 try:
77 return GLOBAL_RUN_CONTEXT.runner.current_time()
78 except AttributeError:
79 raise RuntimeError("must be called from async context") from None
80
81
82 @enable_ki_protection
83 def current_clock() -> Clock:
84 """Returns the current :class:`~trio.abc.Clock`."""
85 try:
86 return GLOBAL_RUN_CONTEXT.runner.current_clock()
87 except AttributeError:
88 raise RuntimeError("must be called from async context") from None
89
90
91 @enable_ki_protection
92 def current_root_task() -> Task | None:
93 """Returns the current root :class:`Task`.
94
95 This is the task that is the ultimate parent of all other tasks.
96
97 """
98 try:
99 return GLOBAL_RUN_CONTEXT.runner.current_root_task()
100 except AttributeError:
101 raise RuntimeError("must be called from async context") from None
102
103
104 @enable_ki_protection
105 def reschedule(task: Task, next_send: outcome.Outcome[object] = _NO_SEND) -> None:
106 """Reschedule the given task with the given
107 :class:`outcome.Outcome`.
108
109 See :func:`wait_task_rescheduled` for the gory details.
110
111 There must be exactly one call to :func:`reschedule` for every call to
112 :func:`wait_task_rescheduled`. (And when counting, keep in mind that
113 returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent
114 to calling :func:`reschedule` once.)
115
116 Args:
117 task (trio.lowlevel.Task): the task to be rescheduled. Must be blocked
118 in a call to :func:`wait_task_rescheduled`.
119 next_send (outcome.Outcome): the value (or error) to return (or
120 raise) from :func:`wait_task_rescheduled`.
121
122 """
123 try:
124 return GLOBAL_RUN_CONTEXT.runner.reschedule(task, next_send)
125 except AttributeError:
126 raise RuntimeError("must be called from async context") from None
127
128
129 @enable_ki_protection
130 def spawn_system_task(
131 async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]],
132 *args: Unpack[PosArgT],
133 name: object = None,
134 context: contextvars.Context | None = None,
135 ) -> Task:
136 """Spawn a "system" task.
137
138 System tasks have a few differences from regular tasks:
139
140 * They don't need an explicit nursery; instead they go into the
141 internal "system nursery".
142
143 * If a system task raises an exception, then it's converted into a
144 :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. If you
145 write a system task, you should be careful to make sure it doesn't
146 crash.
147
148 * System tasks are automatically cancelled when the main task exits.
149
150 * By default, system tasks have :exc:`KeyboardInterrupt` protection
151 *enabled*. If you want your task to be interruptible by control-C,
152 then you need to use :func:`disable_ki_protection` explicitly (and
153 come up with some plan for what to do with a
154 :exc:`KeyboardInterrupt`, given that system tasks aren't allowed to
155 raise exceptions).
156
157 * System tasks do not inherit context variables from their creator.
158
159 Towards the end of a call to :meth:`trio.run`, after the main
160 task and all system tasks have exited, the system nursery
161 becomes closed. At this point, new calls to
162 :func:`spawn_system_task` will raise ``RuntimeError("Nursery
163 is closed to new arrivals")`` instead of creating a system
164 task. It's possible to encounter this state either in
165 a ``finally`` block in an async generator, or in a callback
166 passed to :meth:`TrioToken.run_sync_soon` at the right moment.
167
168 Args:
169 async_fn: An async callable.
170 args: Positional arguments for ``async_fn``. If you want to pass
171 keyword arguments, use :func:`functools.partial`.
172 name: The name for this task. Only used for debugging/introspection
173 (e.g. ``repr(task_obj)``). If this isn't a string,
174 :func:`spawn_system_task` will try to make it one. A common use
175 case is if you're wrapping a function before spawning a new
176 task, you might pass the original function as the ``name=`` to
177 make debugging easier.
178 context: An optional ``contextvars.Context`` object with context variables
179 to use for this task. You would normally get a copy of the current
180 context with ``context = contextvars.copy_context()`` and then you would
181 pass that ``context`` object here.
182
183 Returns:
184 Task: the newly spawned task
185
186 """
187 try:
188 return GLOBAL_RUN_CONTEXT.runner.spawn_system_task(
189 async_fn, *args, name=name, context=context
190 )
191 except AttributeError:
192 raise RuntimeError("must be called from async context") from None
193
194
195 @enable_ki_protection
196 def current_trio_token() -> TrioToken:
197 """Retrieve the :class:`TrioToken` for the current call to
198 :func:`trio.run`.
199
200 """
201 try:
202 return GLOBAL_RUN_CONTEXT.runner.current_trio_token()
203 except AttributeError:
204 raise RuntimeError("must be called from async context") from None
205
206
207 @enable_ki_protection
208 async def wait_all_tasks_blocked(cushion: float = 0.0) -> None:
209 """Block until there are no runnable tasks.
210
211 This is useful in testing code when you want to give other tasks a
212 chance to "settle down". The calling task is blocked, and doesn't wake
213 up until all other tasks are also blocked for at least ``cushion``
214 seconds. (Setting a non-zero ``cushion`` is intended to handle cases
215 like two tasks talking to each other over a local socket, where we
216 want to ignore the potential brief moment between a send and receive
217 when all tasks are blocked.)
218
219 Note that ``cushion`` is measured in *real* time, not the Trio clock
220 time.
221
222 If there are multiple tasks blocked in :func:`wait_all_tasks_blocked`,
223 then the one with the shortest ``cushion`` is the one woken (and
224 this task becoming unblocked resets the timers for the remaining
225 tasks). If there are multiple tasks that have exactly the same
226 ``cushion``, then all are woken.
227
228 You should also consider :class:`trio.testing.Sequencer`, which
229 provides a more explicit way to control execution ordering within a
230 test, and will often produce more readable tests.
231
232 Example:
233 Here's an example of one way to test that Trio's locks are fair: we
234 take the lock in the parent, start a child, wait for the child to be
235 blocked waiting for the lock (!), and then check that we can't
236 release and immediately re-acquire the lock::
237
238 async def lock_taker(lock):
239 await lock.acquire()
240 lock.release()
241
242 async def test_lock_fairness():
243 lock = trio.Lock()
244 await lock.acquire()
245 async with trio.open_nursery() as nursery:
246 nursery.start_soon(lock_taker, lock)
247 # child hasn't run yet, we have the lock
248 assert lock.locked()
249 assert lock._owner is trio.lowlevel.current_task()
250 await trio.testing.wait_all_tasks_blocked()
251 # now the child has run and is blocked on lock.acquire(), we
252 # still have the lock
253 assert lock.locked()
254 assert lock._owner is trio.lowlevel.current_task()
255 lock.release()
256 try:
257 # The child has a prior claim, so we can't have it
258 lock.acquire_nowait()
259 except trio.WouldBlock:
260 assert lock._owner is not trio.lowlevel.current_task()
261 print("PASS")
262 else:
263 print("FAIL")
264
265 """
266 try:
267 return await GLOBAL_RUN_CONTEXT.runner.wait_all_tasks_blocked(cushion)
268 except AttributeError:
269 raise RuntimeError("must be called from async context") from None