| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import enum |
| 4 |
import functools |
| 5 |
import gc |
| 6 |
import itertools |
| 7 |
import random |
| 8 |
import select |
| 9 |
import sys |
| 10 |
import warnings |
| 11 |
from collections import deque |
| 12 |
from contextlib import AbstractAsyncContextManager, contextmanager, suppress |
| 13 |
from contextvars import copy_context |
| 14 |
from heapq import heapify, heappop, heappush |
| 15 |
from math import inf, isnan |
| 16 |
from time import perf_counter |
| 17 |
from typing import ( |
| 18 |
TYPE_CHECKING, |
| 19 |
Any, |
| 20 |
Final, |
| 21 |
NoReturn, |
| 22 |
Protocol, |
| 23 |
cast, |
| 24 |
overload, |
| 25 |
) |
| 26 |
|
| 27 |
import attrs |
| 28 |
import outcome |
| 29 |
from outcome import Error, Outcome, Value, capture |
| 30 |
from sniffio import thread_local as sniffio_library |
| 31 |
from sortedcontainers import SortedDict |
| 32 |
|
| 33 |
from .. import _core |
| 34 |
from .._abc import Clock, Instrument |
| 35 |
from .._deprecate import warn_deprecated |
| 36 |
from .._util import NoPublicConstructor, coroutine_or_error, final, raise_saving_context |
| 37 |
from ._asyncgens import AsyncGenerators |
| 38 |
from ._concat_tb import concat_tb |
| 39 |
from ._entry_queue import EntryQueue, TrioToken |
| 40 |
from ._exceptions import ( |
| 41 |
Cancelled, |
| 42 |
CancelReasonLiteral, |
| 43 |
RunFinishedError, |
| 44 |
TrioInternalError, |
| 45 |
) |
| 46 |
from ._instrumentation import Instruments |
| 47 |
from ._ki import KIManager, enable_ki_protection |
| 48 |
from ._parking_lot import GLOBAL_PARKING_LOT_BREAKER |
| 49 |
from ._run_context import GLOBAL_RUN_CONTEXT as GLOBAL_RUN_CONTEXT |
| 50 |
from ._thread_cache import start_thread_soon |
| 51 |
from ._traps import ( |
| 52 |
Abort, |
| 53 |
CancelShieldedCheckpoint, |
| 54 |
PermanentlyDetachCoroutineObject, |
| 55 |
WaitTaskRescheduled, |
| 56 |
cancel_shielded_checkpoint, |
| 57 |
wait_task_rescheduled, |
| 58 |
) |
| 59 |
|
| 60 |
if sys.version_info < (3, 11): |
| 61 |
from exceptiongroup import BaseExceptionGroup |
| 62 |
|
| 63 |
|
| 64 |
if TYPE_CHECKING: |
| 65 |
import contextvars |
| 66 |
import types |
| 67 |
from collections.abc import ( |
| 68 |
Awaitable, |
| 69 |
Callable, |
| 70 |
Generator, |
| 71 |
Iterator, |
| 72 |
Sequence, |
| 73 |
) |
| 74 |
from types import TracebackType |
| 75 |
|
| 76 |
# for some strange reason Sphinx works with outcome.Outcome, but not Outcome, in |
| 77 |
# start_guest_run. Same with types.FrameType in iter_await_frames |
| 78 |
from typing_extensions import Self, TypeVar, TypeVarTuple, Unpack |
| 79 |
|
| 80 |
PosArgT = TypeVarTuple("PosArgT") |
| 81 |
StatusT = TypeVar("StatusT", default=None) |
| 82 |
StatusT_contra = TypeVar("StatusT_contra", contravariant=True, default=None) |
| 83 |
BaseExcT = TypeVar("BaseExcT", bound=BaseException) |
| 84 |
else: |
| 85 |
from typing import TypeVar |
| 86 |
|
| 87 |
StatusT = TypeVar("StatusT") |
| 88 |
StatusT_contra = TypeVar("StatusT_contra", contravariant=True) |
| 89 |
|
| 90 |
RetT = TypeVar("RetT") |
| 91 |
|
| 92 |
|
| 93 |
DEADLINE_HEAP_MIN_PRUNE_THRESHOLD: Final = 1000 |
| 94 |
|
| 95 |
# Passed as a sentinel |
| 96 |
_NO_SEND: Final[Outcome[object]] = cast("Outcome[object]", object()) |
| 97 |
|
| 98 |
# Used to track if an exceptiongroup can be collapsed |
| 99 |
NONSTRICT_EXCEPTIONGROUP_NOTE = 'This is a "loose" ExceptionGroup, and may be collapsed by Trio if it only contains one exception - typically after `Cancelled` has been stripped from it. Note this has consequences for exception handling, and strict_exception_groups=True is recommended.' |
| 100 |
|
| 101 |
|
| 102 |
@final |
| 103 |
class _NoStatus(metaclass=NoPublicConstructor): |
| 104 |
"""Sentinel for unset TaskStatus._value.""" |
| 105 |
|
| 106 |
|
| 107 |
# Decorator to mark methods public. This does nothing by itself, but |
| 108 |
# trio/_tools/gen_exports.py looks for it. |
| 109 |
def _public(fn: RetT) -> RetT: |
| 110 |
return fn |
| 111 |
|
| 112 |
|
| 113 |
# When running under Hypothesis, we want examples to be reproducible and |
| 114 |
# shrinkable. We therefore register `_hypothesis_plugin_setup()` as a |
| 115 |
# plugin, so that importing *Hypothesis* will make Trio's task |
| 116 |
# scheduling loop deterministic. We have a test for that, of course. |
| 117 |
# Before Hypothesis supported entry-point plugins this integration was |
| 118 |
# handled by pytest-trio, but we want it to work in e.g. unittest too. |
| 119 |
_ALLOW_DETERMINISTIC_SCHEDULING: Final = False |
| 120 |
_r = random.Random() |
| 121 |
|
| 122 |
|
| 123 |
# no cover because we don't check the hypothesis plugin works with hypothesis |
| 124 |
def _hypothesis_plugin_setup() -> None: # pragma: no cover |
| 125 |
from hypothesis import register_random |
| 126 |
|
| 127 |
global _ALLOW_DETERMINISTIC_SCHEDULING |
| 128 |
_ALLOW_DETERMINISTIC_SCHEDULING = True # type: ignore |
| 129 |
register_random(_r) |
| 130 |
|
| 131 |
# monkeypatch repr_callable to make repr's way better |
| 132 |
# requires importing hypothesis (in the test file or in conftest.py) |
| 133 |
try: |
| 134 |
from hypothesis.internal.reflection import get_pretty_function_description |
| 135 |
|
| 136 |
import trio.testing._raises_group |
| 137 |
|
| 138 |
def repr_callable(fun: Callable[[BaseExcT], bool]) -> str: |
| 139 |
# add quotes around the signature |
| 140 |
return repr(get_pretty_function_description(fun)) |
| 141 |
|
| 142 |
trio.testing._raises_group.repr_callable = repr_callable |
| 143 |
except ImportError: |
| 144 |
pass |
| 145 |
|
| 146 |
|
| 147 |
def _count_context_run_tb_frames() -> int: |
| 148 |
"""Count implementation dependent traceback frames from Context.run() |
| 149 |
|
| 150 |
On CPython, Context.run() is implemented in C and doesn't show up in |
| 151 |
tracebacks. On PyPy, it is implemented in Python and adds 1 frame to |
| 152 |
tracebacks. |
| 153 |
|
| 154 |
Returns: |
| 155 |
int: Traceback frame count |
| 156 |
|
| 157 |
""" |
| 158 |
|
| 159 |
def function_with_unique_name_xyzzy() -> NoReturn: |
| 160 |
try: |
| 161 |
1 / 0 # noqa: B018 # We need a ZeroDivisionError to fire |
| 162 |
except ZeroDivisionError: |
| 163 |
raise |
| 164 |
else: # pragma: no cover |
| 165 |
raise TrioInternalError( |
| 166 |
"A ZeroDivisionError should have been raised, but it wasn't.", |
| 167 |
) |
| 168 |
|
| 169 |
ctx = copy_context() |
| 170 |
try: |
| 171 |
ctx.run(function_with_unique_name_xyzzy) |
| 172 |
except ZeroDivisionError as exc: |
| 173 |
tb = exc.__traceback__ |
| 174 |
# Skip the frame where we caught it |
| 175 |
tb = tb.tb_next # type: ignore[union-attr] |
| 176 |
count = 0 |
| 177 |
while tb.tb_frame.f_code.co_name != "function_with_unique_name_xyzzy": # type: ignore[union-attr] |
| 178 |
tb = tb.tb_next # type: ignore[union-attr] |
| 179 |
count += 1 |
| 180 |
return count |
| 181 |
else: # pragma: no cover |
| 182 |
raise TrioInternalError( |
| 183 |
f"The purpose of {function_with_unique_name_xyzzy.__name__} is " |
| 184 |
"to raise a ZeroDivisionError, but it didn't.", |
| 185 |
) |
| 186 |
|
| 187 |
|
| 188 |
CONTEXT_RUN_TB_FRAMES: Final = _count_context_run_tb_frames() |
| 189 |
|
| 190 |
|
| 191 |
@attrs.frozen |
| 192 |
class SystemClock(Clock): |
| 193 |
# Add a large random offset to our clock to ensure that if people |
| 194 |
# accidentally call time.perf_counter() directly or start comparing clocks |
| 195 |
# between different runs, then they'll notice the bug quickly: |
| 196 |
offset: float = attrs.Factory(lambda: _r.uniform(10000, 200000)) |
| 197 |
|
| 198 |
def start_clock(self) -> None: |
| 199 |
pass |
| 200 |
|
| 201 |
# In cPython 3, on every platform except Windows, perf_counter is |
| 202 |
# exactly the same as time.monotonic; and on Windows, it uses |
| 203 |
# QueryPerformanceCounter instead of GetTickCount64. |
| 204 |
def current_time(self) -> float: |
| 205 |
return self.offset + perf_counter() |
| 206 |
|
| 207 |
def deadline_to_sleep_time(self, deadline: float) -> float: |
| 208 |
return deadline - self.current_time() |
| 209 |
|
| 210 |
|
| 211 |
class IdlePrimedTypes(enum.Enum): |
| 212 |
WAITING_FOR_IDLE = 1 |
| 213 |
AUTOJUMP_CLOCK = 2 |
| 214 |
|
| 215 |
|
| 216 |
################################################################ |
| 217 |
# CancelScope and friends |
| 218 |
################################################################ |
| 219 |
|
| 220 |
|
| 221 |
def collapse_exception_group( |
| 222 |
excgroup: BaseExceptionGroup[BaseException], |
| 223 |
) -> BaseException: |
| 224 |
"""Recursively collapse any single-exception groups into that single contained |
| 225 |
exception. |
| 226 |
|
| 227 |
""" |
| 228 |
exceptions = list(excgroup.exceptions) |
| 229 |
modified = False |
| 230 |
for i, exc in enumerate(exceptions): |
| 231 |
if isinstance(exc, BaseExceptionGroup): |
| 232 |
new_exc = collapse_exception_group(exc) |
| 233 |
if new_exc is not exc: |
| 234 |
modified = True |
| 235 |
exceptions[i] = new_exc |
| 236 |
|
| 237 |
if ( |
| 238 |
len(exceptions) == 1 |
| 239 |
and isinstance(excgroup, BaseExceptionGroup) |
| 240 |
and NONSTRICT_EXCEPTIONGROUP_NOTE in getattr(excgroup, "__notes__", ()) |
| 241 |
): |
| 242 |
exceptions[0].__traceback__ = concat_tb( |
| 243 |
excgroup.__traceback__, |
| 244 |
exceptions[0].__traceback__, |
| 245 |
) |
| 246 |
return exceptions[0] |
| 247 |
elif modified: |
| 248 |
return excgroup.derive(exceptions) |
| 249 |
else: |
| 250 |
return excgroup |
| 251 |
|
| 252 |
|
| 253 |
@attrs.define(eq=False) |
| 254 |
class Deadlines: |
| 255 |
"""A container of deadlined cancel scopes. |
| 256 |
|
| 257 |
Only contains scopes with non-infinite deadlines that are currently |
| 258 |
attached to at least one task. |
| 259 |
|
| 260 |
""" |
| 261 |
|
| 262 |
# Heap of (deadline, id(CancelScope), CancelScope) |
| 263 |
_heap: list[tuple[float, int, CancelScope]] = attrs.Factory(list) |
| 264 |
# Count of active deadlines (those that haven't been changed) |
| 265 |
_active: int = 0 |
| 266 |
|
| 267 |
def add(self, deadline: float, cancel_scope: CancelScope) -> None: |
| 268 |
heappush(self._heap, (deadline, id(cancel_scope), cancel_scope)) |
| 269 |
self._active += 1 |
| 270 |
|
| 271 |
def remove(self, deadline: float, cancel_scope: CancelScope) -> None: |
| 272 |
self._active -= 1 |
| 273 |
|
| 274 |
def next_deadline(self) -> float: |
| 275 |
while self._heap: |
| 276 |
deadline, _, cancel_scope = self._heap[0] |
| 277 |
if deadline == cancel_scope._registered_deadline: |
| 278 |
return deadline |
| 279 |
else: |
| 280 |
# This entry is stale; discard it and try again |
| 281 |
heappop(self._heap) |
| 282 |
return inf |
| 283 |
|
| 284 |
def _prune(self) -> None: |
| 285 |
# In principle, it's possible for a cancel scope to toggle back and |
| 286 |
# forth repeatedly between the same two deadlines, and end up with |
| 287 |
# lots of stale entries that *look* like they're still active, because |
| 288 |
# their deadline is correct, but in fact are redundant. So when |
| 289 |
# pruning we have to eliminate entries with the wrong deadline, *and* |
| 290 |
# eliminate duplicates. |
| 291 |
seen = set() |
| 292 |
pruned_heap = [] |
| 293 |
for deadline, tiebreaker, cancel_scope in self._heap: |
| 294 |
if deadline == cancel_scope._registered_deadline: |
| 295 |
if cancel_scope in seen: |
| 296 |
continue |
| 297 |
seen.add(cancel_scope) |
| 298 |
pruned_heap.append((deadline, tiebreaker, cancel_scope)) |
| 299 |
# See test_cancel_scope_deadline_duplicates for a test that exercises |
| 300 |
# this assert: |
| 301 |
assert len(pruned_heap) == self._active |
| 302 |
heapify(pruned_heap) |
| 303 |
self._heap = pruned_heap |
| 304 |
|
| 305 |
def expire(self, now: float) -> bool: |
| 306 |
did_something = False |
| 307 |
while self._heap and self._heap[0][0] <= now: |
| 308 |
deadline, _, cancel_scope = heappop(self._heap) |
| 309 |
if deadline == cancel_scope._registered_deadline: |
| 310 |
did_something = True |
| 311 |
# This implicitly calls self.remove(), so we don't need to |
| 312 |
# decrement _active here |
| 313 |
cancel_scope._cancel(CancelReason(source="deadline")) |
| 314 |
# If we've accumulated too many stale entries, then prune the heap to |
| 315 |
# keep it under control. (We only do this occasionally in a batch, to |
| 316 |
# keep the amortized cost down) |
| 317 |
if len(self._heap) > self._active * 2 + DEADLINE_HEAP_MIN_PRUNE_THRESHOLD: |
| 318 |
self._prune() |
| 319 |
return did_something |
| 320 |
|
| 321 |
|
| 322 |
@attrs.define |
| 323 |
class CancelReason: |
| 324 |
"""Attached to a :class:`CancelScope` upon cancellation with details of the source of the |
| 325 |
cancellation, which is then used to construct the string in a :exc:`Cancelled`. |
| 326 |
Users can pass a ``reason`` str to :meth:`CancelScope.cancel` to set it. |
| 327 |
|
| 328 |
Not publicly exported or documented. |
| 329 |
""" |
| 330 |
|
| 331 |
source: CancelReasonLiteral |
| 332 |
source_task: str | None = None |
| 333 |
reason: str | None = None |
| 334 |
|
| 335 |
|
| 336 |
@attrs.define(eq=False) |
| 337 |
class CancelStatus: |
| 338 |
"""Tracks the cancellation status for a contiguous extent |
| 339 |
of code that will become cancelled, or not, as a unit. |
| 340 |
|
| 341 |
Each task has at all times a single "active" CancelStatus whose |
| 342 |
cancellation state determines whether checkpoints executed in that |
| 343 |
task raise Cancelled. Each 'with CancelScope(...)' context is |
| 344 |
associated with a particular CancelStatus. When a task enters |
| 345 |
such a context, a CancelStatus is created which becomes the active |
| 346 |
CancelStatus for that task; when the 'with' block is exited, the |
| 347 |
active CancelStatus for that task goes back to whatever it was |
| 348 |
before. |
| 349 |
|
| 350 |
CancelStatus objects are arranged in a tree whose structure |
| 351 |
mirrors the lexical nesting of the cancel scope contexts. When a |
| 352 |
CancelStatus becomes cancelled, it notifies all of its direct |
| 353 |
children, who become cancelled in turn (and continue propagating |
| 354 |
the cancellation down the tree) unless they are shielded. (There |
| 355 |
will be at most one such child except in the case of a |
| 356 |
CancelStatus that immediately encloses a nursery.) At the leaves |
| 357 |
of this tree are the tasks themselves, which get woken up to deliver |
| 358 |
an abort when their direct parent CancelStatus becomes cancelled. |
| 359 |
|
| 360 |
You can think of CancelStatus as being responsible for the |
| 361 |
"plumbing" of cancellations as opposed to CancelScope which is |
| 362 |
responsible for the origination of them. |
| 363 |
|
| 364 |
""" |
| 365 |
|
| 366 |
# Our associated cancel scope. Can be any object with attributes |
| 367 |
# `deadline`, `shield`, and `cancel_called`, but in current usage |
| 368 |
# is always a CancelScope object. Must not be None. |
| 369 |
_scope: CancelScope = attrs.field(alias="scope") |
| 370 |
|
| 371 |
# True iff the tasks in self._tasks should receive cancellations |
| 372 |
# when they checkpoint. Always True when scope.cancel_called is True; |
| 373 |
# may also be True due to a cancellation propagated from our |
| 374 |
# parent. Unlike scope.cancel_called, this does not necessarily stay |
| 375 |
# true once it becomes true. For example, we might become |
| 376 |
# effectively cancelled due to the cancel scope two levels out |
| 377 |
# becoming cancelled, but then the cancel scope one level out |
| 378 |
# becomes shielded so we're not effectively cancelled anymore. |
| 379 |
effectively_cancelled: bool = False |
| 380 |
|
| 381 |
# The CancelStatus whose cancellations can propagate to us; we |
| 382 |
# become effectively cancelled when they do, unless scope.shield |
| 383 |
# is True. May be None (for the outermost CancelStatus in a call |
| 384 |
# to trio.run(), briefly during TaskStatus.started(), or during |
| 385 |
# recovery from misnesting of cancel scopes). |
| 386 |
_parent: CancelStatus | None = attrs.field(default=None, repr=False, alias="parent") |
| 387 |
|
| 388 |
# All of the CancelStatuses that have this CancelStatus as their parent. |
| 389 |
_children: set[CancelStatus] = attrs.field(factory=set, init=False, repr=False) |
| 390 |
|
| 391 |
# Tasks whose cancellation state is currently tied directly to |
| 392 |
# the cancellation state of this CancelStatus object. Don't modify |
| 393 |
# this directly; instead, use Task._activate_cancel_status(). |
| 394 |
# Invariant: all(task._cancel_status is self for task in self._tasks) |
| 395 |
_tasks: set[Task] = attrs.field(factory=set, init=False, repr=False) |
| 396 |
|
| 397 |
# Set to True on still-active cancel statuses that are children |
| 398 |
# of a cancel status that's been closed. This is used to permit |
| 399 |
# recovery from misnested cancel scopes (well, at least enough |
| 400 |
# recovery to show a useful traceback). |
| 401 |
abandoned_by_misnesting: bool = attrs.field(default=False, init=False, repr=False) |
| 402 |
|
| 403 |
def __attrs_post_init__(self) -> None: |
| 404 |
if self._parent is not None: |
| 405 |
self._parent._children.add(self) |
| 406 |
self.recalculate() |
| 407 |
|
| 408 |
# parent/children/tasks accessors are used by TaskStatus.started() |
| 409 |
|
| 410 |
@property |
| 411 |
def parent(self) -> CancelStatus | None: |
| 412 |
return self._parent |
| 413 |
|
| 414 |
@parent.setter |
| 415 |
def parent(self, parent: CancelStatus | None) -> None: |
| 416 |
if self._parent is not None: |
| 417 |
self._parent._children.remove(self) |
| 418 |
self._parent = parent |
| 419 |
if self._parent is not None: |
| 420 |
self._parent._children.add(self) |
| 421 |
self.recalculate() |
| 422 |
|
| 423 |
@property |
| 424 |
def children(self) -> frozenset[CancelStatus]: |
| 425 |
return frozenset(self._children) |
| 426 |
|
| 427 |
@property |
| 428 |
def tasks(self) -> frozenset[Task]: |
| 429 |
return frozenset(self._tasks) |
| 430 |
|
| 431 |
def encloses(self, other: CancelStatus | None) -> bool: |
| 432 |
"""Returns true if this cancel status is a direct or indirect |
| 433 |
parent of cancel status *other*, or if *other* is *self*. |
| 434 |
""" |
| 435 |
while other is not None: |
| 436 |
if other is self: |
| 437 |
return True |
| 438 |
other = other.parent |
| 439 |
return False |
| 440 |
|
| 441 |
def close(self) -> None: |
| 442 |
self.parent = None # now we're not a child of self.parent anymore |
| 443 |
if self._tasks or self._children: |
| 444 |
# Cancel scopes weren't exited in opposite order of being |
| 445 |
# entered. CancelScope._close() deals with raising an error |
| 446 |
# if appropriate; our job is to leave things in a reasonable |
| 447 |
# state for unwinding our dangling children. We choose to leave |
| 448 |
# this part of the CancelStatus tree unlinked from everyone |
| 449 |
# else, cancelled, and marked so that exiting a CancelScope |
| 450 |
# within the abandoned subtree doesn't affect the active |
| 451 |
# CancelStatus. Note that it's possible for us to get here |
| 452 |
# without CancelScope._close() raising an error, if a |
| 453 |
# nursery's cancel scope is closed within the nursery's |
| 454 |
# nested child and no other cancel scopes are involved, |
| 455 |
# but in that case task_exited() will deal with raising |
| 456 |
# the error. |
| 457 |
self._mark_abandoned() |
| 458 |
|
| 459 |
# Since our CancelScope is about to forget about us, and we |
| 460 |
# have no parent anymore, there's nothing left to call |
| 461 |
# recalculate(). So, we can stay cancelled by setting |
| 462 |
# effectively_cancelled and updating our children. |
| 463 |
self.effectively_cancelled = True |
| 464 |
for task in self._tasks: |
| 465 |
task._attempt_delivery_of_any_pending_cancel() |
| 466 |
for child in self._children: |
| 467 |
child.recalculate() |
| 468 |
|
| 469 |
@property |
| 470 |
def parent_cancellation_is_visible_to_us(self) -> bool: |
| 471 |
return ( |
| 472 |
self._parent is not None |
| 473 |
and not self._scope.shield |
| 474 |
and self._parent.effectively_cancelled |
| 475 |
) |
| 476 |
|
| 477 |
def recalculate(self) -> None: |
| 478 |
# This does a depth-first traversal over this and descendent cancel |
| 479 |
# statuses, to ensure their state is up-to-date. It's basically a |
| 480 |
# recursive algorithm, but we use an explicit stack to avoid any |
| 481 |
# issues with stack overflow. |
| 482 |
todo = [self] |
| 483 |
while todo: |
| 484 |
current = todo.pop() |
| 485 |
new_state = ( |
| 486 |
current._scope.cancel_called |
| 487 |
or current.parent_cancellation_is_visible_to_us |
| 488 |
) |
| 489 |
if new_state != current.effectively_cancelled: |
| 490 |
if ( |
| 491 |
current._scope._cancel_reason is None |
| 492 |
and current.parent_cancellation_is_visible_to_us |
| 493 |
): |
| 494 |
assert current._parent is not None |
| 495 |
current._scope._cancel_reason = ( |
| 496 |
current._parent._scope._cancel_reason |
| 497 |
) |
| 498 |
current.effectively_cancelled = new_state |
| 499 |
if new_state: |
| 500 |
for task in current._tasks: |
| 501 |
task._attempt_delivery_of_any_pending_cancel() |
| 502 |
todo.extend(current._children) |
| 503 |
|
| 504 |
def _mark_abandoned(self) -> None: |
| 505 |
self.abandoned_by_misnesting = True |
| 506 |
for child in self._children: |
| 507 |
child._mark_abandoned() |
| 508 |
|
| 509 |
def effective_deadline(self) -> float: |
| 510 |
if self.effectively_cancelled: |
| 511 |
return -inf |
| 512 |
if self._parent is None or self._scope.shield: |
| 513 |
return self._scope.deadline |
| 514 |
return min(self._scope.deadline, self._parent.effective_deadline()) |
| 515 |
|
| 516 |
|
| 517 |
MISNESTING_ADVICE = """ |
| 518 |
This is probably a bug in your code, that has caused Trio's internal state to |
| 519 |
become corrupted. We'll do our best to recover, but from now on there are |
| 520 |
no guarantees. |
| 521 |
|
| 522 |
Typically this is caused by one of the following: |
| 523 |
- yielding within a generator or async generator that's opened a cancel |
| 524 |
scope or nursery (unless the generator is a @contextmanager or |
| 525 |
@asynccontextmanager); see https://github.com/python-trio/trio/issues/638 |
| 526 |
- manually calling __enter__ or __exit__ on a trio.CancelScope, or |
| 527 |
__aenter__ or __aexit__ on the object returned by trio.open_nursery(); |
| 528 |
doing so correctly is difficult and you should use @[async]contextmanager |
| 529 |
instead, or maybe [Async]ExitStack |
| 530 |
- using [Async]ExitStack to interleave the entries/exits of cancel scopes |
| 531 |
and/or nurseries in a way that couldn't be achieved by some nesting of |
| 532 |
'with' and 'async with' blocks |
| 533 |
- using the low-level coroutine object protocol to execute some parts of |
| 534 |
an async function in a different cancel scope/nursery context than |
| 535 |
other parts |
| 536 |
If you don't believe you're doing any of these things, please file a bug: |
| 537 |
https://github.com/python-trio/trio/issues/new |
| 538 |
""" |
| 539 |
|
| 540 |
|
| 541 |
@final |
| 542 |
@attrs.define(eq=False, repr=False) |
| 543 |
class CancelScope: |
| 544 |
"""A *cancellation scope*: the link between a unit of cancellable |
| 545 |
work and Trio's cancellation system. |
| 546 |
|
| 547 |
A :class:`CancelScope` becomes associated with some cancellable work |
| 548 |
when it is used as a context manager surrounding that work:: |
| 549 |
|
| 550 |
cancel_scope = trio.CancelScope() |
| 551 |
... |
| 552 |
with cancel_scope: |
| 553 |
await long_running_operation() |
| 554 |
|
| 555 |
Inside the ``with`` block, a cancellation of ``cancel_scope`` (via |
| 556 |
a call to its :meth:`cancel` method or via the expiry of its |
| 557 |
:attr:`deadline`) will immediately interrupt the |
| 558 |
``long_running_operation()`` by raising :exc:`Cancelled` at its |
| 559 |
next :ref:`checkpoint <checkpoints>`. |
| 560 |
|
| 561 |
The context manager ``__enter__`` returns the :class:`CancelScope` |
| 562 |
object itself, so you can also write ``with trio.CancelScope() as |
| 563 |
cancel_scope:``. |
| 564 |
|
| 565 |
If a cancel scope becomes cancelled before entering its ``with`` block, |
| 566 |
the :exc:`Cancelled` exception will be raised at the first |
| 567 |
checkpoint inside the ``with`` block. This allows a |
| 568 |
:class:`CancelScope` to be created in one :ref:`task <tasks>` and |
| 569 |
passed to another, so that the first task can later cancel some work |
| 570 |
inside the second. |
| 571 |
|
| 572 |
Cancel scopes are not reusable or reentrant; that is, each cancel |
| 573 |
scope can be used for at most one ``with`` block. (You'll get a |
| 574 |
:exc:`RuntimeError` if you violate this rule.) |
| 575 |
|
| 576 |
The :class:`CancelScope` constructor takes initial values for the |
| 577 |
cancel scope's :attr:`deadline` and :attr:`shield` attributes; these |
| 578 |
may be freely modified after construction, whether or not the scope |
| 579 |
has been entered yet, and changes take immediate effect. |
| 580 |
""" |
| 581 |
|
| 582 |
_cancel_status: CancelStatus | None = attrs.field(default=None, init=False) |
| 583 |
_has_been_entered: bool = attrs.field(default=False, init=False) |
| 584 |
_registered_deadline: float = attrs.field(default=inf, init=False) |
| 585 |
_cancel_called: bool = attrs.field(default=False, init=False) |
| 586 |
cancelled_caught: bool = attrs.field(default=False, init=False) |
| 587 |
|
| 588 |
_cancel_reason: CancelReason | None = attrs.field(default=None, init=False) |
| 589 |
|
| 590 |
# Constructor arguments: |
| 591 |
_relative_deadline: float = attrs.field( |
| 592 |
default=inf, |
| 593 |
kw_only=True, |
| 594 |
alias="relative_deadline", |
| 595 |
) |
| 596 |
_deadline: float = attrs.field(default=inf, kw_only=True, alias="deadline") |
| 597 |
_shield: bool = attrs.field(default=False, kw_only=True, alias="shield") |
| 598 |
|
| 599 |
def __attrs_post_init__(self) -> None: |
| 600 |
if isnan(self._deadline): |
| 601 |
raise ValueError("deadline must not be NaN") |
| 602 |
if isnan(self._relative_deadline): |
| 603 |
raise ValueError("relative deadline must not be NaN") |
| 604 |
if self._relative_deadline < 0: |
| 605 |
raise ValueError("timeout must be non-negative") |
| 606 |
if self._relative_deadline != inf and self._deadline != inf: |
| 607 |
raise ValueError( |
| 608 |
"Cannot specify both a deadline and a relative deadline", |
| 609 |
) |
| 610 |
|
| 611 |
@enable_ki_protection |
| 612 |
def __enter__(self) -> Self: |
| 613 |
task = _core.current_task() |
| 614 |
if self._has_been_entered: |
| 615 |
raise RuntimeError( |
| 616 |
"Each CancelScope may only be used for a single 'with' block", |
| 617 |
) |
| 618 |
self._has_been_entered = True |
| 619 |
|
| 620 |
if self._relative_deadline != inf: |
| 621 |
assert self._deadline == inf |
| 622 |
self._deadline = current_time() + self._relative_deadline |
| 623 |
self._relative_deadline = inf |
| 624 |
|
| 625 |
if current_time() >= self._deadline: |
| 626 |
self._cancel(CancelReason(source="deadline")) |
| 627 |
with self._might_change_registered_deadline(): |
| 628 |
self._cancel_status = CancelStatus(scope=self, parent=task._cancel_status) |
| 629 |
task._activate_cancel_status(self._cancel_status) |
| 630 |
return self |
| 631 |
|
| 632 |
def _close(self, exc: BaseException | None) -> BaseException | None: |
| 633 |
if self._cancel_status is None: |
| 634 |
new_exc = RuntimeError( |
| 635 |
f"Cancel scope stack corrupted: attempted to exit {self!r} " |
| 636 |
"which had already been exited", |
| 637 |
) |
| 638 |
new_exc.__context__ = exc |
| 639 |
return new_exc |
| 640 |
scope_task = current_task() |
| 641 |
if scope_task._cancel_status is not self._cancel_status: |
| 642 |
# Cancel scope misnesting: this cancel scope isn't the most |
| 643 |
# recently opened by this task (that's still open). That is, |
| 644 |
# our assumptions about context managers forming a stack |
| 645 |
# have been violated. Try and make the best of it. |
| 646 |
if self._cancel_status.abandoned_by_misnesting: |
| 647 |
# We are an inner cancel scope that was still active when |
| 648 |
# some outer scope was closed. The closure of that outer |
| 649 |
# scope threw an error, so we don't need to throw another |
| 650 |
# one; it would just confuse the traceback. |
| 651 |
pass |
| 652 |
elif not self._cancel_status.encloses(scope_task._cancel_status): |
| 653 |
# This task isn't even indirectly contained within the |
| 654 |
# cancel scope it's trying to close. Raise an error |
| 655 |
# without changing any state. |
| 656 |
new_exc = RuntimeError( |
| 657 |
f"Cancel scope stack corrupted: attempted to exit {self!r} " |
| 658 |
f"from unrelated {scope_task!r}\n{MISNESTING_ADVICE}", |
| 659 |
) |
| 660 |
new_exc.__context__ = exc |
| 661 |
return new_exc |
| 662 |
else: |
| 663 |
# Otherwise, there's some inner cancel scope(s) that |
| 664 |
# we're abandoning by closing this outer one. |
| 665 |
# CancelStatus.close() will take care of the plumbing; |
| 666 |
# we just need to make sure we don't let the error |
| 667 |
# pass silently. |
| 668 |
new_exc = RuntimeError( |
| 669 |
f"Cancel scope stack corrupted: attempted to exit {self!r} " |
| 670 |
f"in {scope_task!r} that's still within its child {scope_task._cancel_status._scope!r}\n{MISNESTING_ADVICE}", |
| 671 |
) |
| 672 |
new_exc.__context__ = exc |
| 673 |
exc = new_exc |
| 674 |
scope_task._activate_cancel_status(self._cancel_status.parent) |
| 675 |
else: |
| 676 |
scope_task._activate_cancel_status(self._cancel_status.parent) |
| 677 |
if ( |
| 678 |
exc is not None |
| 679 |
and self._cancel_status.effectively_cancelled |
| 680 |
and not self._cancel_status.parent_cancellation_is_visible_to_us |
| 681 |
) or ( |
| 682 |
scope_task._cancel_status is not self._cancel_status |
| 683 |
and self._cancel_status.abandoned_by_misnesting |
| 684 |
): |
| 685 |
if isinstance(exc, Cancelled): |
| 686 |
self.cancelled_caught = True |
| 687 |
exc = None |
| 688 |
elif isinstance(exc, BaseExceptionGroup): |
| 689 |
matched, exc = exc.split(Cancelled) |
| 690 |
if matched: |
| 691 |
self.cancelled_caught = True |
| 692 |
|
| 693 |
if exc: |
| 694 |
exc = collapse_exception_group(exc) |
| 695 |
|
| 696 |
self._cancel_status.close() |
| 697 |
with self._might_change_registered_deadline(): |
| 698 |
self._cancel_status = None |
| 699 |
return exc |
| 700 |
|
| 701 |
@enable_ki_protection |
| 702 |
def __exit__( |
| 703 |
self, |
| 704 |
etype: type[BaseException] | None, |
| 705 |
exc: BaseException | None, |
| 706 |
tb: TracebackType | None, |
| 707 |
) -> bool: |
| 708 |
# NB: NurseryManager calls _close() directly rather than __exit__(), |
| 709 |
# so __exit__() must be just _close() plus this logic for adapting |
| 710 |
# the exception-filtering result to the context manager API. |
| 711 |
|
| 712 |
# Tracebacks show the 'raise' line below out of context, so let's give |
| 713 |
# this variable a name that makes sense out of context. |
| 714 |
remaining_error_after_cancel_scope = self._close(exc) |
| 715 |
if remaining_error_after_cancel_scope is None: |
| 716 |
return True |
| 717 |
elif remaining_error_after_cancel_scope is exc: |
| 718 |
return False |
| 719 |
else: |
| 720 |
# Copied verbatim from the old MultiErrorCatcher. Python doesn't |
| 721 |
# allow us to encapsulate this __context__ fixup. |
| 722 |
old_context = remaining_error_after_cancel_scope.__context__ |
| 723 |
try: |
| 724 |
raise remaining_error_after_cancel_scope |
| 725 |
finally: |
| 726 |
_, value, _ = sys.exc_info() |
| 727 |
assert value is remaining_error_after_cancel_scope |
| 728 |
value.__context__ = old_context |
| 729 |
# delete references from locals to avoid creating cycles |
| 730 |
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage |
| 731 |
# Note: still relevant |
| 732 |
del remaining_error_after_cancel_scope, value, _, exc |
| 733 |
|
| 734 |
def __repr__(self) -> str: |
| 735 |
if self._cancel_status is not None: |
| 736 |
binding = "active" |
| 737 |
elif self._has_been_entered: |
| 738 |
binding = "exited" |
| 739 |
else: |
| 740 |
binding = "unbound" |
| 741 |
|
| 742 |
if self._cancel_called: |
| 743 |
state = ", cancelled" |
| 744 |
elif self._deadline == inf: |
| 745 |
state = "" |
| 746 |
else: |
| 747 |
try: |
| 748 |
now = current_time() |
| 749 |
except RuntimeError: # must be called from async context |
| 750 |
state = "" |
| 751 |
else: |
| 752 |
state = ", deadline is {:.2f} seconds {}".format( |
| 753 |
abs(self._deadline - now), |
| 754 |
"from now" if self._deadline >= now else "ago", |
| 755 |
) |
| 756 |
|
| 757 |
return f"<trio.CancelScope at {id(self):#x}, {binding}{state}>" |
| 758 |
|
| 759 |
@contextmanager |
| 760 |
@enable_ki_protection |
| 761 |
def _might_change_registered_deadline(self) -> Iterator[None]: |
| 762 |
try: |
| 763 |
yield |
| 764 |
finally: |
| 765 |
old = self._registered_deadline |
| 766 |
if self._cancel_status is None or self._cancel_called: |
| 767 |
new = inf |
| 768 |
else: |
| 769 |
new = self._deadline |
| 770 |
if old != new: |
| 771 |
self._registered_deadline = new |
| 772 |
runner = GLOBAL_RUN_CONTEXT.runner |
| 773 |
if runner.is_guest: |
| 774 |
old_next_deadline = runner.deadlines.next_deadline() |
| 775 |
if old != inf: |
| 776 |
runner.deadlines.remove(old, self) |
| 777 |
if new != inf: |
| 778 |
runner.deadlines.add(new, self) |
| 779 |
if runner.is_guest: |
| 780 |
new_next_deadline = runner.deadlines.next_deadline() |
| 781 |
if old_next_deadline != new_next_deadline: |
| 782 |
runner.force_guest_tick_asap() |
| 783 |
|
| 784 |
@property |
| 785 |
def deadline(self) -> float: |
| 786 |
"""Read-write, :class:`float`. An absolute time on the current |
| 787 |
run's clock at which this scope will automatically become |
| 788 |
cancelled. You can adjust the deadline by modifying this |
| 789 |
attribute, e.g.:: |
| 790 |
|
| 791 |
# I need a little more time! |
| 792 |
cancel_scope.deadline += 30 |
| 793 |
|
| 794 |
Note that for efficiency, the core run loop only checks for |
| 795 |
expired deadlines every once in a while. This means that in |
| 796 |
certain cases there may be a short delay between when the clock |
| 797 |
says the deadline should have expired, and when checkpoints |
| 798 |
start raising :exc:`~trio.Cancelled`. This is a very obscure |
| 799 |
corner case that you're unlikely to notice, but we document it |
| 800 |
for completeness. (If this *does* cause problems for you, of |
| 801 |
course, then `we want to know! |
| 802 |
<https://github.com/python-trio/trio/issues>`__) |
| 803 |
|
| 804 |
Defaults to :data:`math.inf`, which means "no deadline", though |
| 805 |
this can be overridden by the ``deadline=`` argument to |
| 806 |
the :class:`~trio.CancelScope` constructor. |
| 807 |
""" |
| 808 |
if self._relative_deadline != inf: |
| 809 |
assert self._deadline == inf |
| 810 |
raise RuntimeError( |
| 811 |
"Unentered relative cancel scope does not have an absolute deadline." |
| 812 |
) |
| 813 |
return self._deadline |
| 814 |
|
| 815 |
@deadline.setter |
| 816 |
def deadline(self, new_deadline: float) -> None: |
| 817 |
if isnan(new_deadline): |
| 818 |
raise ValueError("deadline must not be NaN") |
| 819 |
if self._relative_deadline != inf: |
| 820 |
assert self._deadline == inf |
| 821 |
raise RuntimeError( |
| 822 |
"Unentered relative cancel scope does not have an absolute deadline." |
| 823 |
) |
| 824 |
with self._might_change_registered_deadline(): |
| 825 |
self._deadline = float(new_deadline) |
| 826 |
|
| 827 |
@property |
| 828 |
def relative_deadline(self) -> float: |
| 829 |
"""Read-write, :class:`float`. The number of seconds remaining until this |
| 830 |
scope's deadline, relative to the current time. |
| 831 |
|
| 832 |
Defaults to :data:`math.inf` ("no deadline"). Must be non-negative. |
| 833 |
|
| 834 |
When modified |
| 835 |
Before entering: sets the deadline relative to when the scope enters. |
| 836 |
After entering: sets a new deadline relative to the current time. |
| 837 |
|
| 838 |
Raises: |
| 839 |
RuntimeError: if trying to read or modify an unentered scope with an absolute deadline, i.e. when :attr:`is_relative` is ``False``. |
| 840 |
""" |
| 841 |
if self._has_been_entered: |
| 842 |
return self._deadline - current_time() |
| 843 |
elif self._deadline != inf: |
| 844 |
assert self._relative_deadline == inf |
| 845 |
raise RuntimeError( |
| 846 |
"Unentered non-relative cancel scope does not have a relative deadline", |
| 847 |
) |
| 848 |
return self._relative_deadline |
| 849 |
|
| 850 |
@relative_deadline.setter |
| 851 |
def relative_deadline(self, new_relative_deadline: float) -> None: |
| 852 |
if isnan(new_relative_deadline): |
| 853 |
raise ValueError("relative deadline must not be NaN") |
| 854 |
if new_relative_deadline < 0: |
| 855 |
raise ValueError("relative deadline must be non-negative") |
| 856 |
if self._has_been_entered: |
| 857 |
with self._might_change_registered_deadline(): |
| 858 |
self._deadline = current_time() + float(new_relative_deadline) |
| 859 |
elif self._deadline != inf: |
| 860 |
assert self._relative_deadline == inf |
| 861 |
raise RuntimeError( |
| 862 |
"Unentered non-relative cancel scope does not have a relative deadline", |
| 863 |
) |
| 864 |
else: |
| 865 |
self._relative_deadline = new_relative_deadline |
| 866 |
|
| 867 |
@property |
| 868 |
def is_relative(self) -> bool | None: |
| 869 |
"""Returns None after entering. Returns False if both deadline and |
| 870 |
relative_deadline are inf.""" |
| 871 |
assert not (self._deadline != inf and self._relative_deadline != inf) |
| 872 |
if self._has_been_entered: |
| 873 |
return None |
| 874 |
return self._relative_deadline != inf |
| 875 |
|
| 876 |
@property |
| 877 |
def shield(self) -> bool: |
| 878 |
"""Read-write, :class:`bool`, default :data:`False`. So long as |
| 879 |
this is set to :data:`True`, then the code inside this scope |
| 880 |
will not receive :exc:`~trio.Cancelled` exceptions from scopes |
| 881 |
that are outside this scope. They can still receive |
| 882 |
:exc:`~trio.Cancelled` exceptions from (1) this scope, or (2) |
| 883 |
scopes inside this scope. You can modify this attribute:: |
| 884 |
|
| 885 |
with trio.CancelScope() as cancel_scope: |
| 886 |
cancel_scope.shield = True |
| 887 |
# This cannot be interrupted by any means short of |
| 888 |
# killing the process: |
| 889 |
await sleep(10) |
| 890 |
|
| 891 |
cancel_scope.shield = False |
| 892 |
# Now this can be cancelled normally: |
| 893 |
await sleep(10) |
| 894 |
|
| 895 |
Defaults to :data:`False`, though this can be overridden by the |
| 896 |
``shield=`` argument to the :class:`~trio.CancelScope` constructor. |
| 897 |
""" |
| 898 |
return self._shield |
| 899 |
|
| 900 |
@shield.setter |
| 901 |
@enable_ki_protection |
| 902 |
def shield(self, new_value: bool) -> None: |
| 903 |
if not isinstance(new_value, bool): |
| 904 |
raise TypeError("shield must be a bool") |
| 905 |
self._shield = new_value |
| 906 |
if self._cancel_status is not None: |
| 907 |
self._cancel_status.recalculate() |
| 908 |
|
| 909 |
@enable_ki_protection |
| 910 |
def _cancel(self, cancel_reason: CancelReason | None) -> None: |
| 911 |
"""Internal sources of cancellation should use this instead of :meth:`cancel` |
| 912 |
in order to set a more detailed :class:`CancelReason` |
| 913 |
Helper or high-level functions can use `cancel`. |
| 914 |
""" |
| 915 |
if self._cancel_called: |
| 916 |
return |
| 917 |
|
| 918 |
if self._cancel_reason is None: |
| 919 |
self._cancel_reason = cancel_reason |
| 920 |
|
| 921 |
with self._might_change_registered_deadline(): |
| 922 |
self._cancel_called = True |
| 923 |
|
| 924 |
if self._cancel_status is not None: |
| 925 |
self._cancel_status.recalculate() |
| 926 |
|
| 927 |
@enable_ki_protection |
| 928 |
def cancel(self, reason: str | None = None) -> None: |
| 929 |
"""Cancels this scope immediately. |
| 930 |
|
| 931 |
The optional ``reason`` argument accepts a string, which will be attached to |
| 932 |
any resulting :exc:`Cancelled` exception to help you understand where that |
| 933 |
cancellation is coming from and why it happened. |
| 934 |
|
| 935 |
This method is idempotent, i.e., if the scope was already |
| 936 |
cancelled then this method silently does nothing. |
| 937 |
""" |
| 938 |
try: |
| 939 |
current_task = repr(_core.current_task()) |
| 940 |
except RuntimeError: |
| 941 |
current_task = None |
| 942 |
self._cancel( |
| 943 |
CancelReason(reason=reason, source="explicit", source_task=current_task) |
| 944 |
) |
| 945 |
|
| 946 |
@property |
| 947 |
def cancel_called(self) -> bool: |
| 948 |
"""Readonly :class:`bool`. Records whether cancellation has been |
| 949 |
requested for this scope, either by an explicit call to |
| 950 |
:meth:`cancel` or by the deadline expiring. |
| 951 |
|
| 952 |
This attribute being True does *not* necessarily mean that the |
| 953 |
code within the scope has been, or will be, affected by the |
| 954 |
cancellation. For example, if :meth:`cancel` was called after |
| 955 |
the last checkpoint in the ``with`` block, when it's too late to |
| 956 |
deliver a :exc:`~trio.Cancelled` exception, then this attribute |
| 957 |
will still be True. |
| 958 |
|
| 959 |
This attribute is mostly useful for debugging and introspection. |
| 960 |
If you want to know whether or not a chunk of code was actually |
| 961 |
cancelled, then :attr:`cancelled_caught` is usually more |
| 962 |
appropriate. |
| 963 |
""" |
| 964 |
if ( # noqa: SIM102 # collapsible-if but this way is nicer |
| 965 |
self._cancel_status is not None or not self._has_been_entered |
| 966 |
): |
| 967 |
# Scope is active or not yet entered: make sure cancel_called |
| 968 |
# is true if the deadline has passed. This shouldn't |
| 969 |
# be able to actually change behavior, since we check for |
| 970 |
# deadline expiry on scope entry and at every checkpoint, |
| 971 |
# but it makes the value returned by cancel_called more |
| 972 |
# closely match expectations. |
| 973 |
if not self._cancel_called and current_time() >= self._deadline: |
| 974 |
self._cancel(CancelReason(source="deadline")) |
| 975 |
return self._cancel_called |
| 976 |
|
| 977 |
|
| 978 |
################################################################ |
| 979 |
# Nursery and friends |
| 980 |
################################################################ |
| 981 |
|
| 982 |
|
| 983 |
class TaskStatus(Protocol[StatusT_contra]): |
| 984 |
"""The interface provided by :meth:`Nursery.start()` to the spawned task. |
| 985 |
|
| 986 |
This is provided via the ``task_status`` keyword-only parameter. |
| 987 |
""" |
| 988 |
|
| 989 |
@overload |
| 990 |
def started(self: TaskStatus[None]) -> None: ... |
| 991 |
|
| 992 |
@overload |
| 993 |
def started(self, value: StatusT_contra) -> None: ... |
| 994 |
|
| 995 |
def started(self, value: StatusT_contra | None = None) -> None: |
| 996 |
"""Tasks call this method to indicate that they have initialized. |
| 997 |
|
| 998 |
See `nursery.start() <trio.Nursery.start>` for more information. |
| 999 |
""" |
| 1000 |
|
| 1001 |
|
| 1002 |
# This code needs to be read alongside the code from Nursery.start to make |
| 1003 |
# sense. |
| 1004 |
@attrs.define(eq=False, repr=False, slots=False) |
| 1005 |
class _TaskStatus(TaskStatus[StatusT]): |
| 1006 |
_old_nursery: Nursery |
| 1007 |
_new_nursery: Nursery |
| 1008 |
# NoStatus is a sentinel. |
| 1009 |
_value: StatusT | type[_NoStatus] = _NoStatus |
| 1010 |
|
| 1011 |
def __repr__(self) -> str: |
| 1012 |
return f"<Task status object at {id(self):#x}>" |
| 1013 |
|
| 1014 |
@overload |
| 1015 |
def started(self: _TaskStatus[None]) -> None: ... |
| 1016 |
|
| 1017 |
@overload |
| 1018 |
def started(self: _TaskStatus[StatusT], value: StatusT) -> None: ... |
| 1019 |
|
| 1020 |
def started(self, value: StatusT | None = None) -> None: |
| 1021 |
if self._value is not _NoStatus: |
| 1022 |
raise RuntimeError("called 'started' twice on the same task status") |
| 1023 |
self._value = cast("StatusT", value) # If None, StatusT == None |
| 1024 |
|
| 1025 |
# If the old nursery is cancelled, then quietly quit now; the child |
| 1026 |
# will eventually exit on its own, and we don't want to risk moving |
| 1027 |
# children that might have propagating Cancelled exceptions into |
| 1028 |
# a place with no cancelled cancel scopes to catch them. |
| 1029 |
assert self._old_nursery._cancel_status is not None |
| 1030 |
if self._old_nursery._cancel_status.effectively_cancelled: |
| 1031 |
return |
| 1032 |
|
| 1033 |
# Can't be closed, b/c we checked in start() and then _pending_starts |
| 1034 |
# should keep it open. |
| 1035 |
assert not self._new_nursery._closed |
| 1036 |
|
| 1037 |
# Move tasks from the old nursery to the new |
| 1038 |
tasks = self._old_nursery._children |
| 1039 |
self._old_nursery._children = set() |
| 1040 |
for task in tasks: |
| 1041 |
task._parent_nursery = self._new_nursery |
| 1042 |
task._eventual_parent_nursery = None |
| 1043 |
self._new_nursery._children.add(task) |
| 1044 |
|
| 1045 |
# Move all children of the old nursery's cancel status object |
| 1046 |
# to be underneath the new nursery instead. This includes both |
| 1047 |
# tasks and child cancel status objects. |
| 1048 |
# NB: If the new nursery is cancelled, reparenting a cancel |
| 1049 |
# status to be underneath it can invoke an abort_fn, which might |
| 1050 |
# do something evil like cancel the old nursery. We thus break |
| 1051 |
# everything off from the old nursery before we start attaching |
| 1052 |
# anything to the new. |
| 1053 |
cancel_status_children = self._old_nursery._cancel_status.children |
| 1054 |
cancel_status_tasks = set(self._old_nursery._cancel_status.tasks) |
| 1055 |
cancel_status_tasks.discard(self._old_nursery._parent_task) |
| 1056 |
for cancel_status in cancel_status_children: |
| 1057 |
cancel_status.parent = None |
| 1058 |
for task in cancel_status_tasks: |
| 1059 |
task._activate_cancel_status(None) |
| 1060 |
for cancel_status in cancel_status_children: |
| 1061 |
cancel_status.parent = self._new_nursery._cancel_status |
| 1062 |
for task in cancel_status_tasks: |
| 1063 |
task._activate_cancel_status(self._new_nursery._cancel_status) |
| 1064 |
|
| 1065 |
# That should have removed all the children from the old nursery |
| 1066 |
assert not self._old_nursery._children |
| 1067 |
|
| 1068 |
# And finally, poke the old nursery so it notices that all its |
| 1069 |
# children have disappeared and can exit. |
| 1070 |
self._old_nursery._check_nursery_closed() |
| 1071 |
|
| 1072 |
|
| 1073 |
@attrs.define(slots=False) |
| 1074 |
class NurseryManager: |
| 1075 |
"""Nursery context manager. |
| 1076 |
|
| 1077 |
Note we explicitly avoid @asynccontextmanager and @async_generator |
| 1078 |
since they add a lot of extraneous stack frames to exceptions, as |
| 1079 |
well as cause problematic behavior with handling of StopIteration |
| 1080 |
and StopAsyncIteration. |
| 1081 |
|
| 1082 |
""" |
| 1083 |
|
| 1084 |
strict_exception_groups: bool = True |
| 1085 |
|
| 1086 |
@enable_ki_protection |
| 1087 |
async def __aenter__(self) -> Nursery: |
| 1088 |
self._scope = CancelScope() |
| 1089 |
self._scope.__enter__() |
| 1090 |
self._nursery = Nursery._create( |
| 1091 |
current_task(), |
| 1092 |
self._scope, |
| 1093 |
self.strict_exception_groups, |
| 1094 |
) |
| 1095 |
return self._nursery |
| 1096 |
|
| 1097 |
@enable_ki_protection |
| 1098 |
async def __aexit__( |
| 1099 |
self, |
| 1100 |
etype: type[BaseException] | None, |
| 1101 |
exc: BaseException | None, |
| 1102 |
tb: TracebackType | None, |
| 1103 |
) -> bool: |
| 1104 |
new_exc = await self._nursery._nested_child_finished(exc) |
| 1105 |
# Tracebacks show the 'raise' line below out of context, so let's give |
| 1106 |
# this variable a name that makes sense out of context. |
| 1107 |
combined_error_from_nursery = self._scope._close(new_exc) |
| 1108 |
if combined_error_from_nursery is None: |
| 1109 |
return True |
| 1110 |
elif combined_error_from_nursery is exc: |
| 1111 |
return False |
| 1112 |
else: |
| 1113 |
# Copied verbatim from the old MultiErrorCatcher. Python doesn't |
| 1114 |
# allow us to encapsulate this __context__ fixup. |
| 1115 |
old_context = combined_error_from_nursery.__context__ |
| 1116 |
try: |
| 1117 |
raise combined_error_from_nursery |
| 1118 |
finally: |
| 1119 |
_, value, _ = sys.exc_info() |
| 1120 |
assert value is combined_error_from_nursery |
| 1121 |
value.__context__ = old_context |
| 1122 |
# delete references from locals to avoid creating cycles |
| 1123 |
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage |
| 1124 |
del _, combined_error_from_nursery, value, new_exc |
| 1125 |
|
| 1126 |
# make sure these raise errors in static analysis if called |
| 1127 |
if not TYPE_CHECKING: |
| 1128 |
|
| 1129 |
def __enter__(self) -> NoReturn: |
| 1130 |
raise RuntimeError( |
| 1131 |
"use 'async with open_nursery(...)', not 'with open_nursery(...)'", |
| 1132 |
) |
| 1133 |
|
| 1134 |
def __exit__( |
| 1135 |
self, |
| 1136 |
exc_type: type[BaseException] | None, |
| 1137 |
exc_value: BaseException | None, |
| 1138 |
traceback: TracebackType | None, |
| 1139 |
) -> NoReturn: # pragma: no cover |
| 1140 |
raise AssertionError("Never called, but should be defined") |
| 1141 |
|
| 1142 |
|
| 1143 |
def open_nursery( |
| 1144 |
strict_exception_groups: bool | None = None, |
| 1145 |
) -> AbstractAsyncContextManager[Nursery]: |
| 1146 |
"""Returns an async context manager which must be used to create a |
| 1147 |
new `Nursery`. |
| 1148 |
|
| 1149 |
It does not block on entry; on exit it blocks until all child tasks |
| 1150 |
have exited. If no child tasks are running on exit, it will insert a |
| 1151 |
schedule point (but no cancellation point) - equivalent to |
| 1152 |
:func:`trio.lowlevel.cancel_shielded_checkpoint`. This means a nursery |
| 1153 |
is never the source of a cancellation exception, it only propagates it |
| 1154 |
from sub-tasks. |
| 1155 |
|
| 1156 |
Args: |
| 1157 |
strict_exception_groups (bool): Unless set to False, even a single raised exception |
| 1158 |
will be wrapped in an exception group. If not specified, uses the value passed |
| 1159 |
to :func:`run`, which defaults to true. Setting it to False will be deprecated |
| 1160 |
and ultimately removed in a future version of Trio. |
| 1161 |
|
| 1162 |
""" |
| 1163 |
# only warn if explicitly set to falsy, not if we get it from the global context. |
| 1164 |
if strict_exception_groups is not None and not strict_exception_groups: |
| 1165 |
warn_deprecated( |
| 1166 |
"open_nursery(strict_exception_groups=False)", |
| 1167 |
version="0.25.0", |
| 1168 |
issue=2929, |
| 1169 |
instead=( |
| 1170 |
"the default value of True and rewrite exception handlers to handle ExceptionGroups. " |
| 1171 |
"See https://trio.readthedocs.io/en/stable/reference-core.html#designing-for-multiple-errors" |
| 1172 |
), |
| 1173 |
use_triodeprecationwarning=True, |
| 1174 |
) |
| 1175 |
|
| 1176 |
if strict_exception_groups is None: |
| 1177 |
strict_exception_groups = GLOBAL_RUN_CONTEXT.runner.strict_exception_groups |
| 1178 |
|
| 1179 |
return NurseryManager(strict_exception_groups=strict_exception_groups) |
| 1180 |
|
| 1181 |
|
| 1182 |
@final |
| 1183 |
class Nursery(metaclass=NoPublicConstructor): |
| 1184 |
"""A context which may be used to spawn (or cancel) child tasks. |
| 1185 |
|
| 1186 |
Not constructed directly, use `open_nursery` instead. |
| 1187 |
|
| 1188 |
The nursery will remain open until all child tasks have completed, |
| 1189 |
or until it is cancelled, at which point it will cancel all its |
| 1190 |
remaining child tasks and close. |
| 1191 |
|
| 1192 |
Nurseries ensure the absence of orphaned Tasks, since all running |
| 1193 |
tasks will belong to an open Nursery. |
| 1194 |
|
| 1195 |
Attributes: |
| 1196 |
cancel_scope: |
| 1197 |
Creating a nursery also implicitly creates a cancellation scope, |
| 1198 |
which is exposed as the :attr:`cancel_scope` attribute. This is |
| 1199 |
used internally to implement the logic where if an error occurs |
| 1200 |
then ``__aexit__`` cancels all children, but you can use it for |
| 1201 |
other things, e.g. if you want to explicitly cancel all children |
| 1202 |
in response to some external event. |
| 1203 |
""" |
| 1204 |
|
| 1205 |
def __init__( |
| 1206 |
self, |
| 1207 |
parent_task: Task, |
| 1208 |
cancel_scope: CancelScope, |
| 1209 |
strict_exception_groups: bool, |
| 1210 |
) -> None: |
| 1211 |
self._parent_task = parent_task |
| 1212 |
self._strict_exception_groups = strict_exception_groups |
| 1213 |
parent_task._child_nurseries.append(self) |
| 1214 |
# the cancel status that children inherit - we take a snapshot, so it |
| 1215 |
# won't be affected by any changes in the parent. |
| 1216 |
self._cancel_status = parent_task._cancel_status |
| 1217 |
# the cancel scope that directly surrounds us; used for cancelling all |
| 1218 |
# children. |
| 1219 |
self.cancel_scope = cancel_scope |
| 1220 |
assert self.cancel_scope._cancel_status is self._cancel_status |
| 1221 |
self._children: set[Task] = set() |
| 1222 |
self._pending_excs: list[BaseException] = [] |
| 1223 |
# The "nested child" is how this code refers to the contents of the |
| 1224 |
# nursery's 'async with' block, which acts like a child Task in all |
| 1225 |
# the ways we can make it. |
| 1226 |
self._nested_child_running = True |
| 1227 |
self._parent_waiting_in_aexit = False |
| 1228 |
self._pending_starts = 0 |
| 1229 |
self._closed = False |
| 1230 |
|
| 1231 |
@property |
| 1232 |
def child_tasks(self) -> frozenset[Task]: |
| 1233 |
"""(`frozenset`): Contains all the child :class:`~trio.lowlevel.Task` |
| 1234 |
objects which are still running.""" |
| 1235 |
return frozenset(self._children) |
| 1236 |
|
| 1237 |
@property |
| 1238 |
def parent_task(self) -> Task: |
| 1239 |
"(`~trio.lowlevel.Task`): The Task that opened this nursery." |
| 1240 |
return self._parent_task |
| 1241 |
|
| 1242 |
def _add_exc(self, exc: BaseException, reason: CancelReason | None) -> None: |
| 1243 |
self._pending_excs.append(exc) |
| 1244 |
self.cancel_scope._cancel(reason) |
| 1245 |
|
| 1246 |
def _check_nursery_closed(self) -> None: |
| 1247 |
if not any([self._nested_child_running, self._children, self._pending_starts]): |
| 1248 |
self._closed = True |
| 1249 |
if self._parent_waiting_in_aexit: |
| 1250 |
self._parent_waiting_in_aexit = False |
| 1251 |
GLOBAL_RUN_CONTEXT.runner.reschedule(self._parent_task) |
| 1252 |
|
| 1253 |
def _child_finished( |
| 1254 |
self, |
| 1255 |
task: Task, |
| 1256 |
outcome: Outcome[object], |
| 1257 |
) -> None: |
| 1258 |
self._children.remove(task) |
| 1259 |
if self._closed and not hasattr(self, "_pending_excs"): |
| 1260 |
# We're abandoned by misnested nurseries, the result of the task is lost. |
| 1261 |
return |
| 1262 |
if isinstance(outcome, Error): |
| 1263 |
self._add_exc( |
| 1264 |
outcome.error, |
| 1265 |
CancelReason( |
| 1266 |
source="nursery", |
| 1267 |
source_task=repr(task), |
| 1268 |
reason=f"child task raised exception {outcome.error!r}", |
| 1269 |
), |
| 1270 |
) |
| 1271 |
self._check_nursery_closed() |
| 1272 |
|
| 1273 |
async def _nested_child_finished( |
| 1274 |
self, |
| 1275 |
nested_child_exc: BaseException | None, |
| 1276 |
) -> BaseException | None: |
| 1277 |
# Returns ExceptionGroup instance (or any exception if the nursery is in loose mode |
| 1278 |
# and there is just one contained exception) if there are pending exceptions |
| 1279 |
if nested_child_exc is not None: |
| 1280 |
self._add_exc( |
| 1281 |
nested_child_exc, |
| 1282 |
reason=CancelReason( |
| 1283 |
source="nursery", |
| 1284 |
source_task=repr(self._parent_task), |
| 1285 |
reason=f"Code block inside nursery contextmanager raised exception {nested_child_exc!r}", |
| 1286 |
), |
| 1287 |
) |
| 1288 |
self._nested_child_running = False |
| 1289 |
self._check_nursery_closed() |
| 1290 |
|
| 1291 |
if not self._closed: |
| 1292 |
# If we have a KeyboardInterrupt injected, we want to save it in |
| 1293 |
# the nursery's final exceptions list. But if it's just a |
| 1294 |
# Cancelled, then we don't -- see gh-1457. |
| 1295 |
def aborted(raise_cancel: _core.RaiseCancelT) -> Abort: |
| 1296 |
exn = capture(raise_cancel).error |
| 1297 |
if not isinstance(exn, Cancelled): |
| 1298 |
self._add_exc( |
| 1299 |
exn, |
| 1300 |
CancelReason( |
| 1301 |
source="KeyboardInterrupt", |
| 1302 |
source_task=repr(self._parent_task), |
| 1303 |
), |
| 1304 |
) |
| 1305 |
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage |
| 1306 |
del exn # prevent cyclic garbage creation |
| 1307 |
return Abort.FAILED |
| 1308 |
|
| 1309 |
self._parent_waiting_in_aexit = True |
| 1310 |
await wait_task_rescheduled(aborted) |
| 1311 |
else: |
| 1312 |
# Nothing to wait for, so execute a schedule point, but don't |
| 1313 |
# allow us to be cancelled, just like the other branch. We |
| 1314 |
# still need to catch and store non-Cancelled exceptions. |
| 1315 |
try: |
| 1316 |
await cancel_shielded_checkpoint() |
| 1317 |
except BaseException as exc: |
| 1318 |
# there's no children to cancel, so don't need to supply cancel reason |
| 1319 |
self._add_exc(exc, reason=None) |
| 1320 |
|
| 1321 |
popped = self._parent_task._child_nurseries.pop() |
| 1322 |
assert popped is self, "Nursery misnesting detected!" |
| 1323 |
if self._pending_excs: |
| 1324 |
try: |
| 1325 |
if not self._strict_exception_groups and len(self._pending_excs) == 1: |
| 1326 |
return self._pending_excs[0] |
| 1327 |
exception = BaseExceptionGroup( |
| 1328 |
"Exceptions from Trio nursery", |
| 1329 |
self._pending_excs, |
| 1330 |
) |
| 1331 |
if not self._strict_exception_groups: |
| 1332 |
exception.add_note(NONSTRICT_EXCEPTIONGROUP_NOTE) |
| 1333 |
return exception |
| 1334 |
finally: |
| 1335 |
# avoid a garbage cycle |
| 1336 |
# (see test_locals_destroyed_promptly_on_cancel) |
| 1337 |
del self._pending_excs |
| 1338 |
return None |
| 1339 |
|
| 1340 |
def start_soon( |
| 1341 |
self, |
| 1342 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], |
| 1343 |
*args: Unpack[PosArgT], |
| 1344 |
name: object = None, |
| 1345 |
) -> None: |
| 1346 |
"""Creates a child task, scheduling ``await async_fn(*args)``. |
| 1347 |
|
| 1348 |
If you want to run a function and immediately wait for its result, |
| 1349 |
then you don't need a nursery; just use ``await async_fn(*args)``. |
| 1350 |
If you want to wait for the task to initialize itself before |
| 1351 |
continuing, see :meth:`start`, the other fundamental method for |
| 1352 |
creating concurrent tasks in Trio. |
| 1353 |
|
| 1354 |
Note that this is *not* an async function and you don't use await |
| 1355 |
when calling it. It sets up the new task, but then returns |
| 1356 |
immediately, *before* the new task has a chance to do anything. |
| 1357 |
New tasks may start running in any order, and at any checkpoint the |
| 1358 |
scheduler chooses - at latest when the nursery is waiting to exit. |
| 1359 |
|
| 1360 |
It's possible to pass a nursery object into another task, which |
| 1361 |
allows that task to start new child tasks in the first task's |
| 1362 |
nursery. |
| 1363 |
|
| 1364 |
The child task inherits its parent nursery's cancel scopes. |
| 1365 |
|
| 1366 |
Args: |
| 1367 |
async_fn: An async callable. |
| 1368 |
args: Positional arguments for ``async_fn``. If you want |
| 1369 |
to pass keyword arguments, use |
| 1370 |
:func:`functools.partial`. |
| 1371 |
name: The name for this task. Only used for |
| 1372 |
debugging/introspection |
| 1373 |
(e.g. ``repr(task_obj)``). If this isn't a string, |
| 1374 |
:meth:`start_soon` will try to make it one. A |
| 1375 |
common use case is if you're wrapping a function |
| 1376 |
before spawning a new task, you might pass the |
| 1377 |
original function as the ``name=`` to make |
| 1378 |
debugging easier. |
| 1379 |
|
| 1380 |
Raises: |
| 1381 |
RuntimeError: If this nursery is no longer open |
| 1382 |
(i.e. its ``async with`` block has |
| 1383 |
exited). |
| 1384 |
""" |
| 1385 |
GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name) |
| 1386 |
|
| 1387 |
# Typing changes blocked by https://github.com/python/mypy/pull/17512 |
| 1388 |
async def start( # type: ignore[explicit-any] |
| 1389 |
self, |
| 1390 |
async_fn: Callable[..., Awaitable[object]], |
| 1391 |
*args: object, |
| 1392 |
name: object = None, |
| 1393 |
) -> Any: |
| 1394 |
r"""Creates and initializes a child task. |
| 1395 |
|
| 1396 |
Like :meth:`start_soon`, but blocks until the new task has |
| 1397 |
finished initializing itself, and optionally returns some |
| 1398 |
information from it. |
| 1399 |
|
| 1400 |
The ``async_fn`` must accept a ``task_status`` keyword argument, |
| 1401 |
and it must make sure that it (or someone) eventually calls |
| 1402 |
:meth:`task_status.started() <TaskStatus.started>`. |
| 1403 |
|
| 1404 |
The conventional way to define ``async_fn`` is like:: |
| 1405 |
|
| 1406 |
async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED): |
| 1407 |
... # Caller is blocked waiting for this code to run |
| 1408 |
task_status.started() |
| 1409 |
... # This async code can be interleaved with the caller |
| 1410 |
|
| 1411 |
:attr:`trio.TASK_STATUS_IGNORED` is a special global object with |
| 1412 |
a do-nothing ``started`` method. This way your function supports |
| 1413 |
being called either like ``await nursery.start(async_fn, arg1, |
| 1414 |
arg2)`` or directly like ``await async_fn(arg1, arg2)``, and |
| 1415 |
either way it can call :meth:`task_status.started() <TaskStatus.started>` |
| 1416 |
without worrying about which mode it's in. Defining your function like |
| 1417 |
this will make it obvious to readers that it supports being used |
| 1418 |
in both modes. |
| 1419 |
|
| 1420 |
Before the child calls :meth:`task_status.started() <TaskStatus.started>`, |
| 1421 |
it's effectively run underneath the call to :meth:`start`: if it |
| 1422 |
raises an exception then that exception is reported by |
| 1423 |
:meth:`start`, and does *not* propagate out of the nursery. If |
| 1424 |
:meth:`start` is cancelled, then the child task is also |
| 1425 |
cancelled. |
| 1426 |
|
| 1427 |
When the child calls :meth:`task_status.started() <TaskStatus.started>`, |
| 1428 |
it's moved out from underneath :meth:`start` and into the given nursery. |
| 1429 |
|
| 1430 |
If the child task passes a value to :meth:`task_status.started(value) <TaskStatus.started>`, |
| 1431 |
then :meth:`start` returns this value. Otherwise, it returns ``None``. |
| 1432 |
""" |
| 1433 |
if self._closed: |
| 1434 |
raise RuntimeError("Nursery is closed to new arrivals") |
| 1435 |
try: |
| 1436 |
self._pending_starts += 1 |
| 1437 |
# wrap internal nursery in try-except to unroll any exceptiongroups |
| 1438 |
# to avoid wrapping pre-started() exceptions in an extra ExceptionGroup. |
| 1439 |
# See #2611. |
| 1440 |
try: |
| 1441 |
# set strict_exception_groups = True to make sure we always unwrap |
| 1442 |
# *this* nursery's exceptiongroup |
| 1443 |
async with open_nursery(strict_exception_groups=True) as old_nursery: |
| 1444 |
task_status: _TaskStatus[object | None] = _TaskStatus( |
| 1445 |
old_nursery, |
| 1446 |
self, |
| 1447 |
) |
| 1448 |
thunk = functools.partial(async_fn, task_status=task_status) |
| 1449 |
task = GLOBAL_RUN_CONTEXT.runner.spawn_impl( |
| 1450 |
thunk, |
| 1451 |
args, |
| 1452 |
old_nursery, |
| 1453 |
name, |
| 1454 |
) |
| 1455 |
task._eventual_parent_nursery = self |
| 1456 |
# Wait for either TaskStatus.started or an exception to |
| 1457 |
# cancel this nursery: |
| 1458 |
except BaseExceptionGroup as exc: |
| 1459 |
if len(exc.exceptions) == 1: |
| 1460 |
raise_saving_context(exc.exceptions[0]) |
| 1461 |
raise TrioInternalError( |
| 1462 |
"Internal nursery should not have multiple tasks. This can be " |
| 1463 |
'caused by the user managing to access the "old" nursery in ' |
| 1464 |
"`task_status` and spawning tasks in it.", |
| 1465 |
) from exc |
| 1466 |
|
| 1467 |
# If we get here, then the child either got reparented or exited |
| 1468 |
# normally. The complicated logic is all in TaskStatus.started(). |
| 1469 |
# (Any exceptions propagate directly out of the above.) |
| 1470 |
if task_status._value is _NoStatus: |
| 1471 |
raise RuntimeError("child exited without calling task_status.started()") |
| 1472 |
return task_status._value |
| 1473 |
finally: |
| 1474 |
self._pending_starts -= 1 |
| 1475 |
self._check_nursery_closed() |
| 1476 |
|
| 1477 |
def __del__(self) -> None: |
| 1478 |
assert not self._children |
| 1479 |
|
| 1480 |
|
| 1481 |
################################################################ |
| 1482 |
# Task and friends |
| 1483 |
################################################################ |
| 1484 |
|
| 1485 |
|
| 1486 |
@final |
| 1487 |
@attrs.define(eq=False, repr=False) |
| 1488 |
class Task(metaclass=NoPublicConstructor): # type: ignore[explicit-any] |
| 1489 |
_parent_nursery: Nursery | None |
| 1490 |
coro: types.CoroutineType[Any, Outcome[object], Any] # type: ignore[explicit-any] |
| 1491 |
_runner: Runner |
| 1492 |
name: str |
| 1493 |
context: contextvars.Context |
| 1494 |
_counter: int = attrs.field(init=False, factory=itertools.count().__next__) |
| 1495 |
_ki_protected: bool |
| 1496 |
|
| 1497 |
# Invariant: |
| 1498 |
# - for unscheduled tasks, _next_send_fn and _next_send are both None |
| 1499 |
# - for scheduled tasks, _next_send_fn(_next_send) resumes the task; |
| 1500 |
# usually _next_send_fn is self.coro.send and _next_send is an |
| 1501 |
# Outcome. When recovering from a foreign await, _next_send_fn is |
| 1502 |
# self.coro.throw and _next_send is an exception. _next_send_fn |
| 1503 |
# will effectively be at the top of every task's call stack, so |
| 1504 |
# it should be written in C if you don't want to pollute Trio |
| 1505 |
# tracebacks with extraneous frames. |
| 1506 |
# - for scheduled tasks, custom_sleep_data is None |
| 1507 |
# Tasks start out unscheduled. |
| 1508 |
_next_send_fn: Callable[[Any], object] | None = None # type: ignore[explicit-any] |
| 1509 |
_next_send: Outcome[Any] | BaseException | None = None # type: ignore[explicit-any] |
| 1510 |
_abort_func: Callable[[_core.RaiseCancelT], Abort] | None = None |
| 1511 |
custom_sleep_data: Any = None # type: ignore[explicit-any] |
| 1512 |
|
| 1513 |
# For introspection and nursery.start() |
| 1514 |
_child_nurseries: list[Nursery] = attrs.Factory(list) |
| 1515 |
_eventual_parent_nursery: Nursery | None = None |
| 1516 |
|
| 1517 |
# these are counts of how many cancel/schedule points this task has |
| 1518 |
# executed, for assert{_no,}_checkpoints |
| 1519 |
# XX maybe these should be exposed as part of a statistics() method? |
| 1520 |
_cancel_points: int = 0 |
| 1521 |
_schedule_points: int = 0 |
| 1522 |
|
| 1523 |
def __repr__(self) -> str: |
| 1524 |
return f"<Task {self.name!r} at {id(self):#x}>" |
| 1525 |
|
| 1526 |
@property |
| 1527 |
def parent_nursery(self) -> Nursery | None: |
| 1528 |
"""The nursery this task is inside (or None if this is the "init" |
| 1529 |
task). |
| 1530 |
|
| 1531 |
Example use case: drawing a visualization of the task tree in a |
| 1532 |
debugger. |
| 1533 |
|
| 1534 |
""" |
| 1535 |
return self._parent_nursery |
| 1536 |
|
| 1537 |
@property |
| 1538 |
def eventual_parent_nursery(self) -> Nursery | None: |
| 1539 |
"""The nursery this task will be inside after it calls |
| 1540 |
``task_status.started()``. |
| 1541 |
|
| 1542 |
If this task has already called ``started()``, or if it was not |
| 1543 |
spawned using `nursery.start() <trio.Nursery.start>`, then |
| 1544 |
its `eventual_parent_nursery` is ``None``. |
| 1545 |
|
| 1546 |
""" |
| 1547 |
return self._eventual_parent_nursery |
| 1548 |
|
| 1549 |
@property |
| 1550 |
def child_nurseries(self) -> list[Nursery]: |
| 1551 |
"""The nurseries this task contains. |
| 1552 |
|
| 1553 |
This is a list, with outer nurseries before inner nurseries. |
| 1554 |
|
| 1555 |
""" |
| 1556 |
return list(self._child_nurseries) |
| 1557 |
|
| 1558 |
def iter_await_frames(self) -> Iterator[tuple[types.FrameType, int]]: |
| 1559 |
"""Iterates recursively over the coroutine-like objects this |
| 1560 |
task is waiting on, yielding the frame and line number at each |
| 1561 |
frame. |
| 1562 |
|
| 1563 |
This is similar to `traceback.walk_stack` in a synchronous |
| 1564 |
context. Note that `traceback.walk_stack` returns frames from |
| 1565 |
the bottom of the call stack to the top, while this function |
| 1566 |
starts from `Task.coro <trio.lowlevel.Task.coro>` and works it |
| 1567 |
way down. |
| 1568 |
|
| 1569 |
Example usage: extracting a stack trace:: |
| 1570 |
|
| 1571 |
import traceback |
| 1572 |
|
| 1573 |
def print_stack_for_task(task): |
| 1574 |
ss = traceback.StackSummary.extract(task.iter_await_frames()) |
| 1575 |
print("".join(ss.format())) |
| 1576 |
|
| 1577 |
""" |
| 1578 |
# Ignore static typing as we're doing lots of dynamic introspection |
| 1579 |
coro: Any = self.coro # type: ignore[explicit-any] |
| 1580 |
while coro is not None: |
| 1581 |
if hasattr(coro, "cr_frame"): |
| 1582 |
# A real coroutine |
| 1583 |
if cr_frame := coro.cr_frame: # None if the task has finished |
| 1584 |
yield cr_frame, cr_frame.f_lineno |
| 1585 |
coro = coro.cr_await |
| 1586 |
elif hasattr(coro, "gi_frame"): |
| 1587 |
# A generator decorated with @types.coroutine |
| 1588 |
if gi_frame := coro.gi_frame: # pragma: no branch |
| 1589 |
yield gi_frame, gi_frame.f_lineno # pragma: no cover |
| 1590 |
coro = coro.gi_yieldfrom |
| 1591 |
elif coro.__class__.__name__ in [ |
| 1592 |
"async_generator_athrow", |
| 1593 |
"async_generator_asend", |
| 1594 |
]: |
| 1595 |
# cannot extract the generator directly, see https://github.com/python/cpython/issues/76991 |
| 1596 |
# we can however use the gc to look through the object |
| 1597 |
for referent in gc.get_referents(coro): |
| 1598 |
if hasattr(referent, "ag_frame"): # pragma: no branch |
| 1599 |
yield referent.ag_frame, referent.ag_frame.f_lineno |
| 1600 |
coro = referent.ag_await |
| 1601 |
break |
| 1602 |
else: # pragma: no cover |
| 1603 |
# either cpython changed or we are running on an alternative python implementation |
| 1604 |
return |
| 1605 |
else: # pragma: no cover |
| 1606 |
return |
| 1607 |
|
| 1608 |
################ |
| 1609 |
# Cancellation |
| 1610 |
################ |
| 1611 |
|
| 1612 |
# The CancelStatus object that is currently active for this task. |
| 1613 |
# Don't change this directly; instead, use _activate_cancel_status(). |
| 1614 |
# This can be None, but only in the init task. |
| 1615 |
_cancel_status: CancelStatus = attrs.field(default=None, repr=False) |
| 1616 |
|
| 1617 |
def _activate_cancel_status(self, cancel_status: CancelStatus | None) -> None: |
| 1618 |
if self._cancel_status is not None: |
| 1619 |
self._cancel_status._tasks.remove(self) |
| 1620 |
self._cancel_status = cancel_status # type: ignore[assignment] |
| 1621 |
if self._cancel_status is not None: |
| 1622 |
self._cancel_status._tasks.add(self) |
| 1623 |
if self._cancel_status.effectively_cancelled: |
| 1624 |
self._attempt_delivery_of_any_pending_cancel() |
| 1625 |
|
| 1626 |
def _attempt_abort(self, raise_cancel: _core.RaiseCancelT) -> None: |
| 1627 |
# Either the abort succeeds, in which case we will reschedule the |
| 1628 |
# task, or else it fails, in which case it will worry about |
| 1629 |
# rescheduling itself (hopefully eventually calling reraise to raise |
| 1630 |
# the given exception, but not necessarily). |
| 1631 |
|
| 1632 |
# This is only called by the functions immediately below, which both check |
| 1633 |
# `self.abort_func is not None`. |
| 1634 |
assert self._abort_func is not None, "FATAL INTERNAL ERROR" |
| 1635 |
|
| 1636 |
success = self._abort_func(raise_cancel) |
| 1637 |
if type(success) is not Abort: |
| 1638 |
raise TrioInternalError("abort function must return Abort enum") |
| 1639 |
# We only attempt to abort once per blocking call, regardless of |
| 1640 |
# whether we succeeded or failed. |
| 1641 |
self._abort_func = None |
| 1642 |
if success is Abort.SUCCEEDED: |
| 1643 |
self._runner.reschedule(self, capture(raise_cancel)) |
| 1644 |
|
| 1645 |
def _attempt_delivery_of_any_pending_cancel(self) -> None: |
| 1646 |
if self._abort_func is None: |
| 1647 |
return |
| 1648 |
if not self._cancel_status.effectively_cancelled: |
| 1649 |
return |
| 1650 |
|
| 1651 |
reason = self._cancel_status._scope._cancel_reason |
| 1652 |
|
| 1653 |
def raise_cancel() -> NoReturn: |
| 1654 |
if reason is None: |
| 1655 |
raise Cancelled._create(source="unknown", reason="misnesting") |
| 1656 |
else: |
| 1657 |
raise Cancelled._create( |
| 1658 |
source=reason.source, |
| 1659 |
reason=reason.reason, |
| 1660 |
source_task=reason.source_task, |
| 1661 |
) |
| 1662 |
|
| 1663 |
self._attempt_abort(raise_cancel) |
| 1664 |
|
| 1665 |
def _attempt_delivery_of_pending_ki(self) -> None: |
| 1666 |
assert self._runner.ki_pending |
| 1667 |
if self._abort_func is None: |
| 1668 |
return |
| 1669 |
|
| 1670 |
def raise_cancel() -> NoReturn: |
| 1671 |
self._runner.ki_pending = False |
| 1672 |
raise KeyboardInterrupt |
| 1673 |
|
| 1674 |
self._attempt_abort(raise_cancel) |
| 1675 |
|
| 1676 |
|
| 1677 |
################################################################ |
| 1678 |
# The central Runner object |
| 1679 |
################################################################ |
| 1680 |
|
| 1681 |
|
| 1682 |
@attrs.frozen |
| 1683 |
class RunStatistics: |
| 1684 |
"""An object containing run-loop-level debugging information. |
| 1685 |
|
| 1686 |
Currently, the following fields are defined: |
| 1687 |
|
| 1688 |
* ``tasks_living`` (int): The number of tasks that have been spawned |
| 1689 |
and not yet exited. |
| 1690 |
* ``tasks_runnable`` (int): The number of tasks that are currently |
| 1691 |
queued on the run queue (as opposed to blocked waiting for something |
| 1692 |
to happen). |
| 1693 |
* ``seconds_to_next_deadline`` (float): The time until the next |
| 1694 |
pending cancel scope deadline. May be negative if the deadline has |
| 1695 |
expired but we haven't yet processed cancellations. May be |
| 1696 |
:data:`~math.inf` if there are no pending deadlines. |
| 1697 |
* ``run_sync_soon_queue_size`` (int): The number of |
| 1698 |
unprocessed callbacks queued via |
| 1699 |
:meth:`trio.lowlevel.TrioToken.run_sync_soon`. |
| 1700 |
* ``io_statistics`` (object): Some statistics from Trio's I/O |
| 1701 |
backend. This always has an attribute ``backend`` which is a string |
| 1702 |
naming which operating-system-specific I/O backend is in use; the |
| 1703 |
other attributes vary between backends. |
| 1704 |
""" |
| 1705 |
|
| 1706 |
tasks_living: int |
| 1707 |
tasks_runnable: int |
| 1708 |
seconds_to_next_deadline: float |
| 1709 |
io_statistics: IOStatistics |
| 1710 |
run_sync_soon_queue_size: int |
| 1711 |
|
| 1712 |
|
| 1713 |
# This holds all the state that gets trampolined back and forth between |
| 1714 |
# callbacks when we're running in guest mode. |
| 1715 |
# |
| 1716 |
# It has to be a separate object from Runner, and Runner *cannot* hold |
| 1717 |
# references to it (directly or indirectly)! |
| 1718 |
# |
| 1719 |
# The idea is that we want a chance to detect if our host loop quits and stops |
| 1720 |
# driving us forward. We detect that by unrolled_run_gen being garbage |
| 1721 |
# collected, and hitting its 'except GeneratorExit:' block. So this only |
| 1722 |
# happens if unrolled_run_gen is GCed. |
| 1723 |
# |
| 1724 |
# The Runner state is referenced from the global GLOBAL_RUN_CONTEXT. The only |
| 1725 |
# way it gets *un*referenced is by unrolled_run_gen completing, e.g. by being |
| 1726 |
# GCed. But if Runner has a direct or indirect reference to it, and the host |
| 1727 |
# loop has abandoned it, then this will never happen! |
| 1728 |
# |
| 1729 |
# So this object can reference Runner, but Runner can't reference it. The only |
| 1730 |
# references to it are the "in flight" callback chain on the host loop / |
| 1731 |
# worker thread. |
| 1732 |
|
| 1733 |
|
| 1734 |
@attrs.define(eq=False) |
| 1735 |
class GuestState: # type: ignore[explicit-any] |
| 1736 |
runner: Runner |
| 1737 |
run_sync_soon_threadsafe: Callable[[Callable[[], object]], object] |
| 1738 |
run_sync_soon_not_threadsafe: Callable[[Callable[[], object]], object] |
| 1739 |
done_callback: Callable[[Outcome[Any]], object] # type: ignore[explicit-any] |
| 1740 |
unrolled_run_gen: Generator[float, EventResult, None] |
| 1741 |
unrolled_run_next_send: Outcome[Any] = attrs.Factory(lambda: Value(None)) # type: ignore[explicit-any] |
| 1742 |
|
| 1743 |
def guest_tick(self) -> None: |
| 1744 |
prev_library, sniffio_library.name = sniffio_library.name, "trio" |
| 1745 |
try: |
| 1746 |
timeout = self.unrolled_run_next_send.send(self.unrolled_run_gen) |
| 1747 |
except StopIteration: |
| 1748 |
assert self.runner.main_task_outcome is not None |
| 1749 |
self.done_callback(self.runner.main_task_outcome) |
| 1750 |
return |
| 1751 |
except TrioInternalError as exc: |
| 1752 |
self.done_callback(Error(exc)) |
| 1753 |
return |
| 1754 |
finally: |
| 1755 |
sniffio_library.name = prev_library |
| 1756 |
|
| 1757 |
# Optimization: try to skip going into the thread if we can avoid it |
| 1758 |
events_outcome: Value[EventResult] | Error = capture( |
| 1759 |
self.runner.io_manager.get_events, |
| 1760 |
0, |
| 1761 |
) |
| 1762 |
if timeout <= 0 or isinstance(events_outcome, Error) or events_outcome.value: |
| 1763 |
# No need to go into the thread |
| 1764 |
self.unrolled_run_next_send = events_outcome |
| 1765 |
self.runner.guest_tick_scheduled = True |
| 1766 |
self.run_sync_soon_not_threadsafe(self.guest_tick) |
| 1767 |
else: |
| 1768 |
# Need to go into the thread and call get_events() there |
| 1769 |
self.runner.guest_tick_scheduled = False |
| 1770 |
|
| 1771 |
def get_events() -> EventResult: |
| 1772 |
return self.runner.io_manager.get_events(timeout) |
| 1773 |
|
| 1774 |
def deliver(events_outcome: Outcome[EventResult]) -> None: |
| 1775 |
def in_main_thread() -> None: |
| 1776 |
self.unrolled_run_next_send = events_outcome |
| 1777 |
self.runner.guest_tick_scheduled = True |
| 1778 |
self.guest_tick() |
| 1779 |
|
| 1780 |
self.run_sync_soon_threadsafe(in_main_thread) |
| 1781 |
|
| 1782 |
start_thread_soon(get_events, deliver) |
| 1783 |
|
| 1784 |
|
| 1785 |
@attrs.define(eq=False) |
| 1786 |
class Runner: # type: ignore[explicit-any] |
| 1787 |
clock: Clock |
| 1788 |
instruments: Instruments |
| 1789 |
io_manager: TheIOManager |
| 1790 |
ki_manager: KIManager |
| 1791 |
strict_exception_groups: bool |
| 1792 |
|
| 1793 |
# Run-local values, see _local.py |
| 1794 |
_locals: dict[_core.RunVar[Any], object] = attrs.Factory(dict) # type: ignore[explicit-any] |
| 1795 |
|
| 1796 |
runq: deque[Task] = attrs.Factory(deque) |
| 1797 |
tasks: set[Task] = attrs.Factory(set) |
| 1798 |
|
| 1799 |
deadlines: Deadlines = attrs.Factory(Deadlines) |
| 1800 |
|
| 1801 |
init_task: Task | None = None |
| 1802 |
system_nursery: Nursery | None = None |
| 1803 |
system_context: contextvars.Context = attrs.field(kw_only=True) |
| 1804 |
main_task: Task | None = None |
| 1805 |
main_task_outcome: Outcome[object] | None = None |
| 1806 |
|
| 1807 |
entry_queue: EntryQueue = attrs.Factory(EntryQueue) |
| 1808 |
trio_token: TrioToken | None = None |
| 1809 |
asyncgens: AsyncGenerators = attrs.Factory(AsyncGenerators) |
| 1810 |
|
| 1811 |
# If everything goes idle for this long, we call clock._autojump() |
| 1812 |
clock_autojump_threshold: float = inf |
| 1813 |
|
| 1814 |
# Guest mode stuff |
| 1815 |
is_guest: bool = False |
| 1816 |
guest_tick_scheduled: bool = False |
| 1817 |
|
| 1818 |
def force_guest_tick_asap(self) -> None: |
| 1819 |
if self.guest_tick_scheduled: |
| 1820 |
return |
| 1821 |
self.guest_tick_scheduled = True |
| 1822 |
self.io_manager.force_wakeup() |
| 1823 |
|
| 1824 |
def close(self) -> None: |
| 1825 |
self.io_manager.close() |
| 1826 |
self.entry_queue.close() |
| 1827 |
self.asyncgens.close() |
| 1828 |
if "after_run" in self.instruments: |
| 1829 |
self.instruments.call("after_run") |
| 1830 |
# This is where KI protection gets disabled, so we do it last |
| 1831 |
self.ki_manager.close() |
| 1832 |
|
| 1833 |
@_public |
| 1834 |
def current_statistics(self) -> RunStatistics: |
| 1835 |
"""Returns ``RunStatistics``, which contains run-loop-level debugging information. |
| 1836 |
|
| 1837 |
Currently, the following fields are defined: |
| 1838 |
|
| 1839 |
* ``tasks_living`` (int): The number of tasks that have been spawned |
| 1840 |
and not yet exited. |
| 1841 |
* ``tasks_runnable`` (int): The number of tasks that are currently |
| 1842 |
queued on the run queue (as opposed to blocked waiting for something |
| 1843 |
to happen). |
| 1844 |
* ``seconds_to_next_deadline`` (float): The time until the next |
| 1845 |
pending cancel scope deadline. May be negative if the deadline has |
| 1846 |
expired but we haven't yet processed cancellations. May be |
| 1847 |
:data:`~math.inf` if there are no pending deadlines. |
| 1848 |
* ``run_sync_soon_queue_size`` (int): The number of |
| 1849 |
unprocessed callbacks queued via |
| 1850 |
:meth:`trio.lowlevel.TrioToken.run_sync_soon`. |
| 1851 |
* ``io_statistics`` (object): Some statistics from Trio's I/O |
| 1852 |
backend. This always has an attribute ``backend`` which is a string |
| 1853 |
naming which operating-system-specific I/O backend is in use; the |
| 1854 |
other attributes vary between backends. |
| 1855 |
|
| 1856 |
""" |
| 1857 |
seconds_to_next_deadline = self.deadlines.next_deadline() - self.current_time() |
| 1858 |
return RunStatistics( |
| 1859 |
tasks_living=len(self.tasks), |
| 1860 |
tasks_runnable=len(self.runq), |
| 1861 |
seconds_to_next_deadline=seconds_to_next_deadline, |
| 1862 |
io_statistics=self.io_manager.statistics(), |
| 1863 |
run_sync_soon_queue_size=self.entry_queue.size(), |
| 1864 |
) |
| 1865 |
|
| 1866 |
@_public |
| 1867 |
def current_time(self) -> float: |
| 1868 |
"""Returns the current time according to Trio's internal clock. |
| 1869 |
|
| 1870 |
Returns: |
| 1871 |
float: The current time. |
| 1872 |
|
| 1873 |
Raises: |
| 1874 |
RuntimeError: if not inside a call to :func:`trio.run`. |
| 1875 |
|
| 1876 |
""" |
| 1877 |
return self.clock.current_time() |
| 1878 |
|
| 1879 |
@_public |
| 1880 |
def current_clock(self) -> Clock: |
| 1881 |
"""Returns the current :class:`~trio.abc.Clock`.""" |
| 1882 |
return self.clock |
| 1883 |
|
| 1884 |
@_public |
| 1885 |
def current_root_task(self) -> Task | None: |
| 1886 |
"""Returns the current root :class:`Task`. |
| 1887 |
|
| 1888 |
This is the task that is the ultimate parent of all other tasks. |
| 1889 |
|
| 1890 |
""" |
| 1891 |
return self.init_task |
| 1892 |
|
| 1893 |
################ |
| 1894 |
# Core task handling primitives |
| 1895 |
################ |
| 1896 |
|
| 1897 |
@_public |
| 1898 |
def reschedule( |
| 1899 |
self, task: Task, next_send: outcome.Outcome[object] = _NO_SEND |
| 1900 |
) -> None: |
| 1901 |
"""Reschedule the given task with the given |
| 1902 |
:class:`outcome.Outcome`. |
| 1903 |
|
| 1904 |
See :func:`wait_task_rescheduled` for the gory details. |
| 1905 |
|
| 1906 |
There must be exactly one call to :func:`reschedule` for every call to |
| 1907 |
:func:`wait_task_rescheduled`. (And when counting, keep in mind that |
| 1908 |
returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent |
| 1909 |
to calling :func:`reschedule` once.) |
| 1910 |
|
| 1911 |
Args: |
| 1912 |
task (trio.lowlevel.Task): the task to be rescheduled. Must be blocked |
| 1913 |
in a call to :func:`wait_task_rescheduled`. |
| 1914 |
next_send (outcome.Outcome): the value (or error) to return (or |
| 1915 |
raise) from :func:`wait_task_rescheduled`. |
| 1916 |
|
| 1917 |
""" |
| 1918 |
if next_send is _NO_SEND: |
| 1919 |
next_send = Value(None) |
| 1920 |
|
| 1921 |
assert task._runner is self |
| 1922 |
assert task._next_send_fn is None |
| 1923 |
task._next_send_fn = task.coro.send |
| 1924 |
task._next_send = next_send |
| 1925 |
task._abort_func = None |
| 1926 |
task.custom_sleep_data = None |
| 1927 |
if not self.runq and self.is_guest: |
| 1928 |
self.force_guest_tick_asap() |
| 1929 |
self.runq.append(task) |
| 1930 |
if "task_scheduled" in self.instruments: |
| 1931 |
self.instruments.call("task_scheduled", task) |
| 1932 |
|
| 1933 |
def spawn_impl( |
| 1934 |
self, |
| 1935 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], |
| 1936 |
args: tuple[Unpack[PosArgT]], |
| 1937 |
nursery: Nursery | None, |
| 1938 |
name: object, |
| 1939 |
*, |
| 1940 |
system_task: bool = False, |
| 1941 |
context: contextvars.Context | None = None, |
| 1942 |
) -> Task: |
| 1943 |
###### |
| 1944 |
# Make sure the nursery is in working order |
| 1945 |
###### |
| 1946 |
|
| 1947 |
# This sorta feels like it should be a method on nursery, except it |
| 1948 |
# has to handle nursery=None for init. And it touches the internals of |
| 1949 |
# all kinds of objects. |
| 1950 |
if nursery is not None and nursery._closed: |
| 1951 |
raise RuntimeError("Nursery is closed to new arrivals") |
| 1952 |
if nursery is None: |
| 1953 |
assert self.init_task is None |
| 1954 |
|
| 1955 |
###### |
| 1956 |
# Propagate contextvars |
| 1957 |
###### |
| 1958 |
if context is None: |
| 1959 |
context = self.system_context.copy() if system_task else copy_context() |
| 1960 |
|
| 1961 |
###### |
| 1962 |
# Call the function and get the coroutine object, while giving helpful |
| 1963 |
# errors for common mistakes. |
| 1964 |
###### |
| 1965 |
# TypeVarTuple passed into ParamSpec function confuses Mypy. |
| 1966 |
coro = context.run(coroutine_or_error, async_fn, *args) # type: ignore[arg-type] |
| 1967 |
|
| 1968 |
if name is None: |
| 1969 |
name = async_fn |
| 1970 |
if isinstance(name, functools.partial): |
| 1971 |
name = name.func |
| 1972 |
if not isinstance(name, str): |
| 1973 |
try: |
| 1974 |
name = f"{name.__module__}.{name.__qualname__}" # type: ignore[attr-defined] |
| 1975 |
except AttributeError: |
| 1976 |
name = repr(name) |
| 1977 |
|
| 1978 |
# very old Cython versions (<0.29.24) has the attribute, but with a value of None |
| 1979 |
if getattr(coro, "cr_frame", None) is None: |
| 1980 |
# This async function is implemented in C or Cython |
| 1981 |
async def python_wrapper(orig_coro: Awaitable[RetT]) -> RetT: |
| 1982 |
return await orig_coro |
| 1983 |
|
| 1984 |
coro = python_wrapper(coro) |
| 1985 |
assert coro.cr_frame is not None, "Coroutine frame should exist" # type: ignore[attr-defined] |
| 1986 |
|
| 1987 |
###### |
| 1988 |
# Set up the Task object |
| 1989 |
###### |
| 1990 |
task = Task._create( |
| 1991 |
coro=coro, |
| 1992 |
parent_nursery=nursery, |
| 1993 |
runner=self, |
| 1994 |
name=name, |
| 1995 |
context=context, |
| 1996 |
ki_protected=system_task, |
| 1997 |
) |
| 1998 |
|
| 1999 |
self.tasks.add(task) |
| 2000 |
if nursery is not None: |
| 2001 |
nursery._children.add(task) |
| 2002 |
task._activate_cancel_status(nursery._cancel_status) |
| 2003 |
|
| 2004 |
if "task_spawned" in self.instruments: |
| 2005 |
self.instruments.call("task_spawned", task) |
| 2006 |
# Special case: normally next_send should be an Outcome, but for the |
| 2007 |
# very first send we have to send a literal unboxed None. |
| 2008 |
self.reschedule(task, None) # type: ignore[arg-type] |
| 2009 |
return task |
| 2010 |
|
| 2011 |
def task_exited(self, task: Task, outcome: Outcome[object]) -> None: |
| 2012 |
if task._child_nurseries: |
| 2013 |
for nursery in task._child_nurseries: |
| 2014 |
nursery.cancel_scope._cancel( |
| 2015 |
CancelReason( |
| 2016 |
source="nursery", |
| 2017 |
reason="Parent Task exited prematurely, abandoning this nursery without exiting it properly.", |
| 2018 |
source_task=repr(task), |
| 2019 |
) |
| 2020 |
) |
| 2021 |
nursery._closed = True |
| 2022 |
|
| 2023 |
# break parking lots associated with the exiting task |
| 2024 |
if task in GLOBAL_PARKING_LOT_BREAKER: |
| 2025 |
for lot in GLOBAL_PARKING_LOT_BREAKER[task]: |
| 2026 |
lot.break_lot(task) |
| 2027 |
del GLOBAL_PARKING_LOT_BREAKER[task] |
| 2028 |
|
| 2029 |
if ( |
| 2030 |
task._cancel_status is not None |
| 2031 |
and task._cancel_status.abandoned_by_misnesting |
| 2032 |
and task._cancel_status.parent is None |
| 2033 |
) or task._child_nurseries: |
| 2034 |
reason = "Nursery" if task._child_nurseries else "Cancel scope" |
| 2035 |
# The cancel scope surrounding this task's nursery was closed |
| 2036 |
# before the task exited. Force the task to exit with an error, |
| 2037 |
# since the error might not have been caught elsewhere. See the |
| 2038 |
# comments in CancelStatus.close(). |
| 2039 |
try: |
| 2040 |
# Raise this, rather than just constructing it, to get a |
| 2041 |
# traceback frame included |
| 2042 |
raise RuntimeError( |
| 2043 |
f"{reason} stack corrupted: {reason} surrounding " |
| 2044 |
f"{task!r} was closed before the task exited\n{MISNESTING_ADVICE}", |
| 2045 |
) |
| 2046 |
except RuntimeError as new_exc: |
| 2047 |
if isinstance(outcome, Error): |
| 2048 |
new_exc.__context__ = outcome.error |
| 2049 |
outcome = Error(new_exc) |
| 2050 |
|
| 2051 |
task._activate_cancel_status(None) |
| 2052 |
self.tasks.remove(task) |
| 2053 |
if task is self.init_task: |
| 2054 |
# If the init task crashed, then something is very wrong and we |
| 2055 |
# let the error propagate. (It'll eventually be wrapped in a |
| 2056 |
# TrioInternalError.) |
| 2057 |
outcome.unwrap() |
| 2058 |
# the init task should be the last task to exit. If not, then |
| 2059 |
# something is very wrong. |
| 2060 |
if self.tasks: # pragma: no cover |
| 2061 |
raise TrioInternalError |
| 2062 |
else: |
| 2063 |
if task is self.main_task: |
| 2064 |
self.main_task_outcome = outcome |
| 2065 |
outcome = Value(None) |
| 2066 |
assert task._parent_nursery is not None, task |
| 2067 |
task._parent_nursery._child_finished(task, outcome) |
| 2068 |
|
| 2069 |
if "task_exited" in self.instruments: |
| 2070 |
self.instruments.call("task_exited", task) |
| 2071 |
|
| 2072 |
################ |
| 2073 |
# System tasks and init |
| 2074 |
################ |
| 2075 |
|
| 2076 |
@_public |
| 2077 |
def spawn_system_task( |
| 2078 |
self, |
| 2079 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], |
| 2080 |
*args: Unpack[PosArgT], |
| 2081 |
name: object = None, |
| 2082 |
context: contextvars.Context | None = None, |
| 2083 |
) -> Task: |
| 2084 |
"""Spawn a "system" task. |
| 2085 |
|
| 2086 |
System tasks have a few differences from regular tasks: |
| 2087 |
|
| 2088 |
* They don't need an explicit nursery; instead they go into the |
| 2089 |
internal "system nursery". |
| 2090 |
|
| 2091 |
* If a system task raises an exception, then it's converted into a |
| 2092 |
:exc:`~trio.TrioInternalError` and *all* tasks are cancelled. If you |
| 2093 |
write a system task, you should be careful to make sure it doesn't |
| 2094 |
crash. |
| 2095 |
|
| 2096 |
* System tasks are automatically cancelled when the main task exits. |
| 2097 |
|
| 2098 |
* By default, system tasks have :exc:`KeyboardInterrupt` protection |
| 2099 |
*enabled*. If you want your task to be interruptible by control-C, |
| 2100 |
then you need to use :func:`disable_ki_protection` explicitly (and |
| 2101 |
come up with some plan for what to do with a |
| 2102 |
:exc:`KeyboardInterrupt`, given that system tasks aren't allowed to |
| 2103 |
raise exceptions). |
| 2104 |
|
| 2105 |
* System tasks do not inherit context variables from their creator. |
| 2106 |
|
| 2107 |
Towards the end of a call to :meth:`trio.run`, after the main |
| 2108 |
task and all system tasks have exited, the system nursery |
| 2109 |
becomes closed. At this point, new calls to |
| 2110 |
:func:`spawn_system_task` will raise ``RuntimeError("Nursery |
| 2111 |
is closed to new arrivals")`` instead of creating a system |
| 2112 |
task. It's possible to encounter this state either in |
| 2113 |
a ``finally`` block in an async generator, or in a callback |
| 2114 |
passed to :meth:`TrioToken.run_sync_soon` at the right moment. |
| 2115 |
|
| 2116 |
Args: |
| 2117 |
async_fn: An async callable. |
| 2118 |
args: Positional arguments for ``async_fn``. If you want to pass |
| 2119 |
keyword arguments, use :func:`functools.partial`. |
| 2120 |
name: The name for this task. Only used for debugging/introspection |
| 2121 |
(e.g. ``repr(task_obj)``). If this isn't a string, |
| 2122 |
:func:`spawn_system_task` will try to make it one. A common use |
| 2123 |
case is if you're wrapping a function before spawning a new |
| 2124 |
task, you might pass the original function as the ``name=`` to |
| 2125 |
make debugging easier. |
| 2126 |
context: An optional ``contextvars.Context`` object with context variables |
| 2127 |
to use for this task. You would normally get a copy of the current |
| 2128 |
context with ``context = contextvars.copy_context()`` and then you would |
| 2129 |
pass that ``context`` object here. |
| 2130 |
|
| 2131 |
Returns: |
| 2132 |
Task: the newly spawned task |
| 2133 |
|
| 2134 |
""" |
| 2135 |
return self.spawn_impl( |
| 2136 |
async_fn, |
| 2137 |
args, |
| 2138 |
self.system_nursery, |
| 2139 |
name, |
| 2140 |
system_task=True, |
| 2141 |
context=context, |
| 2142 |
) |
| 2143 |
|
| 2144 |
async def init( |
| 2145 |
self, |
| 2146 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], |
| 2147 |
args: tuple[Unpack[PosArgT]], |
| 2148 |
) -> None: |
| 2149 |
# run_sync_soon task runs here: |
| 2150 |
async with open_nursery() as run_sync_soon_nursery: |
| 2151 |
# All other system tasks run here: |
| 2152 |
async with open_nursery() as self.system_nursery: |
| 2153 |
# Only the main task runs here: |
| 2154 |
async with open_nursery() as main_task_nursery: |
| 2155 |
try: |
| 2156 |
self.main_task = self.spawn_impl( |
| 2157 |
async_fn, |
| 2158 |
args, |
| 2159 |
main_task_nursery, |
| 2160 |
None, |
| 2161 |
) |
| 2162 |
except BaseException as exc: |
| 2163 |
self.main_task_outcome = Error(exc) |
| 2164 |
return |
| 2165 |
self.spawn_impl( |
| 2166 |
self.entry_queue.task, |
| 2167 |
(), |
| 2168 |
run_sync_soon_nursery, |
| 2169 |
"<TrioToken.run_sync_soon task>", |
| 2170 |
system_task=True, |
| 2171 |
) |
| 2172 |
|
| 2173 |
# Main task is done; start shutting down system tasks |
| 2174 |
self.system_nursery.cancel_scope._cancel( |
| 2175 |
CancelReason( |
| 2176 |
source="shutdown", |
| 2177 |
reason="main task done, shutting down system tasks", |
| 2178 |
source_task=repr(self.init_task), |
| 2179 |
) |
| 2180 |
) |
| 2181 |
|
| 2182 |
# System nursery is closed; finalize remaining async generators |
| 2183 |
await self.asyncgens.finalize_remaining(self) |
| 2184 |
|
| 2185 |
# There are no more asyncgens, which means no more user-provided |
| 2186 |
# code except possibly run_sync_soon callbacks. It's finally safe |
| 2187 |
# to stop the run_sync_soon task and exit run(). |
| 2188 |
run_sync_soon_nursery.cancel_scope._cancel( |
| 2189 |
CancelReason( |
| 2190 |
source="shutdown", |
| 2191 |
reason="main task done, shutting down run_sync_soon callbacks", |
| 2192 |
source_task=repr(self.init_task), |
| 2193 |
) |
| 2194 |
) |
| 2195 |
|
| 2196 |
################ |
| 2197 |
# Outside context problems |
| 2198 |
################ |
| 2199 |
|
| 2200 |
@_public |
| 2201 |
def current_trio_token(self) -> TrioToken: |
| 2202 |
"""Retrieve the :class:`TrioToken` for the current call to |
| 2203 |
:func:`trio.run`. |
| 2204 |
|
| 2205 |
""" |
| 2206 |
if self.trio_token is None: |
| 2207 |
self.trio_token = TrioToken._create(self.entry_queue) |
| 2208 |
return self.trio_token |
| 2209 |
|
| 2210 |
################ |
| 2211 |
# KI handling |
| 2212 |
################ |
| 2213 |
|
| 2214 |
ki_pending: bool = False |
| 2215 |
|
| 2216 |
# deliver_ki is broke. Maybe move all the actual logic and state into |
| 2217 |
# RunToken, and we'll only have one instance per runner? But then we can't |
| 2218 |
# have a public constructor. Eh, but current_run_token() returning a |
| 2219 |
# unique object per run feels pretty nice. Maybe let's just go for it. And |
| 2220 |
# keep the class public so people can isinstance() it if they want. |
| 2221 |
|
| 2222 |
# This gets called from signal context |
| 2223 |
def deliver_ki(self) -> None: |
| 2224 |
self.ki_pending = True |
| 2225 |
with suppress(RunFinishedError): |
| 2226 |
self.entry_queue.run_sync_soon(self._deliver_ki_cb) |
| 2227 |
|
| 2228 |
def _deliver_ki_cb(self) -> None: |
| 2229 |
if not self.ki_pending: |
| 2230 |
return |
| 2231 |
# Can't happen because main_task and run_sync_soon_task are created at |
| 2232 |
# the same time -- so even if KI arrives before main_task is created, |
| 2233 |
# we won't get here until afterwards. |
| 2234 |
assert self.main_task is not None |
| 2235 |
if self.main_task_outcome is not None: |
| 2236 |
# We're already in the process of exiting -- leave ki_pending set |
| 2237 |
# and we'll check it again on our way out of run(). |
| 2238 |
return |
| 2239 |
self.main_task._attempt_delivery_of_pending_ki() |
| 2240 |
|
| 2241 |
################ |
| 2242 |
# Quiescing |
| 2243 |
################ |
| 2244 |
|
| 2245 |
# sortedcontainers doesn't have types, and is reportedly very hard to type: |
| 2246 |
# https://github.com/grantjenks/python-sortedcontainers/issues/68 |
| 2247 |
waiting_for_idle: Any = attrs.Factory(SortedDict) # type: ignore[explicit-any] |
| 2248 |
|
| 2249 |
@_public |
| 2250 |
async def wait_all_tasks_blocked(self, cushion: float = 0.0) -> None: |
| 2251 |
"""Block until there are no runnable tasks. |
| 2252 |
|
| 2253 |
This is useful in testing code when you want to give other tasks a |
| 2254 |
chance to "settle down". The calling task is blocked, and doesn't wake |
| 2255 |
up until all other tasks are also blocked for at least ``cushion`` |
| 2256 |
seconds. (Setting a non-zero ``cushion`` is intended to handle cases |
| 2257 |
like two tasks talking to each other over a local socket, where we |
| 2258 |
want to ignore the potential brief moment between a send and receive |
| 2259 |
when all tasks are blocked.) |
| 2260 |
|
| 2261 |
Note that ``cushion`` is measured in *real* time, not the Trio clock |
| 2262 |
time. |
| 2263 |
|
| 2264 |
If there are multiple tasks blocked in :func:`wait_all_tasks_blocked`, |
| 2265 |
then the one with the shortest ``cushion`` is the one woken (and |
| 2266 |
this task becoming unblocked resets the timers for the remaining |
| 2267 |
tasks). If there are multiple tasks that have exactly the same |
| 2268 |
``cushion``, then all are woken. |
| 2269 |
|
| 2270 |
You should also consider :class:`trio.testing.Sequencer`, which |
| 2271 |
provides a more explicit way to control execution ordering within a |
| 2272 |
test, and will often produce more readable tests. |
| 2273 |
|
| 2274 |
Example: |
| 2275 |
Here's an example of one way to test that Trio's locks are fair: we |
| 2276 |
take the lock in the parent, start a child, wait for the child to be |
| 2277 |
blocked waiting for the lock (!), and then check that we can't |
| 2278 |
release and immediately re-acquire the lock:: |
| 2279 |
|
| 2280 |
async def lock_taker(lock): |
| 2281 |
await lock.acquire() |
| 2282 |
lock.release() |
| 2283 |
|
| 2284 |
async def test_lock_fairness(): |
| 2285 |
lock = trio.Lock() |
| 2286 |
await lock.acquire() |
| 2287 |
async with trio.open_nursery() as nursery: |
| 2288 |
nursery.start_soon(lock_taker, lock) |
| 2289 |
# child hasn't run yet, we have the lock |
| 2290 |
assert lock.locked() |
| 2291 |
assert lock._owner is trio.lowlevel.current_task() |
| 2292 |
await trio.testing.wait_all_tasks_blocked() |
| 2293 |
# now the child has run and is blocked on lock.acquire(), we |
| 2294 |
# still have the lock |
| 2295 |
assert lock.locked() |
| 2296 |
assert lock._owner is trio.lowlevel.current_task() |
| 2297 |
lock.release() |
| 2298 |
try: |
| 2299 |
# The child has a prior claim, so we can't have it |
| 2300 |
lock.acquire_nowait() |
| 2301 |
except trio.WouldBlock: |
| 2302 |
assert lock._owner is not trio.lowlevel.current_task() |
| 2303 |
print("PASS") |
| 2304 |
else: |
| 2305 |
print("FAIL") |
| 2306 |
|
| 2307 |
""" |
| 2308 |
task = current_task() |
| 2309 |
key = (cushion, id(task)) |
| 2310 |
self.waiting_for_idle[key] = task |
| 2311 |
|
| 2312 |
def abort(_: _core.RaiseCancelT) -> Abort: |
| 2313 |
del self.waiting_for_idle[key] |
| 2314 |
return Abort.SUCCEEDED |
| 2315 |
|
| 2316 |
await wait_task_rescheduled(abort) |
| 2317 |
|
| 2318 |
|
| 2319 |
################################################################ |
| 2320 |
# run |
| 2321 |
################################################################ |
| 2322 |
# |
| 2323 |
# Trio's core task scheduler and coroutine runner is in 'unrolled_run'. It's |
| 2324 |
# called that because it has an unusual feature: it's actually a generator. |
| 2325 |
# Whenever it needs to fetch IO events from the OS, it yields, and waits for |
| 2326 |
# its caller to send the IO events back in. So the loop is "unrolled" into a |
| 2327 |
# sequence of generator send() calls. |
| 2328 |
# |
| 2329 |
# The reason for this unusual design is to support two different modes of |
| 2330 |
# operation, where the IO is handled differently. |
| 2331 |
# |
| 2332 |
# In normal mode using trio.run, the scheduler and IO run in the same thread: |
| 2333 |
# |
| 2334 |
# Main thread: |
| 2335 |
# |
| 2336 |
# +---------------------------+ |
| 2337 |
# | Run tasks | |
| 2338 |
# | (unrolled_run) | |
| 2339 |
# +---------------------------+ |
| 2340 |
# | Block waiting for I/O | |
| 2341 |
# | (io_manager.get_events) | |
| 2342 |
# +---------------------------+ |
| 2343 |
# | Run tasks | |
| 2344 |
# | (unrolled_run) | |
| 2345 |
# +---------------------------+ |
| 2346 |
# | Block waiting for I/O | |
| 2347 |
# | (io_manager.get_events) | |
| 2348 |
# +---------------------------+ |
| 2349 |
# : |
| 2350 |
# |
| 2351 |
# |
| 2352 |
# In guest mode using trio.lowlevel.start_guest_run, the scheduler runs on the |
| 2353 |
# main thread as a host loop callback, but blocking for IO gets pushed into a |
| 2354 |
# worker thread: |
| 2355 |
# |
| 2356 |
# Main thread executing host loop: Trio I/O thread: |
| 2357 |
# |
| 2358 |
# +---------------------------+ |
| 2359 |
# | Run Trio tasks | |
| 2360 |
# | (unrolled_run) | |
| 2361 |
# +---------------------------+ --------------+ |
| 2362 |
# v |
| 2363 |
# +---------------------------+ +----------------------------+ |
| 2364 |
# | Host loop does whatever | | Block waiting for Trio I/O | |
| 2365 |
# | it wants | | (io_manager.get_events) | |
| 2366 |
# +---------------------------+ +----------------------------+ |
| 2367 |
# | |
| 2368 |
# +---------------------------+ <-------------+ |
| 2369 |
# | Run Trio tasks | |
| 2370 |
# | (unrolled_run) | |
| 2371 |
# +---------------------------+ --------------+ |
| 2372 |
# v |
| 2373 |
# +---------------------------+ +----------------------------+ |
| 2374 |
# | Host loop does whatever | | Block waiting for Trio I/O | |
| 2375 |
# | it wants | | (io_manager.get_events) | |
| 2376 |
# +---------------------------+ +----------------------------+ |
| 2377 |
# : : |
| 2378 |
# |
| 2379 |
# Most of Trio's internals don't need to care about this difference. The main |
| 2380 |
# complication it creates is that in guest mode, we might need to wake up not |
| 2381 |
# just due to OS-reported IO events, but also because of code running on the |
| 2382 |
# host loop calling reschedule() or changing task deadlines. Search for |
| 2383 |
# 'is_guest' to see the special cases we need to handle this. |
| 2384 |
|
| 2385 |
|
| 2386 |
def setup_runner( |
| 2387 |
clock: Clock | None, |
| 2388 |
instruments: Sequence[Instrument], |
| 2389 |
restrict_keyboard_interrupt_to_checkpoints: bool, |
| 2390 |
strict_exception_groups: bool, |
| 2391 |
) -> Runner: |
| 2392 |
"""Create a Runner object and install it as the GLOBAL_RUN_CONTEXT.""" |
| 2393 |
# It wouldn't be *hard* to support nested calls to run(), but I can't |
| 2394 |
# think of a single good reason for it, so let's be conservative for |
| 2395 |
# now: |
| 2396 |
if in_trio_run(): |
| 2397 |
raise RuntimeError("Attempted to call run() from inside a run()") |
| 2398 |
|
| 2399 |
if clock is None: |
| 2400 |
clock = SystemClock() |
| 2401 |
instrument_group = Instruments(instruments) |
| 2402 |
io_manager = TheIOManager() |
| 2403 |
system_context = copy_context() |
| 2404 |
ki_manager = KIManager() |
| 2405 |
|
| 2406 |
runner = Runner( |
| 2407 |
clock=clock, |
| 2408 |
instruments=instrument_group, |
| 2409 |
io_manager=io_manager, |
| 2410 |
system_context=system_context, |
| 2411 |
ki_manager=ki_manager, |
| 2412 |
strict_exception_groups=strict_exception_groups, |
| 2413 |
) |
| 2414 |
runner.asyncgens.install_hooks(runner) |
| 2415 |
|
| 2416 |
# This is where KI protection gets enabled, so we want to do it early - in |
| 2417 |
# particular before we start modifying global state like GLOBAL_RUN_CONTEXT |
| 2418 |
ki_manager.install(runner.deliver_ki, restrict_keyboard_interrupt_to_checkpoints) |
| 2419 |
|
| 2420 |
GLOBAL_RUN_CONTEXT.runner = runner |
| 2421 |
return runner |
| 2422 |
|
| 2423 |
|
| 2424 |
def run( |
| 2425 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[RetT]], |
| 2426 |
*args: Unpack[PosArgT], |
| 2427 |
clock: Clock | None = None, |
| 2428 |
instruments: Sequence[Instrument] = (), |
| 2429 |
restrict_keyboard_interrupt_to_checkpoints: bool = False, |
| 2430 |
strict_exception_groups: bool = True, |
| 2431 |
) -> RetT: |
| 2432 |
"""Run a Trio-flavored async function, and return the result. |
| 2433 |
|
| 2434 |
Calling:: |
| 2435 |
|
| 2436 |
run(async_fn, *args) |
| 2437 |
|
| 2438 |
is the equivalent of:: |
| 2439 |
|
| 2440 |
await async_fn(*args) |
| 2441 |
|
| 2442 |
except that :func:`run` can (and must) be called from a synchronous |
| 2443 |
context. |
| 2444 |
|
| 2445 |
This is Trio's main entry point. Almost every other function in Trio |
| 2446 |
requires that you be inside a call to :func:`run`. |
| 2447 |
|
| 2448 |
Args: |
| 2449 |
async_fn: An async function. |
| 2450 |
|
| 2451 |
args: Positional arguments to be passed to *async_fn*. If you need to |
| 2452 |
pass keyword arguments, then use :func:`functools.partial`. |
| 2453 |
|
| 2454 |
clock: ``None`` to use the default system-specific monotonic clock; |
| 2455 |
otherwise, an object implementing the :class:`trio.abc.Clock` |
| 2456 |
interface, like (for example) a :class:`trio.testing.MockClock` |
| 2457 |
instance. |
| 2458 |
|
| 2459 |
instruments (list of :class:`trio.abc.Instrument` objects): Any |
| 2460 |
instrumentation you want to apply to this run. This can also be |
| 2461 |
modified during the run; see :ref:`instrumentation`. |
| 2462 |
|
| 2463 |
restrict_keyboard_interrupt_to_checkpoints (bool): What happens if the |
| 2464 |
user hits control-C while :func:`run` is running? If this argument |
| 2465 |
is False (the default), then you get the standard Python behavior: a |
| 2466 |
:exc:`KeyboardInterrupt` exception will immediately interrupt |
| 2467 |
whatever task is running (or if no task is running, then Trio will |
| 2468 |
wake up a task to be interrupted). Alternatively, if you set this |
| 2469 |
argument to True, then :exc:`KeyboardInterrupt` delivery will be |
| 2470 |
delayed: it will be *only* be raised at :ref:`checkpoints |
| 2471 |
<checkpoints>`, like a :exc:`Cancelled` exception. |
| 2472 |
|
| 2473 |
The default behavior is nice because it means that even if you |
| 2474 |
accidentally write an infinite loop that never executes any |
| 2475 |
checkpoints, then you can still break out of it using control-C. |
| 2476 |
The alternative behavior is nice if you're paranoid about a |
| 2477 |
:exc:`KeyboardInterrupt` at just the wrong place leaving your |
| 2478 |
program in an inconsistent state, because it means that you only |
| 2479 |
have to worry about :exc:`KeyboardInterrupt` at the exact same |
| 2480 |
places where you already have to worry about :exc:`Cancelled`. |
| 2481 |
|
| 2482 |
This setting has no effect if your program has registered a custom |
| 2483 |
SIGINT handler, or if :func:`run` is called from anywhere but the |
| 2484 |
main thread (this is a Python limitation), or if you use |
| 2485 |
:func:`open_signal_receiver` to catch SIGINT. |
| 2486 |
|
| 2487 |
strict_exception_groups (bool): Unless set to False, nurseries will always wrap |
| 2488 |
even a single raised exception in an exception group. This can be overridden |
| 2489 |
on the level of individual nurseries. Setting it to False will be deprecated |
| 2490 |
and ultimately removed in a future version of Trio. |
| 2491 |
|
| 2492 |
Returns: |
| 2493 |
Whatever ``async_fn`` returns. |
| 2494 |
|
| 2495 |
Raises: |
| 2496 |
TrioInternalError: if an unexpected error is encountered inside Trio's |
| 2497 |
internal machinery. This is a bug and you should `let us know |
| 2498 |
<https://github.com/python-trio/trio/issues>`__. |
| 2499 |
|
| 2500 |
Anything else: if ``async_fn`` raises an exception, then :func:`run` |
| 2501 |
propagates it. |
| 2502 |
|
| 2503 |
""" |
| 2504 |
if strict_exception_groups is not None and not strict_exception_groups: |
| 2505 |
warn_deprecated( |
| 2506 |
"trio.run(..., strict_exception_groups=False)", |
| 2507 |
version="0.25.0", |
| 2508 |
issue=2929, |
| 2509 |
instead=( |
| 2510 |
"the default value of True and rewrite exception handlers to handle ExceptionGroups. " |
| 2511 |
"See https://trio.readthedocs.io/en/stable/reference-core.html#designing-for-multiple-errors" |
| 2512 |
), |
| 2513 |
use_triodeprecationwarning=True, |
| 2514 |
) |
| 2515 |
|
| 2516 |
__tracebackhide__ = True |
| 2517 |
|
| 2518 |
runner = setup_runner( |
| 2519 |
clock, |
| 2520 |
instruments, |
| 2521 |
restrict_keyboard_interrupt_to_checkpoints, |
| 2522 |
strict_exception_groups, |
| 2523 |
) |
| 2524 |
|
| 2525 |
prev_library, sniffio_library.name = sniffio_library.name, "trio" |
| 2526 |
try: |
| 2527 |
gen = unrolled_run(runner, async_fn, args) |
| 2528 |
# Need to send None in the first time. |
| 2529 |
next_send: EventResult = None # type: ignore[assignment] |
| 2530 |
while True: |
| 2531 |
try: |
| 2532 |
timeout = gen.send(next_send) |
| 2533 |
except StopIteration: |
| 2534 |
break |
| 2535 |
next_send = runner.io_manager.get_events(timeout) |
| 2536 |
finally: |
| 2537 |
sniffio_library.name = prev_library |
| 2538 |
# Inlined copy of runner.main_task_outcome.unwrap() to avoid |
| 2539 |
# cluttering every single Trio traceback with an extra frame. |
| 2540 |
if isinstance(runner.main_task_outcome, Value): |
| 2541 |
return cast("RetT", runner.main_task_outcome.value) |
| 2542 |
elif isinstance(runner.main_task_outcome, Error): |
| 2543 |
raise runner.main_task_outcome.error |
| 2544 |
else: # pragma: no cover |
| 2545 |
raise AssertionError(runner.main_task_outcome) |
| 2546 |
|
| 2547 |
|
| 2548 |
def start_guest_run( # type: ignore[explicit-any] |
| 2549 |
async_fn: Callable[..., Awaitable[RetT]], |
| 2550 |
*args: object, |
| 2551 |
run_sync_soon_threadsafe: Callable[[Callable[[], object]], object], |
| 2552 |
done_callback: Callable[[outcome.Outcome[RetT]], object], |
| 2553 |
run_sync_soon_not_threadsafe: ( |
| 2554 |
Callable[[Callable[[], object]], object] | None |
| 2555 |
) = None, |
| 2556 |
host_uses_signal_set_wakeup_fd: bool = False, |
| 2557 |
clock: Clock | None = None, |
| 2558 |
instruments: Sequence[Instrument] = (), |
| 2559 |
restrict_keyboard_interrupt_to_checkpoints: bool = False, |
| 2560 |
strict_exception_groups: bool = True, |
| 2561 |
) -> None: |
| 2562 |
"""Start a "guest" run of Trio on top of some other "host" event loop. |
| 2563 |
|
| 2564 |
Each host loop can only have one guest run at a time. |
| 2565 |
|
| 2566 |
You should always let the Trio run finish before stopping the host loop; |
| 2567 |
if not, it may leave Trio's internal data structures in an inconsistent |
| 2568 |
state. You might be able to get away with it if you immediately exit the |
| 2569 |
program, but it's safest not to go there in the first place. |
| 2570 |
|
| 2571 |
Generally, the best way to do this is wrap this in a function that starts |
| 2572 |
the host loop and then immediately starts the guest run, and then shuts |
| 2573 |
down the host when the guest run completes. |
| 2574 |
|
| 2575 |
Once :func:`start_guest_run` returns successfully, the guest run |
| 2576 |
has been set up enough that you can invoke sync-colored Trio |
| 2577 |
functions such as :func:`~trio.current_time`, :func:`spawn_system_task`, |
| 2578 |
and :func:`current_trio_token`. If a `~trio.TrioInternalError` occurs |
| 2579 |
during this early setup of the guest run, it will be raised out of |
| 2580 |
:func:`start_guest_run`. All other errors, including all errors |
| 2581 |
raised by the *async_fn*, will be delivered to your |
| 2582 |
*done_callback* at some point after :func:`start_guest_run` returns |
| 2583 |
successfully. |
| 2584 |
|
| 2585 |
Args: |
| 2586 |
|
| 2587 |
run_sync_soon_threadsafe: An arbitrary callable, which will be passed a |
| 2588 |
function as its sole argument:: |
| 2589 |
|
| 2590 |
def my_run_sync_soon_threadsafe(fn): |
| 2591 |
... |
| 2592 |
|
| 2593 |
This callable should schedule ``fn()`` to be run by the host on its |
| 2594 |
next pass through its loop. **Must support being called from |
| 2595 |
arbitrary threads.** |
| 2596 |
|
| 2597 |
done_callback: An arbitrary callable:: |
| 2598 |
|
| 2599 |
def my_done_callback(run_outcome): |
| 2600 |
... |
| 2601 |
|
| 2602 |
When the Trio run has finished, Trio will invoke this callback to let |
| 2603 |
you know. The argument is an `outcome.Outcome`, reporting what would |
| 2604 |
have been returned or raised by `trio.run`. This function can do |
| 2605 |
anything you want, but commonly you'll want it to shut down the |
| 2606 |
host loop, unwrap the outcome, etc. |
| 2607 |
|
| 2608 |
run_sync_soon_not_threadsafe: Like ``run_sync_soon_threadsafe``, but |
| 2609 |
will only be called from inside the host loop's main thread. |
| 2610 |
Optional, but if your host loop allows you to implement this more |
| 2611 |
efficiently than ``run_sync_soon_threadsafe`` then passing it will |
| 2612 |
make things a bit faster. |
| 2613 |
|
| 2614 |
host_uses_signal_set_wakeup_fd (bool): Pass `True` if your host loop |
| 2615 |
uses `signal.set_wakeup_fd`, and `False` otherwise. For more details, |
| 2616 |
see :ref:`guest-run-implementation`. |
| 2617 |
|
| 2618 |
For the meaning of other arguments, see `trio.run`. |
| 2619 |
|
| 2620 |
""" |
| 2621 |
if strict_exception_groups is not None and not strict_exception_groups: |
| 2622 |
warn_deprecated( |
| 2623 |
"trio.start_guest_run(..., strict_exception_groups=False)", |
| 2624 |
version="0.25.0", |
| 2625 |
issue=2929, |
| 2626 |
instead=( |
| 2627 |
"the default value of True and rewrite exception handlers to handle ExceptionGroups. " |
| 2628 |
"See https://trio.readthedocs.io/en/stable/reference-core.html#designing-for-multiple-errors" |
| 2629 |
), |
| 2630 |
use_triodeprecationwarning=True, |
| 2631 |
) |
| 2632 |
|
| 2633 |
runner = setup_runner( |
| 2634 |
clock, |
| 2635 |
instruments, |
| 2636 |
restrict_keyboard_interrupt_to_checkpoints, |
| 2637 |
strict_exception_groups, |
| 2638 |
) |
| 2639 |
runner.is_guest = True |
| 2640 |
runner.guest_tick_scheduled = True |
| 2641 |
|
| 2642 |
if run_sync_soon_not_threadsafe is None: |
| 2643 |
run_sync_soon_not_threadsafe = run_sync_soon_threadsafe |
| 2644 |
|
| 2645 |
guest_state = GuestState( |
| 2646 |
runner=runner, |
| 2647 |
run_sync_soon_threadsafe=run_sync_soon_threadsafe, |
| 2648 |
run_sync_soon_not_threadsafe=run_sync_soon_not_threadsafe, |
| 2649 |
done_callback=done_callback, |
| 2650 |
unrolled_run_gen=unrolled_run( |
| 2651 |
runner, |
| 2652 |
async_fn, |
| 2653 |
args, |
| 2654 |
host_uses_signal_set_wakeup_fd=host_uses_signal_set_wakeup_fd, |
| 2655 |
), |
| 2656 |
) |
| 2657 |
|
| 2658 |
# Run a few ticks of the guest run synchronously, so that by the |
| 2659 |
# time we return, the system nursery exists and callers can use |
| 2660 |
# spawn_system_task. We don't actually run any user code during |
| 2661 |
# this time, so it shouldn't be possible to get an exception here, |
| 2662 |
# except for a TrioInternalError. |
| 2663 |
next_send = cast( |
| 2664 |
"EventResult", |
| 2665 |
None, |
| 2666 |
) # First iteration must be `None`, every iteration after that is EventResult |
| 2667 |
for _tick in range(5): # expected need is 2 iterations + leave some wiggle room |
| 2668 |
if runner.system_nursery is not None: |
| 2669 |
# We're initialized enough to switch to async guest ticks |
| 2670 |
break |
| 2671 |
try: |
| 2672 |
timeout = guest_state.unrolled_run_gen.send(next_send) |
| 2673 |
except StopIteration: # pragma: no cover |
| 2674 |
raise TrioInternalError( |
| 2675 |
"Guest runner exited before system nursery was initialized", |
| 2676 |
) from None |
| 2677 |
if timeout != 0: # pragma: no cover |
| 2678 |
guest_state.unrolled_run_gen.throw( |
| 2679 |
TrioInternalError( |
| 2680 |
"Guest runner blocked before system nursery was initialized", |
| 2681 |
), |
| 2682 |
) |
| 2683 |
# next_send should be the return value of |
| 2684 |
# IOManager.get_events() if no I/O was waiting, which is |
| 2685 |
# platform-dependent. We don't actually check for I/O during |
| 2686 |
# this init phase because no one should be expecting any yet. |
| 2687 |
if sys.platform == "win32": |
| 2688 |
next_send = 0 |
| 2689 |
else: |
| 2690 |
next_send = [] |
| 2691 |
else: # pragma: no cover |
| 2692 |
guest_state.unrolled_run_gen.throw( |
| 2693 |
TrioInternalError( |
| 2694 |
"Guest runner yielded too many times before " |
| 2695 |
"system nursery was initialized", |
| 2696 |
), |
| 2697 |
) |
| 2698 |
|
| 2699 |
guest_state.unrolled_run_next_send = Value(next_send) |
| 2700 |
run_sync_soon_not_threadsafe(guest_state.guest_tick) |
| 2701 |
|
| 2702 |
|
| 2703 |
# 24 hours is arbitrary, but it avoids issues like people setting timeouts of |
| 2704 |
# 10**20 and then getting integer overflows in the underlying system calls. |
| 2705 |
_MAX_TIMEOUT: Final = 24 * 60 * 60 |
| 2706 |
|
| 2707 |
|
| 2708 |
# Weird quirk: this is written as a generator in order to support "guest |
| 2709 |
# mode", where our core event loop gets unrolled into a series of callbacks on |
| 2710 |
# the host loop. If you're doing a regular trio.run then this gets run |
| 2711 |
# straight through. |
| 2712 |
@enable_ki_protection |
| 2713 |
def unrolled_run( |
| 2714 |
runner: Runner, |
| 2715 |
async_fn: Callable[[Unpack[PosArgT]], Awaitable[object]], |
| 2716 |
args: tuple[Unpack[PosArgT]], |
| 2717 |
host_uses_signal_set_wakeup_fd: bool = False, |
| 2718 |
) -> Generator[float, EventResult, None]: |
| 2719 |
__tracebackhide__ = True |
| 2720 |
|
| 2721 |
try: |
| 2722 |
if not host_uses_signal_set_wakeup_fd: |
| 2723 |
runner.entry_queue.wakeup.wakeup_on_signals() |
| 2724 |
|
| 2725 |
if "before_run" in runner.instruments: |
| 2726 |
runner.instruments.call("before_run") |
| 2727 |
runner.clock.start_clock() |
| 2728 |
runner.init_task = runner.spawn_impl( |
| 2729 |
runner.init, |
| 2730 |
(async_fn, args), |
| 2731 |
None, |
| 2732 |
"<init>", |
| 2733 |
system_task=True, |
| 2734 |
) |
| 2735 |
|
| 2736 |
# You know how people talk about "event loops"? This 'while' loop right |
| 2737 |
# here is our event loop: |
| 2738 |
while runner.tasks: |
| 2739 |
if runner.runq: |
| 2740 |
timeout: float = 0 |
| 2741 |
else: |
| 2742 |
deadline = runner.deadlines.next_deadline() |
| 2743 |
timeout = runner.clock.deadline_to_sleep_time(deadline) |
| 2744 |
timeout = min(max(0, timeout), _MAX_TIMEOUT) |
| 2745 |
|
| 2746 |
idle_primed = None |
| 2747 |
if runner.waiting_for_idle: |
| 2748 |
cushion, _ = runner.waiting_for_idle.keys()[0] |
| 2749 |
if cushion < timeout: |
| 2750 |
timeout = cushion |
| 2751 |
idle_primed = IdlePrimedTypes.WAITING_FOR_IDLE |
| 2752 |
# We use 'elif' here because if there are tasks in |
| 2753 |
# wait_all_tasks_blocked, then those tasks will wake up without |
| 2754 |
# jumping the clock, so we don't need to autojump. |
| 2755 |
elif runner.clock_autojump_threshold < timeout: |
| 2756 |
timeout = runner.clock_autojump_threshold |
| 2757 |
idle_primed = IdlePrimedTypes.AUTOJUMP_CLOCK |
| 2758 |
|
| 2759 |
if "before_io_wait" in runner.instruments: |
| 2760 |
runner.instruments.call("before_io_wait", timeout) |
| 2761 |
|
| 2762 |
# Driver will call io_manager.get_events(timeout) and pass it back |
| 2763 |
# in through the yield |
| 2764 |
events = yield timeout |
| 2765 |
runner.io_manager.process_events(events) |
| 2766 |
|
| 2767 |
if "after_io_wait" in runner.instruments: |
| 2768 |
runner.instruments.call("after_io_wait", timeout) |
| 2769 |
|
| 2770 |
# Process cancellations due to deadline expiry |
| 2771 |
now = runner.clock.current_time() |
| 2772 |
if runner.deadlines.expire(now): |
| 2773 |
idle_primed = None |
| 2774 |
|
| 2775 |
# idle_primed != None means: if the IO wait hit the timeout, and |
| 2776 |
# still nothing is happening, then we should start waking up |
| 2777 |
# wait_all_tasks_blocked tasks or autojump the clock. But there |
| 2778 |
# are some subtleties in defining "nothing is happening". |
| 2779 |
# |
| 2780 |
# 'not runner.runq' means that no tasks are currently runnable. |
| 2781 |
# 'not events' means that the last IO wait call hit its full |
| 2782 |
# timeout. These are very similar, and if idle_primed != None and |
| 2783 |
# we're running in regular mode then they always go together. But, |
| 2784 |
# in *guest* mode, they can happen independently, even when |
| 2785 |
# idle_primed=True: |
| 2786 |
# |
| 2787 |
# - runner.runq=empty and events=True: the host loop adjusted a |
| 2788 |
# deadline and that forced an IO wakeup before the timeout expired, |
| 2789 |
# even though no actual tasks were scheduled. |
| 2790 |
# |
| 2791 |
# - runner.runq=nonempty and events=False: the IO wait hit its |
| 2792 |
# timeout, but then some code in the host thread rescheduled a task |
| 2793 |
# before we got here. |
| 2794 |
# |
| 2795 |
# So we need to check both. |
| 2796 |
if idle_primed is not None and not runner.runq and not events: |
| 2797 |
if idle_primed is IdlePrimedTypes.WAITING_FOR_IDLE: |
| 2798 |
while runner.waiting_for_idle: |
| 2799 |
key, task = runner.waiting_for_idle.peekitem(0) |
| 2800 |
if key[0] == cushion: |
| 2801 |
del runner.waiting_for_idle[key] |
| 2802 |
runner.reschedule(task) |
| 2803 |
else: |
| 2804 |
break |
| 2805 |
else: |
| 2806 |
assert idle_primed is IdlePrimedTypes.AUTOJUMP_CLOCK |
| 2807 |
assert isinstance(runner.clock, _core.MockClock) |
| 2808 |
runner.clock._autojump() |
| 2809 |
|
| 2810 |
# Process all runnable tasks, but only the ones that are already |
| 2811 |
# runnable now. Anything that becomes runnable during this cycle |
| 2812 |
# needs to wait until the next pass. This avoids various |
| 2813 |
# starvation issues by ensuring that there's never an unbounded |
| 2814 |
# delay between successive checks for I/O. |
| 2815 |
# |
| 2816 |
# Also, we randomize the order of each batch to avoid assumptions |
| 2817 |
# about scheduling order sneaking in. In the long run, I suspect |
| 2818 |
# we'll either (a) use strict FIFO ordering and document that for |
| 2819 |
# predictability/determinism, or (b) implement a more |
| 2820 |
# sophisticated scheduler (e.g. some variant of fair queueing), |
| 2821 |
# for better behavior under load. For now, this is the worst of |
| 2822 |
# both worlds - but it keeps our options open. (If we do decide to |
| 2823 |
# go all in on deterministic scheduling, then there are other |
| 2824 |
# things that will probably need to change too, like the deadlines |
| 2825 |
# tie-breaker and the non-deterministic ordering of |
| 2826 |
# task._notify_queues.) |
| 2827 |
batch = list(runner.runq) |
| 2828 |
runner.runq.clear() |
| 2829 |
if _ALLOW_DETERMINISTIC_SCHEDULING: |
| 2830 |
# We're running under Hypothesis, and pytest-trio has patched |
| 2831 |
# this in to make the scheduler deterministic and avoid flaky |
| 2832 |
# tests. It's not worth the (small) performance cost in normal |
| 2833 |
# operation, since we'll shuffle the list and _r is only |
| 2834 |
# seeded for tests. |
| 2835 |
batch.sort(key=lambda t: t._counter) |
| 2836 |
_r.shuffle(batch) |
| 2837 |
else: |
| 2838 |
# 50% chance of reversing the batch, this way each task |
| 2839 |
# can appear before/after any other task. |
| 2840 |
if _r.random() < 0.5: |
| 2841 |
batch.reverse() |
| 2842 |
while batch: |
| 2843 |
task = batch.pop() |
| 2844 |
GLOBAL_RUN_CONTEXT.task = task |
| 2845 |
|
| 2846 |
if "before_task_step" in runner.instruments: |
| 2847 |
runner.instruments.call("before_task_step", task) |
| 2848 |
|
| 2849 |
next_send_fn = task._next_send_fn |
| 2850 |
next_send = task._next_send |
| 2851 |
task._next_send_fn = task._next_send = None |
| 2852 |
final_outcome: Outcome[object] | None = None |
| 2853 |
|
| 2854 |
assert next_send_fn is not None |
| 2855 |
|
| 2856 |
try: |
| 2857 |
# We used to unwrap the Outcome object here and send/throw |
| 2858 |
# its contents in directly, but it turns out that .throw() |
| 2859 |
# is buggy on CPython (all versions at time of writing): |
| 2860 |
# https://bugs.python.org/issue29587 |
| 2861 |
# https://bugs.python.org/issue29590 |
| 2862 |
# https://bugs.python.org/issue40694 |
| 2863 |
# https://github.com/python/cpython/issues/108668 |
| 2864 |
# So now we send in the Outcome object and unwrap it on the |
| 2865 |
# other side. |
| 2866 |
msg = task.context.run(next_send_fn, next_send) |
| 2867 |
except StopIteration as stop_iteration: |
| 2868 |
final_outcome = Value(stop_iteration.value) |
| 2869 |
except BaseException as task_exc: |
| 2870 |
# Store for later, removing uninteresting top frames: 1 |
| 2871 |
# frame we always remove, because it's this function |
| 2872 |
# catching it, and then in addition we remove however many |
| 2873 |
# more Context.run adds. |
| 2874 |
tb = task_exc.__traceback__ |
| 2875 |
for _ in range(1 + CONTEXT_RUN_TB_FRAMES): |
| 2876 |
if tb is not None: # pragma: no branch |
| 2877 |
tb = tb.tb_next |
| 2878 |
final_outcome = Error(task_exc.with_traceback(tb)) |
| 2879 |
# Remove local refs so that e.g. cancelled coroutine locals |
| 2880 |
# are not kept alive by this frame until another exception |
| 2881 |
# comes along. |
| 2882 |
del tb |
| 2883 |
|
| 2884 |
if final_outcome is not None: |
| 2885 |
# We can't call this directly inside the except: blocks |
| 2886 |
# above, because then the exceptions end up attaching |
| 2887 |
# themselves to other exceptions as __context__ in |
| 2888 |
# unwanted ways. |
| 2889 |
runner.task_exited(task, final_outcome) |
| 2890 |
# final_outcome may contain a traceback ref. It's not as |
| 2891 |
# crucial compared to the above, but this will allow more |
| 2892 |
# prompt release of resources in coroutine locals. |
| 2893 |
final_outcome = None |
| 2894 |
else: |
| 2895 |
task._schedule_points += 1 |
| 2896 |
if msg is CancelShieldedCheckpoint: |
| 2897 |
runner.reschedule(task) |
| 2898 |
elif type(msg) is WaitTaskRescheduled: |
| 2899 |
task._cancel_points += 1 |
| 2900 |
task._abort_func = msg.abort_func |
| 2901 |
# KI is "outside" all cancel scopes, so check for it |
| 2902 |
# before checking for regular cancellation: |
| 2903 |
if runner.ki_pending and task is runner.main_task: |
| 2904 |
task._attempt_delivery_of_pending_ki() |
| 2905 |
task._attempt_delivery_of_any_pending_cancel() |
| 2906 |
elif type(msg) is PermanentlyDetachCoroutineObject: |
| 2907 |
# Pretend the task just exited with the given outcome |
| 2908 |
runner.task_exited(task, msg.final_outcome) |
| 2909 |
else: |
| 2910 |
exc = TypeError( |
| 2911 |
f"trio.run received unrecognized yield message {msg!r}. " |
| 2912 |
"Are you trying to use a library written for some " |
| 2913 |
"other framework like asyncio? That won't work " |
| 2914 |
"without some kind of compatibility shim.", |
| 2915 |
) |
| 2916 |
# The foreign library probably doesn't adhere to our |
| 2917 |
# protocol of unwrapping whatever outcome gets sent in. |
| 2918 |
# Instead, we'll arrange to throw `exc` in directly, |
| 2919 |
# which works for at least asyncio and curio. |
| 2920 |
runner.reschedule(task, exc) # type: ignore[arg-type] |
| 2921 |
task._next_send_fn = task.coro.throw |
| 2922 |
# prevent long-lived reference |
| 2923 |
# TODO: develop test for this deletion |
| 2924 |
del msg |
| 2925 |
|
| 2926 |
if "after_task_step" in runner.instruments: |
| 2927 |
runner.instruments.call("after_task_step", task) |
| 2928 |
del GLOBAL_RUN_CONTEXT.task |
| 2929 |
# prevent long-lived references |
| 2930 |
# TODO: develop test for this deletion |
| 2931 |
del task, next_send, next_send_fn |
| 2932 |
|
| 2933 |
except GeneratorExit: |
| 2934 |
# The run-loop generator has been garbage collected without finishing |
| 2935 |
warnings.warn( |
| 2936 |
RuntimeWarning( |
| 2937 |
"Trio guest run got abandoned without properly finishing... " |
| 2938 |
"weird stuff might happen", |
| 2939 |
), |
| 2940 |
stacklevel=1, |
| 2941 |
) |
| 2942 |
except TrioInternalError: |
| 2943 |
raise |
| 2944 |
except BaseException as exc: |
| 2945 |
raise TrioInternalError("internal error in Trio - please file a bug!") from exc |
| 2946 |
finally: |
| 2947 |
runner.close() |
| 2948 |
GLOBAL_RUN_CONTEXT.__dict__.clear() |
| 2949 |
|
| 2950 |
# Have to do this after runner.close() has disabled KI protection, |
| 2951 |
# because otherwise there's a race where ki_pending could get set |
| 2952 |
# after we check it. |
| 2953 |
if runner.ki_pending: |
| 2954 |
ki = KeyboardInterrupt() |
| 2955 |
if isinstance(runner.main_task_outcome, Error): |
| 2956 |
ki.__context__ = runner.main_task_outcome.error |
| 2957 |
runner.main_task_outcome = Error(ki) |
| 2958 |
|
| 2959 |
|
| 2960 |
################################################################ |
| 2961 |
# Other public API functions |
| 2962 |
################################################################ |
| 2963 |
|
| 2964 |
|
| 2965 |
class _TaskStatusIgnored(TaskStatus[object]): |
| 2966 |
def __repr__(self) -> str: |
| 2967 |
return "TASK_STATUS_IGNORED" |
| 2968 |
|
| 2969 |
def started(self, value: object = None) -> None: |
| 2970 |
pass |
| 2971 |
|
| 2972 |
|
| 2973 |
TASK_STATUS_IGNORED: Final[TaskStatus[object]] = _TaskStatusIgnored() |
| 2974 |
|
| 2975 |
|
| 2976 |
def current_task() -> Task: |
| 2977 |
"""Return the :class:`Task` object representing the current task. |
| 2978 |
|
| 2979 |
Returns: |
| 2980 |
Task: the :class:`Task` that called :func:`current_task`. |
| 2981 |
|
| 2982 |
""" |
| 2983 |
|
| 2984 |
try: |
| 2985 |
return GLOBAL_RUN_CONTEXT.task |
| 2986 |
except AttributeError: |
| 2987 |
raise RuntimeError("must be called from async context") from None |
| 2988 |
|
| 2989 |
|
| 2990 |
def current_effective_deadline() -> float: |
| 2991 |
"""Returns the current effective deadline for the current task. |
| 2992 |
|
| 2993 |
This function examines all the cancellation scopes that are currently in |
| 2994 |
effect (taking into account shielding), and returns the deadline that will |
| 2995 |
expire first. |
| 2996 |
|
| 2997 |
One example of where this might be is useful is if your code is trying to |
| 2998 |
decide whether to begin an expensive operation like an RPC call, but wants |
| 2999 |
to skip it if it knows that it can't possibly complete in the available |
| 3000 |
time. Another example would be if you're using a protocol like gRPC that |
| 3001 |
`propagates timeout information to the remote peer |
| 3002 |
<http://www.grpc.io/docs/guides/concepts.html#deadlines>`__; this function |
| 3003 |
gives a way to fetch that information so you can send it along. |
| 3004 |
|
| 3005 |
If this is called in a context where a cancellation is currently active |
| 3006 |
(i.e., a blocking call will immediately raise :exc:`Cancelled`), then |
| 3007 |
returned deadline is ``-inf``. If it is called in a context where no |
| 3008 |
scopes have a deadline set, it returns ``inf``. |
| 3009 |
|
| 3010 |
Returns: |
| 3011 |
float: the effective deadline, as an absolute time. |
| 3012 |
|
| 3013 |
""" |
| 3014 |
return current_task()._cancel_status.effective_deadline() |
| 3015 |
|
| 3016 |
|
| 3017 |
async def checkpoint() -> None: |
| 3018 |
"""A pure :ref:`checkpoint <checkpoints>`. |
| 3019 |
|
| 3020 |
This checks for cancellation and allows other tasks to be scheduled, |
| 3021 |
without otherwise blocking. |
| 3022 |
|
| 3023 |
Note that the scheduler has the option of ignoring this and continuing to |
| 3024 |
run the current task if it decides this is appropriate (e.g. for increased |
| 3025 |
efficiency). |
| 3026 |
|
| 3027 |
Equivalent to ``await trio.sleep(0)`` (which is implemented by calling |
| 3028 |
:func:`checkpoint`.) |
| 3029 |
|
| 3030 |
""" |
| 3031 |
# The scheduler is what checks timeouts and converts them into |
| 3032 |
# cancellations. So by doing the schedule point first, we ensure that the |
| 3033 |
# cancel point has the most up-to-date info. |
| 3034 |
await cancel_shielded_checkpoint() |
| 3035 |
task = current_task() |
| 3036 |
task._cancel_points += 1 |
| 3037 |
if task._cancel_status.effectively_cancelled or ( |
| 3038 |
task is task._runner.main_task and task._runner.ki_pending |
| 3039 |
): |
| 3040 |
cs = CancelScope(deadline=-inf) |
| 3041 |
if ( |
| 3042 |
task._cancel_status._scope._cancel_reason is None |
| 3043 |
and task is task._runner.main_task |
| 3044 |
and task._runner.ki_pending |
| 3045 |
): |
| 3046 |
task._cancel_status._scope._cancel_reason = CancelReason( |
| 3047 |
source="KeyboardInterrupt" |
| 3048 |
) |
| 3049 |
assert task._cancel_status._scope._cancel_reason is not None |
| 3050 |
cs._cancel_reason = task._cancel_status._scope._cancel_reason |
| 3051 |
with cs: |
| 3052 |
await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) |
| 3053 |
|
| 3054 |
|
| 3055 |
async def checkpoint_if_cancelled() -> None: |
| 3056 |
"""Issue a :ref:`checkpoint <checkpoints>` if the calling context has been |
| 3057 |
cancelled. |
| 3058 |
|
| 3059 |
Equivalent to (but potentially more efficient than):: |
| 3060 |
|
| 3061 |
if trio.current_effective_deadline() == -inf: |
| 3062 |
await trio.lowlevel.checkpoint() |
| 3063 |
|
| 3064 |
This is either a no-op, or else it allow other tasks to be scheduled and |
| 3065 |
then raises :exc:`trio.Cancelled`. |
| 3066 |
|
| 3067 |
Typically used together with :func:`cancel_shielded_checkpoint`. |
| 3068 |
|
| 3069 |
""" |
| 3070 |
task = current_task() |
| 3071 |
if task._cancel_status.effectively_cancelled or ( |
| 3072 |
task is task._runner.main_task and task._runner.ki_pending |
| 3073 |
): |
| 3074 |
await _core.checkpoint() |
| 3075 |
raise AssertionError("this should never happen") # pragma: no cover |
| 3076 |
task._cancel_points += 1 |
| 3077 |
|
| 3078 |
|
| 3079 |
def in_trio_run() -> bool: |
| 3080 |
"""Check whether we are in a Trio run. |
| 3081 |
This returns `True` if and only if :func:`~trio.current_time` will succeed. |
| 3082 |
|
| 3083 |
See also the discussion of differing ways of :ref:`detecting Trio <trio_contexts>`. |
| 3084 |
""" |
| 3085 |
return hasattr(GLOBAL_RUN_CONTEXT, "runner") |
| 3086 |
|
| 3087 |
|
| 3088 |
def in_trio_task() -> bool: |
| 3089 |
"""Check whether we are in a Trio task. |
| 3090 |
This returns `True` if and only if :func:`~trio.lowlevel.current_task` will succeed. |
| 3091 |
|
| 3092 |
See also the discussion of differing ways of :ref:`detecting Trio <trio_contexts>`. |
| 3093 |
""" |
| 3094 |
return hasattr(GLOBAL_RUN_CONTEXT, "task") |
| 3095 |
|
| 3096 |
|
| 3097 |
# export everything for the documentation |
| 3098 |
if "sphinx.ext.autodoc" in sys.modules: |
| 3099 |
from ._generated_io_epoll import * |
| 3100 |
from ._generated_io_kqueue import * |
| 3101 |
from ._generated_io_windows import * |
| 3102 |
|
| 3103 |
if sys.platform == "win32": |
| 3104 |
from ._generated_io_windows import * |
| 3105 |
from ._io_windows import ( |
| 3106 |
EventResult as EventResult, |
| 3107 |
WindowsIOManager as TheIOManager, |
| 3108 |
_WindowsStatistics as IOStatistics, |
| 3109 |
) |
| 3110 |
elif ( |
| 3111 |
sys.platform == "linux" |
| 3112 |
or sys.platform == "android" |
| 3113 |
or (not TYPE_CHECKING and hasattr(select, "epoll")) |
| 3114 |
): |
| 3115 |
from ._generated_io_epoll import * |
| 3116 |
from ._io_epoll import ( |
| 3117 |
EpollIOManager as TheIOManager, |
| 3118 |
EventResult as EventResult, |
| 3119 |
_EpollStatistics as IOStatistics, |
| 3120 |
) |
| 3121 |
elif TYPE_CHECKING or hasattr(select, "kqueue"): |
| 3122 |
from ._generated_io_kqueue import * |
| 3123 |
from ._io_kqueue import ( |
| 3124 |
EventResult as EventResult, |
| 3125 |
KqueueIOManager as TheIOManager, |
| 3126 |
_KqueueStatistics as IOStatistics, |
| 3127 |
) |
| 3128 |
else: # pragma: no cover |
| 3129 |
_patchers = sorted({"eventlet", "gevent"}.intersection(sys.modules)) |
| 3130 |
if _patchers: |
| 3131 |
raise NotImplementedError( |
| 3132 |
"unsupported platform or primitives Trio depends on are monkey-patched out by " |
| 3133 |
+ ", ".join(_patchers), |
| 3134 |
) |
| 3135 |
|
| 3136 |
raise NotImplementedError("unsupported platform") |
| 3137 |
|
| 3138 |
from ._generated_instrumentation import * |
| 3139 |
from ._generated_run import * |