| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import array |
| 4 |
import asyncio |
| 5 |
import concurrent.futures |
| 6 |
import contextvars |
| 7 |
import math |
| 8 |
import os |
| 9 |
import socket |
| 10 |
import sys |
| 11 |
import threading |
| 12 |
import weakref |
| 13 |
from asyncio import ( |
| 14 |
AbstractEventLoop, |
| 15 |
CancelledError, |
| 16 |
all_tasks, |
| 17 |
create_task, |
| 18 |
current_task, |
| 19 |
get_running_loop, |
| 20 |
sleep, |
| 21 |
) |
| 22 |
from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined] |
| 23 |
from collections import OrderedDict, deque |
| 24 |
from collections.abc import ( |
| 25 |
AsyncGenerator, |
| 26 |
AsyncIterator, |
| 27 |
Awaitable, |
| 28 |
Callable, |
| 29 |
Collection, |
| 30 |
Coroutine, |
| 31 |
Iterable, |
| 32 |
Sequence, |
| 33 |
) |
| 34 |
from concurrent.futures import Future |
| 35 |
from contextlib import AbstractContextManager, suppress |
| 36 |
from contextvars import Context, copy_context |
| 37 |
from dataclasses import dataclass, field |
| 38 |
from functools import partial, wraps |
| 39 |
from inspect import ( |
| 40 |
CORO_RUNNING, |
| 41 |
CORO_SUSPENDED, |
| 42 |
getcoroutinestate, |
| 43 |
iscoroutine, |
| 44 |
) |
| 45 |
from io import IOBase |
| 46 |
from os import PathLike |
| 47 |
from queue import Queue |
| 48 |
from signal import Signals |
| 49 |
from socket import AddressFamily, SocketKind |
| 50 |
from threading import Thread |
| 51 |
from types import CodeType, TracebackType |
| 52 |
from typing import ( |
| 53 |
IO, |
| 54 |
TYPE_CHECKING, |
| 55 |
Any, |
| 56 |
Optional, |
| 57 |
TypeVar, |
| 58 |
cast, |
| 59 |
) |
| 60 |
from weakref import WeakKeyDictionary |
| 61 |
|
| 62 |
from .. import ( |
| 63 |
CapacityLimiterStatistics, |
| 64 |
EventStatistics, |
| 65 |
LockStatistics, |
| 66 |
TaskInfo, |
| 67 |
abc, |
| 68 |
) |
| 69 |
from .._core._eventloop import ( |
| 70 |
claim_worker_thread, |
| 71 |
set_current_async_library, |
| 72 |
threadlocals, |
| 73 |
) |
| 74 |
from .._core._exceptions import ( |
| 75 |
BrokenResourceError, |
| 76 |
BusyResourceError, |
| 77 |
ClosedResourceError, |
| 78 |
EndOfStream, |
| 79 |
RunFinishedError, |
| 80 |
WouldBlock, |
| 81 |
iterate_exceptions, |
| 82 |
) |
| 83 |
from .._core._sockets import convert_ipv6_sockaddr |
| 84 |
from .._core._streams import create_memory_object_stream |
| 85 |
from .._core._synchronization import ( |
| 86 |
CapacityLimiter as BaseCapacityLimiter, |
| 87 |
) |
| 88 |
from .._core._synchronization import Event as BaseEvent |
| 89 |
from .._core._synchronization import Lock as BaseLock |
| 90 |
from .._core._synchronization import ( |
| 91 |
ResourceGuard, |
| 92 |
SemaphoreStatistics, |
| 93 |
) |
| 94 |
from .._core._synchronization import Semaphore as BaseSemaphore |
| 95 |
from .._core._tasks import CancelScope as BaseCancelScope |
| 96 |
from ..abc import ( |
| 97 |
AsyncBackend, |
| 98 |
IPSockAddrType, |
| 99 |
SocketListener, |
| 100 |
UDPPacketType, |
| 101 |
UNIXDatagramPacketType, |
| 102 |
) |
| 103 |
from ..abc._eventloop import StrOrBytesPath |
| 104 |
from ..lowlevel import RunVar |
| 105 |
from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream |
| 106 |
|
| 107 |
if TYPE_CHECKING: |
| 108 |
from _typeshed import FileDescriptorLike |
| 109 |
else: |
| 110 |
FileDescriptorLike = object |
| 111 |
|
| 112 |
if sys.version_info >= (3, 10): |
| 113 |
from typing import ParamSpec |
| 114 |
else: |
| 115 |
from typing_extensions import ParamSpec |
| 116 |
|
| 117 |
if sys.version_info >= (3, 11): |
| 118 |
from asyncio import Runner |
| 119 |
from typing import TypeVarTuple, Unpack |
| 120 |
else: |
| 121 |
import contextvars |
| 122 |
import enum |
| 123 |
import signal |
| 124 |
from asyncio import coroutines, events, exceptions, tasks |
| 125 |
|
| 126 |
from exceptiongroup import BaseExceptionGroup |
| 127 |
from typing_extensions import TypeVarTuple, Unpack |
| 128 |
|
| 129 |
class _State(enum.Enum): |
| 130 |
CREATED = "created" |
| 131 |
INITIALIZED = "initialized" |
| 132 |
CLOSED = "closed" |
| 133 |
|
| 134 |
class Runner: |
| 135 |
# Copied from CPython 3.11 |
| 136 |
def __init__( |
| 137 |
self, |
| 138 |
*, |
| 139 |
debug: bool | None = None, |
| 140 |
loop_factory: Callable[[], AbstractEventLoop] | None = None, |
| 141 |
): |
| 142 |
self._state = _State.CREATED |
| 143 |
self._debug = debug |
| 144 |
self._loop_factory = loop_factory |
| 145 |
self._loop: AbstractEventLoop | None = None |
| 146 |
self._context = None |
| 147 |
self._interrupt_count = 0 |
| 148 |
self._set_event_loop = False |
| 149 |
|
| 150 |
def __enter__(self) -> Runner: |
| 151 |
self._lazy_init() |
| 152 |
return self |
| 153 |
|
| 154 |
def __exit__( |
| 155 |
self, |
| 156 |
exc_type: type[BaseException] | None, |
| 157 |
exc_val: BaseException | None, |
| 158 |
exc_tb: TracebackType | None, |
| 159 |
) -> None: |
| 160 |
self.close() |
| 161 |
|
| 162 |
def close(self) -> None: |
| 163 |
"""Shutdown and close event loop.""" |
| 164 |
loop = self._loop |
| 165 |
if self._state is not _State.INITIALIZED or loop is None: |
| 166 |
return |
| 167 |
try: |
| 168 |
_cancel_all_tasks(loop) |
| 169 |
loop.run_until_complete(loop.shutdown_asyncgens()) |
| 170 |
if hasattr(loop, "shutdown_default_executor"): |
| 171 |
loop.run_until_complete(loop.shutdown_default_executor()) |
| 172 |
else: |
| 173 |
loop.run_until_complete(_shutdown_default_executor(loop)) |
| 174 |
finally: |
| 175 |
if self._set_event_loop: |
| 176 |
events.set_event_loop(None) |
| 177 |
loop.close() |
| 178 |
self._loop = None |
| 179 |
self._state = _State.CLOSED |
| 180 |
|
| 181 |
def get_loop(self) -> AbstractEventLoop: |
| 182 |
"""Return embedded event loop.""" |
| 183 |
self._lazy_init() |
| 184 |
return self._loop |
| 185 |
|
| 186 |
def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval: |
| 187 |
"""Run a coroutine inside the embedded event loop.""" |
| 188 |
if not coroutines.iscoroutine(coro): |
| 189 |
raise ValueError(f"a coroutine was expected, got {coro!r}") |
| 190 |
|
| 191 |
if events._get_running_loop() is not None: |
| 192 |
# fail fast with short traceback |
| 193 |
raise RuntimeError( |
| 194 |
"Runner.run() cannot be called from a running event loop" |
| 195 |
) |
| 196 |
|
| 197 |
self._lazy_init() |
| 198 |
|
| 199 |
if context is None: |
| 200 |
context = self._context |
| 201 |
task = context.run(self._loop.create_task, coro) |
| 202 |
|
| 203 |
if ( |
| 204 |
threading.current_thread() is threading.main_thread() |
| 205 |
and signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 206 |
): |
| 207 |
sigint_handler = partial(self._on_sigint, main_task=task) |
| 208 |
try: |
| 209 |
signal.signal(signal.SIGINT, sigint_handler) |
| 210 |
except ValueError: |
| 211 |
# `signal.signal` may throw if `threading.main_thread` does |
| 212 |
# not support signals (e.g. embedded interpreter with signals |
| 213 |
# not registered - see gh-91880) |
| 214 |
sigint_handler = None |
| 215 |
else: |
| 216 |
sigint_handler = None |
| 217 |
|
| 218 |
self._interrupt_count = 0 |
| 219 |
try: |
| 220 |
return self._loop.run_until_complete(task) |
| 221 |
except exceptions.CancelledError: |
| 222 |
if self._interrupt_count > 0: |
| 223 |
uncancel = getattr(task, "uncancel", None) |
| 224 |
if uncancel is not None and uncancel() == 0: |
| 225 |
raise KeyboardInterrupt # noqa: B904 |
| 226 |
raise # CancelledError |
| 227 |
finally: |
| 228 |
if ( |
| 229 |
sigint_handler is not None |
| 230 |
and signal.getsignal(signal.SIGINT) is sigint_handler |
| 231 |
): |
| 232 |
signal.signal(signal.SIGINT, signal.default_int_handler) |
| 233 |
|
| 234 |
def _lazy_init(self) -> None: |
| 235 |
if self._state is _State.CLOSED: |
| 236 |
raise RuntimeError("Runner is closed") |
| 237 |
if self._state is _State.INITIALIZED: |
| 238 |
return |
| 239 |
if self._loop_factory is None: |
| 240 |
self._loop = events.new_event_loop() |
| 241 |
if not self._set_event_loop: |
| 242 |
# Call set_event_loop only once to avoid calling |
| 243 |
# attach_loop multiple times on child watchers |
| 244 |
events.set_event_loop(self._loop) |
| 245 |
self._set_event_loop = True |
| 246 |
else: |
| 247 |
self._loop = self._loop_factory() |
| 248 |
if self._debug is not None: |
| 249 |
self._loop.set_debug(self._debug) |
| 250 |
self._context = contextvars.copy_context() |
| 251 |
self._state = _State.INITIALIZED |
| 252 |
|
| 253 |
def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None: |
| 254 |
self._interrupt_count += 1 |
| 255 |
if self._interrupt_count == 1 and not main_task.done(): |
| 256 |
main_task.cancel() |
| 257 |
# wakeup loop if it is blocked by select() with long timeout |
| 258 |
self._loop.call_soon_threadsafe(lambda: None) |
| 259 |
return |
| 260 |
raise KeyboardInterrupt() |
| 261 |
|
| 262 |
def _cancel_all_tasks(loop: AbstractEventLoop) -> None: |
| 263 |
to_cancel = tasks.all_tasks(loop) |
| 264 |
if not to_cancel: |
| 265 |
return |
| 266 |
|
| 267 |
for task in to_cancel: |
| 268 |
task.cancel() |
| 269 |
|
| 270 |
loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True)) |
| 271 |
|
| 272 |
for task in to_cancel: |
| 273 |
if task.cancelled(): |
| 274 |
continue |
| 275 |
if task.exception() is not None: |
| 276 |
loop.call_exception_handler( |
| 277 |
{ |
| 278 |
"message": "unhandled exception during asyncio.run() shutdown", |
| 279 |
"exception": task.exception(), |
| 280 |
"task": task, |
| 281 |
} |
| 282 |
) |
| 283 |
|
| 284 |
async def _shutdown_default_executor(loop: AbstractEventLoop) -> None: |
| 285 |
"""Schedule the shutdown of the default executor.""" |
| 286 |
|
| 287 |
def _do_shutdown(future: asyncio.futures.Future) -> None: |
| 288 |
try: |
| 289 |
loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined] |
| 290 |
loop.call_soon_threadsafe(future.set_result, None) |
| 291 |
except Exception as ex: |
| 292 |
loop.call_soon_threadsafe(future.set_exception, ex) |
| 293 |
|
| 294 |
loop._executor_shutdown_called = True |
| 295 |
if loop._default_executor is None: |
| 296 |
return |
| 297 |
future = loop.create_future() |
| 298 |
thread = threading.Thread(target=_do_shutdown, args=(future,)) |
| 299 |
thread.start() |
| 300 |
try: |
| 301 |
await future |
| 302 |
finally: |
| 303 |
thread.join() |
| 304 |
|
| 305 |
|
| 306 |
T_Retval = TypeVar("T_Retval") |
| 307 |
T_contra = TypeVar("T_contra", contravariant=True) |
| 308 |
PosArgsT = TypeVarTuple("PosArgsT") |
| 309 |
P = ParamSpec("P") |
| 310 |
|
| 311 |
_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task") |
| 312 |
|
| 313 |
|
| 314 |
def find_root_task() -> asyncio.Task: |
| 315 |
root_task = _root_task.get(None) |
| 316 |
if root_task is not None and not root_task.done(): |
| 317 |
return root_task |
| 318 |
|
| 319 |
# Look for a task that has been started via run_until_complete() |
| 320 |
for task in all_tasks(): |
| 321 |
if task._callbacks and not task.done(): |
| 322 |
callbacks = [cb for cb, context in task._callbacks] |
| 323 |
for cb in callbacks: |
| 324 |
if ( |
| 325 |
cb is _run_until_complete_cb |
| 326 |
or getattr(cb, "__module__", None) == "uvloop.loop" |
| 327 |
): |
| 328 |
_root_task.set(task) |
| 329 |
return task |
| 330 |
|
| 331 |
# Look up the topmost task in the AnyIO task tree, if possible |
| 332 |
task = cast(asyncio.Task, current_task()) |
| 333 |
state = _task_states.get(task) |
| 334 |
if state: |
| 335 |
cancel_scope = state.cancel_scope |
| 336 |
while cancel_scope and cancel_scope._parent_scope is not None: |
| 337 |
cancel_scope = cancel_scope._parent_scope |
| 338 |
|
| 339 |
if cancel_scope is not None: |
| 340 |
return cast(asyncio.Task, cancel_scope._host_task) |
| 341 |
|
| 342 |
return task |
| 343 |
|
| 344 |
|
| 345 |
def get_callable_name(func: Callable) -> str: |
| 346 |
module = getattr(func, "__module__", None) |
| 347 |
qualname = getattr(func, "__qualname__", None) |
| 348 |
return ".".join([x for x in (module, qualname) if x]) |
| 349 |
|
| 350 |
|
| 351 |
# |
| 352 |
# Event loop |
| 353 |
# |
| 354 |
|
| 355 |
_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary() |
| 356 |
|
| 357 |
|
| 358 |
def _task_started(task: asyncio.Task) -> bool: |
| 359 |
"""Return ``True`` if the task has been started and has not finished.""" |
| 360 |
# The task coro should never be None here, as we never add finished tasks to the |
| 361 |
# task list |
| 362 |
coro = task.get_coro() |
| 363 |
assert coro is not None |
| 364 |
try: |
| 365 |
return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED) |
| 366 |
except AttributeError: |
| 367 |
# task coro is async_genenerator_asend https://bugs.python.org/issue37771 |
| 368 |
raise Exception(f"Cannot determine if task {task} has started or not") from None |
| 369 |
|
| 370 |
|
| 371 |
# |
| 372 |
# Timeouts and cancellation |
| 373 |
# |
| 374 |
|
| 375 |
|
| 376 |
def is_anyio_cancellation(exc: CancelledError) -> bool: |
| 377 |
# Sometimes third party frameworks catch a CancelledError and raise a new one, so as |
| 378 |
# a workaround we have to look at the previous ones in __context__ too for a |
| 379 |
# matching cancel message |
| 380 |
while True: |
| 381 |
if ( |
| 382 |
exc.args |
| 383 |
and isinstance(exc.args[0], str) |
| 384 |
and exc.args[0].startswith("Cancelled via cancel scope ") |
| 385 |
): |
| 386 |
return True |
| 387 |
|
| 388 |
if isinstance(exc.__context__, CancelledError): |
| 389 |
exc = exc.__context__ |
| 390 |
continue |
| 391 |
|
| 392 |
return False |
| 393 |
|
| 394 |
|
| 395 |
class CancelScope(BaseCancelScope): |
| 396 |
def __new__( |
| 397 |
cls, *, deadline: float = math.inf, shield: bool = False |
| 398 |
) -> CancelScope: |
| 399 |
return object.__new__(cls) |
| 400 |
|
| 401 |
def __init__(self, deadline: float = math.inf, shield: bool = False): |
| 402 |
self._deadline = deadline |
| 403 |
self._shield = shield |
| 404 |
self._parent_scope: CancelScope | None = None |
| 405 |
self._child_scopes: set[CancelScope] = set() |
| 406 |
self._cancel_called = False |
| 407 |
self._cancel_reason: str | None = None |
| 408 |
self._cancelled_caught = False |
| 409 |
self._active = False |
| 410 |
self._timeout_handle: asyncio.TimerHandle | None = None |
| 411 |
self._cancel_handle: asyncio.Handle | None = None |
| 412 |
self._tasks: set[asyncio.Task] = set() |
| 413 |
self._host_task: asyncio.Task | None = None |
| 414 |
if sys.version_info >= (3, 11): |
| 415 |
self._pending_uncancellations: int | None = 0 |
| 416 |
else: |
| 417 |
self._pending_uncancellations = None |
| 418 |
|
| 419 |
def __enter__(self) -> CancelScope: |
| 420 |
if self._active: |
| 421 |
raise RuntimeError( |
| 422 |
"Each CancelScope may only be used for a single 'with' block" |
| 423 |
) |
| 424 |
|
| 425 |
self._host_task = host_task = cast(asyncio.Task, current_task()) |
| 426 |
self._tasks.add(host_task) |
| 427 |
try: |
| 428 |
task_state = _task_states[host_task] |
| 429 |
except KeyError: |
| 430 |
task_state = TaskState(None, self) |
| 431 |
_task_states[host_task] = task_state |
| 432 |
else: |
| 433 |
self._parent_scope = task_state.cancel_scope |
| 434 |
task_state.cancel_scope = self |
| 435 |
if self._parent_scope is not None: |
| 436 |
# If using an eager task factory, the parent scope may not even contain |
| 437 |
# the host task |
| 438 |
self._parent_scope._child_scopes.add(self) |
| 439 |
self._parent_scope._tasks.discard(host_task) |
| 440 |
|
| 441 |
self._timeout() |
| 442 |
self._active = True |
| 443 |
|
| 444 |
# Start cancelling the host task if the scope was cancelled before entering |
| 445 |
if self._cancel_called: |
| 446 |
self._deliver_cancellation(self) |
| 447 |
|
| 448 |
return self |
| 449 |
|
| 450 |
def __exit__( |
| 451 |
self, |
| 452 |
exc_type: type[BaseException] | None, |
| 453 |
exc_val: BaseException | None, |
| 454 |
exc_tb: TracebackType | None, |
| 455 |
) -> bool: |
| 456 |
del exc_tb |
| 457 |
|
| 458 |
if not self._active: |
| 459 |
raise RuntimeError("This cancel scope is not active") |
| 460 |
if current_task() is not self._host_task: |
| 461 |
raise RuntimeError( |
| 462 |
"Attempted to exit cancel scope in a different task than it was " |
| 463 |
"entered in" |
| 464 |
) |
| 465 |
|
| 466 |
assert self._host_task is not None |
| 467 |
host_task_state = _task_states.get(self._host_task) |
| 468 |
if host_task_state is None or host_task_state.cancel_scope is not self: |
| 469 |
raise RuntimeError( |
| 470 |
"Attempted to exit a cancel scope that isn't the current tasks's " |
| 471 |
"current cancel scope" |
| 472 |
) |
| 473 |
|
| 474 |
try: |
| 475 |
self._active = False |
| 476 |
if self._timeout_handle: |
| 477 |
self._timeout_handle.cancel() |
| 478 |
self._timeout_handle = None |
| 479 |
|
| 480 |
self._tasks.remove(self._host_task) |
| 481 |
if self._parent_scope is not None: |
| 482 |
self._parent_scope._child_scopes.remove(self) |
| 483 |
self._parent_scope._tasks.add(self._host_task) |
| 484 |
|
| 485 |
host_task_state.cancel_scope = self._parent_scope |
| 486 |
|
| 487 |
# Restart the cancellation effort in the closest visible, cancelled parent |
| 488 |
# scope if necessary |
| 489 |
self._restart_cancellation_in_parent() |
| 490 |
|
| 491 |
# We only swallow the exception iff it was an AnyIO CancelledError, either |
| 492 |
# directly as exc_val or inside an exception group and there are no cancelled |
| 493 |
# parent cancel scopes visible to us here |
| 494 |
if self._cancel_called and not self._parent_cancellation_is_visible_to_us: |
| 495 |
# For each level-cancel() call made on the host task, call uncancel() |
| 496 |
while self._pending_uncancellations: |
| 497 |
self._host_task.uncancel() |
| 498 |
self._pending_uncancellations -= 1 |
| 499 |
|
| 500 |
# Update cancelled_caught and check for exceptions we must not swallow |
| 501 |
cannot_swallow_exc_val = False |
| 502 |
if exc_val is not None: |
| 503 |
for exc in iterate_exceptions(exc_val): |
| 504 |
if isinstance(exc, CancelledError) and is_anyio_cancellation( |
| 505 |
exc |
| 506 |
): |
| 507 |
self._cancelled_caught = True |
| 508 |
else: |
| 509 |
cannot_swallow_exc_val = True |
| 510 |
|
| 511 |
return self._cancelled_caught and not cannot_swallow_exc_val |
| 512 |
else: |
| 513 |
if self._pending_uncancellations: |
| 514 |
assert self._parent_scope is not None |
| 515 |
assert self._parent_scope._pending_uncancellations is not None |
| 516 |
self._parent_scope._pending_uncancellations += ( |
| 517 |
self._pending_uncancellations |
| 518 |
) |
| 519 |
self._pending_uncancellations = 0 |
| 520 |
|
| 521 |
return False |
| 522 |
finally: |
| 523 |
self._host_task = None |
| 524 |
del exc_val |
| 525 |
|
| 526 |
@property |
| 527 |
def _effectively_cancelled(self) -> bool: |
| 528 |
cancel_scope: CancelScope | None = self |
| 529 |
while cancel_scope is not None: |
| 530 |
if cancel_scope._cancel_called: |
| 531 |
return True |
| 532 |
|
| 533 |
if cancel_scope.shield: |
| 534 |
return False |
| 535 |
|
| 536 |
cancel_scope = cancel_scope._parent_scope |
| 537 |
|
| 538 |
return False |
| 539 |
|
| 540 |
@property |
| 541 |
def _parent_cancellation_is_visible_to_us(self) -> bool: |
| 542 |
return ( |
| 543 |
self._parent_scope is not None |
| 544 |
and not self.shield |
| 545 |
and self._parent_scope._effectively_cancelled |
| 546 |
) |
| 547 |
|
| 548 |
def _timeout(self) -> None: |
| 549 |
if self._deadline != math.inf: |
| 550 |
loop = get_running_loop() |
| 551 |
if loop.time() >= self._deadline: |
| 552 |
self.cancel("deadline exceeded") |
| 553 |
else: |
| 554 |
self._timeout_handle = loop.call_at(self._deadline, self._timeout) |
| 555 |
|
| 556 |
def _deliver_cancellation(self, origin: CancelScope) -> bool: |
| 557 |
""" |
| 558 |
Deliver cancellation to directly contained tasks and nested cancel scopes. |
| 559 |
|
| 560 |
Schedule another run at the end if we still have tasks eligible for |
| 561 |
cancellation. |
| 562 |
|
| 563 |
:param origin: the cancel scope that originated the cancellation |
| 564 |
:return: ``True`` if the delivery needs to be retried on the next cycle |
| 565 |
|
| 566 |
""" |
| 567 |
should_retry = False |
| 568 |
current = current_task() |
| 569 |
for task in self._tasks: |
| 570 |
should_retry = True |
| 571 |
if task._must_cancel: # type: ignore[attr-defined] |
| 572 |
continue |
| 573 |
|
| 574 |
# The task is eligible for cancellation if it has started |
| 575 |
if task is not current and (task is self._host_task or _task_started(task)): |
| 576 |
waiter = task._fut_waiter # type: ignore[attr-defined] |
| 577 |
if not isinstance(waiter, asyncio.Future) or not waiter.done(): |
| 578 |
task.cancel(origin._cancel_reason) |
| 579 |
if ( |
| 580 |
task is origin._host_task |
| 581 |
and origin._pending_uncancellations is not None |
| 582 |
): |
| 583 |
origin._pending_uncancellations += 1 |
| 584 |
|
| 585 |
# Deliver cancellation to child scopes that aren't shielded or running their own |
| 586 |
# cancellation callbacks |
| 587 |
for scope in self._child_scopes: |
| 588 |
if not scope._shield and not scope.cancel_called: |
| 589 |
should_retry = scope._deliver_cancellation(origin) or should_retry |
| 590 |
|
| 591 |
# Schedule another callback if there are still tasks left |
| 592 |
if origin is self: |
| 593 |
if should_retry: |
| 594 |
self._cancel_handle = get_running_loop().call_soon( |
| 595 |
self._deliver_cancellation, origin |
| 596 |
) |
| 597 |
else: |
| 598 |
self._cancel_handle = None |
| 599 |
|
| 600 |
return should_retry |
| 601 |
|
| 602 |
def _restart_cancellation_in_parent(self) -> None: |
| 603 |
""" |
| 604 |
Restart the cancellation effort in the closest directly cancelled parent scope. |
| 605 |
|
| 606 |
""" |
| 607 |
scope = self._parent_scope |
| 608 |
while scope is not None: |
| 609 |
if scope._cancel_called: |
| 610 |
if scope._cancel_handle is None: |
| 611 |
scope._deliver_cancellation(scope) |
| 612 |
|
| 613 |
break |
| 614 |
|
| 615 |
# No point in looking beyond any shielded scope |
| 616 |
if scope._shield: |
| 617 |
break |
| 618 |
|
| 619 |
scope = scope._parent_scope |
| 620 |
|
| 621 |
def cancel(self, reason: str | None = None) -> None: |
| 622 |
if not self._cancel_called: |
| 623 |
if self._timeout_handle: |
| 624 |
self._timeout_handle.cancel() |
| 625 |
self._timeout_handle = None |
| 626 |
|
| 627 |
self._cancel_called = True |
| 628 |
self._cancel_reason = f"Cancelled via cancel scope {id(self):x}" |
| 629 |
if task := current_task(): |
| 630 |
self._cancel_reason += f" by {task}" |
| 631 |
|
| 632 |
if reason: |
| 633 |
self._cancel_reason += f"; reason: {reason}" |
| 634 |
|
| 635 |
if self._host_task is not None: |
| 636 |
self._deliver_cancellation(self) |
| 637 |
|
| 638 |
@property |
| 639 |
def deadline(self) -> float: |
| 640 |
return self._deadline |
| 641 |
|
| 642 |
@deadline.setter |
| 643 |
def deadline(self, value: float) -> None: |
| 644 |
self._deadline = float(value) |
| 645 |
if self._timeout_handle is not None: |
| 646 |
self._timeout_handle.cancel() |
| 647 |
self._timeout_handle = None |
| 648 |
|
| 649 |
if self._active and not self._cancel_called: |
| 650 |
self._timeout() |
| 651 |
|
| 652 |
@property |
| 653 |
def cancel_called(self) -> bool: |
| 654 |
return self._cancel_called |
| 655 |
|
| 656 |
@property |
| 657 |
def cancelled_caught(self) -> bool: |
| 658 |
return self._cancelled_caught |
| 659 |
|
| 660 |
@property |
| 661 |
def shield(self) -> bool: |
| 662 |
return self._shield |
| 663 |
|
| 664 |
@shield.setter |
| 665 |
def shield(self, value: bool) -> None: |
| 666 |
if self._shield != value: |
| 667 |
self._shield = value |
| 668 |
if not value: |
| 669 |
self._restart_cancellation_in_parent() |
| 670 |
|
| 671 |
|
| 672 |
# |
| 673 |
# Task states |
| 674 |
# |
| 675 |
|
| 676 |
|
| 677 |
class TaskState: |
| 678 |
""" |
| 679 |
Encapsulates auxiliary task information that cannot be added to the Task instance |
| 680 |
itself because there are no guarantees about its implementation. |
| 681 |
""" |
| 682 |
|
| 683 |
__slots__ = "parent_id", "cancel_scope", "__weakref__" |
| 684 |
|
| 685 |
def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None): |
| 686 |
self.parent_id = parent_id |
| 687 |
self.cancel_scope = cancel_scope |
| 688 |
|
| 689 |
|
| 690 |
_task_states: WeakKeyDictionary[asyncio.Task, TaskState] = WeakKeyDictionary() |
| 691 |
|
| 692 |
|
| 693 |
# |
| 694 |
# Task groups |
| 695 |
# |
| 696 |
|
| 697 |
|
| 698 |
class _AsyncioTaskStatus(abc.TaskStatus): |
| 699 |
def __init__(self, future: asyncio.Future, parent_id: int): |
| 700 |
self._future = future |
| 701 |
self._parent_id = parent_id |
| 702 |
|
| 703 |
def started(self, value: T_contra | None = None) -> None: |
| 704 |
try: |
| 705 |
self._future.set_result(value) |
| 706 |
except asyncio.InvalidStateError: |
| 707 |
if not self._future.cancelled(): |
| 708 |
raise RuntimeError( |
| 709 |
"called 'started' twice on the same task status" |
| 710 |
) from None |
| 711 |
|
| 712 |
task = cast(asyncio.Task, current_task()) |
| 713 |
_task_states[task].parent_id = self._parent_id |
| 714 |
|
| 715 |
|
| 716 |
if sys.version_info >= (3, 12): |
| 717 |
_eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__ |
| 718 |
else: |
| 719 |
_eager_task_factory_code = None |
| 720 |
|
| 721 |
|
| 722 |
class TaskGroup(abc.TaskGroup): |
| 723 |
def __init__(self) -> None: |
| 724 |
self.cancel_scope: CancelScope = CancelScope() |
| 725 |
self._active = False |
| 726 |
self._exceptions: list[BaseException] = [] |
| 727 |
self._tasks: set[asyncio.Task] = set() |
| 728 |
self._on_completed_fut: asyncio.Future[None] | None = None |
| 729 |
|
| 730 |
async def __aenter__(self) -> TaskGroup: |
| 731 |
self.cancel_scope.__enter__() |
| 732 |
self._active = True |
| 733 |
return self |
| 734 |
|
| 735 |
async def __aexit__( |
| 736 |
self, |
| 737 |
exc_type: type[BaseException] | None, |
| 738 |
exc_val: BaseException | None, |
| 739 |
exc_tb: TracebackType | None, |
| 740 |
) -> bool: |
| 741 |
try: |
| 742 |
if exc_val is not None: |
| 743 |
self.cancel_scope.cancel() |
| 744 |
if not isinstance(exc_val, CancelledError): |
| 745 |
self._exceptions.append(exc_val) |
| 746 |
|
| 747 |
loop = get_running_loop() |
| 748 |
try: |
| 749 |
if self._tasks: |
| 750 |
with CancelScope() as wait_scope: |
| 751 |
while self._tasks: |
| 752 |
self._on_completed_fut = loop.create_future() |
| 753 |
|
| 754 |
try: |
| 755 |
await self._on_completed_fut |
| 756 |
except CancelledError as exc: |
| 757 |
# Shield the scope against further cancellation attempts, |
| 758 |
# as they're not productive (#695) |
| 759 |
wait_scope.shield = True |
| 760 |
self.cancel_scope.cancel() |
| 761 |
|
| 762 |
# Set exc_val from the cancellation exception if it was |
| 763 |
# previously unset. However, we should not replace a native |
| 764 |
# cancellation exception with one raise by a cancel scope. |
| 765 |
if exc_val is None or ( |
| 766 |
isinstance(exc_val, CancelledError) |
| 767 |
and not is_anyio_cancellation(exc) |
| 768 |
): |
| 769 |
exc_val = exc |
| 770 |
|
| 771 |
self._on_completed_fut = None |
| 772 |
else: |
| 773 |
# If there are no child tasks to wait on, run at least one checkpoint |
| 774 |
# anyway |
| 775 |
await AsyncIOBackend.cancel_shielded_checkpoint() |
| 776 |
|
| 777 |
self._active = False |
| 778 |
if self._exceptions: |
| 779 |
# The exception that got us here should already have been |
| 780 |
# added to self._exceptions so it's ok to break exception |
| 781 |
# chaining and avoid adding a "During handling of above..." |
| 782 |
# for each nesting level. |
| 783 |
raise BaseExceptionGroup( |
| 784 |
"unhandled errors in a TaskGroup", self._exceptions |
| 785 |
) from None |
| 786 |
elif exc_val: |
| 787 |
raise exc_val |
| 788 |
except BaseException as exc: |
| 789 |
if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): |
| 790 |
return True |
| 791 |
|
| 792 |
raise |
| 793 |
|
| 794 |
return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb) |
| 795 |
finally: |
| 796 |
del exc_val, exc_tb, self._exceptions |
| 797 |
|
| 798 |
def _spawn( |
| 799 |
self, |
| 800 |
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], |
| 801 |
args: tuple[Unpack[PosArgsT]], |
| 802 |
name: object, |
| 803 |
task_status_future: asyncio.Future | None = None, |
| 804 |
) -> asyncio.Task: |
| 805 |
def task_done(_task: asyncio.Task) -> None: |
| 806 |
if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: |
| 807 |
asyncio.future_discard_from_awaited_by( |
| 808 |
_task, self.cancel_scope._host_task |
| 809 |
) |
| 810 |
|
| 811 |
task_state = _task_states[_task] |
| 812 |
assert task_state.cancel_scope is not None |
| 813 |
assert _task in task_state.cancel_scope._tasks |
| 814 |
task_state.cancel_scope._tasks.remove(_task) |
| 815 |
self._tasks.remove(task) |
| 816 |
del _task_states[_task] |
| 817 |
|
| 818 |
if self._on_completed_fut is not None and not self._tasks: |
| 819 |
try: |
| 820 |
self._on_completed_fut.set_result(None) |
| 821 |
except asyncio.InvalidStateError: |
| 822 |
pass |
| 823 |
|
| 824 |
try: |
| 825 |
exc = _task.exception() |
| 826 |
except CancelledError as e: |
| 827 |
while isinstance(e.__context__, CancelledError): |
| 828 |
e = e.__context__ |
| 829 |
|
| 830 |
exc = e |
| 831 |
|
| 832 |
if exc is not None: |
| 833 |
# The future can only be in the cancelled state if the host task was |
| 834 |
# cancelled, so return immediately instead of adding one more |
| 835 |
# CancelledError to the exceptions list |
| 836 |
if task_status_future is not None and task_status_future.cancelled(): |
| 837 |
return |
| 838 |
|
| 839 |
if task_status_future is None or task_status_future.done(): |
| 840 |
if not isinstance(exc, CancelledError): |
| 841 |
self._exceptions.append(exc) |
| 842 |
|
| 843 |
if not self.cancel_scope._effectively_cancelled: |
| 844 |
self.cancel_scope.cancel() |
| 845 |
else: |
| 846 |
task_status_future.set_exception(exc) |
| 847 |
elif task_status_future is not None and not task_status_future.done(): |
| 848 |
task_status_future.set_exception( |
| 849 |
RuntimeError("Child exited without calling task_status.started()") |
| 850 |
) |
| 851 |
|
| 852 |
if not self._active: |
| 853 |
raise RuntimeError( |
| 854 |
"This task group is not active; no new tasks can be started." |
| 855 |
) |
| 856 |
|
| 857 |
kwargs = {} |
| 858 |
if task_status_future: |
| 859 |
parent_id = id(current_task()) |
| 860 |
kwargs["task_status"] = _AsyncioTaskStatus( |
| 861 |
task_status_future, id(self.cancel_scope._host_task) |
| 862 |
) |
| 863 |
else: |
| 864 |
parent_id = id(self.cancel_scope._host_task) |
| 865 |
|
| 866 |
coro = func(*args, **kwargs) |
| 867 |
if not iscoroutine(coro): |
| 868 |
prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" |
| 869 |
raise TypeError( |
| 870 |
f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " |
| 871 |
f"the return value ({coro!r}) is not a coroutine object" |
| 872 |
) |
| 873 |
|
| 874 |
name = get_callable_name(func) if name is None else str(name) |
| 875 |
loop = asyncio.get_running_loop() |
| 876 |
if ( |
| 877 |
(factory := loop.get_task_factory()) |
| 878 |
and getattr(factory, "__code__", None) is _eager_task_factory_code |
| 879 |
and (closure := getattr(factory, "__closure__", None)) |
| 880 |
): |
| 881 |
custom_task_constructor = closure[0].cell_contents |
| 882 |
task = custom_task_constructor(coro, loop=loop, name=name) |
| 883 |
else: |
| 884 |
task = create_task(coro, name=name) |
| 885 |
|
| 886 |
# Make the spawned task inherit the task group's cancel scope |
| 887 |
_task_states[task] = TaskState( |
| 888 |
parent_id=parent_id, cancel_scope=self.cancel_scope |
| 889 |
) |
| 890 |
self.cancel_scope._tasks.add(task) |
| 891 |
self._tasks.add(task) |
| 892 |
if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: |
| 893 |
asyncio.future_add_to_awaited_by(task, self.cancel_scope._host_task) |
| 894 |
|
| 895 |
task.add_done_callback(task_done) |
| 896 |
return task |
| 897 |
|
| 898 |
def start_soon( |
| 899 |
self, |
| 900 |
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], |
| 901 |
*args: Unpack[PosArgsT], |
| 902 |
name: object = None, |
| 903 |
) -> None: |
| 904 |
self._spawn(func, args, name) |
| 905 |
|
| 906 |
async def start( |
| 907 |
self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None |
| 908 |
) -> Any: |
| 909 |
future: asyncio.Future = asyncio.Future() |
| 910 |
task = self._spawn(func, args, name, future) |
| 911 |
|
| 912 |
# If the task raises an exception after sending a start value without a switch |
| 913 |
# point between, the task group is cancelled and this method never proceeds to |
| 914 |
# process the completed future. That's why we have to have a shielded cancel |
| 915 |
# scope here. |
| 916 |
try: |
| 917 |
return await future |
| 918 |
except CancelledError: |
| 919 |
# Cancel the task and wait for it to exit before returning |
| 920 |
task.cancel() |
| 921 |
with CancelScope(shield=True), suppress(CancelledError): |
| 922 |
await task |
| 923 |
|
| 924 |
raise |
| 925 |
|
| 926 |
|
| 927 |
# |
| 928 |
# Threads |
| 929 |
# |
| 930 |
|
| 931 |
_Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]] |
| 932 |
|
| 933 |
|
| 934 |
class WorkerThread(Thread): |
| 935 |
MAX_IDLE_TIME = 10 # seconds |
| 936 |
|
| 937 |
def __init__( |
| 938 |
self, |
| 939 |
root_task: asyncio.Task, |
| 940 |
workers: set[WorkerThread], |
| 941 |
idle_workers: deque[WorkerThread], |
| 942 |
): |
| 943 |
super().__init__(name="AnyIO worker thread") |
| 944 |
self.root_task = root_task |
| 945 |
self.workers = workers |
| 946 |
self.idle_workers = idle_workers |
| 947 |
self.loop = root_task._loop |
| 948 |
self.queue: Queue[ |
| 949 |
tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None |
| 950 |
] = Queue(2) |
| 951 |
self.idle_since = AsyncIOBackend.current_time() |
| 952 |
self.stopping = False |
| 953 |
|
| 954 |
def _report_result( |
| 955 |
self, future: asyncio.Future, result: Any, exc: BaseException | None |
| 956 |
) -> None: |
| 957 |
self.idle_since = AsyncIOBackend.current_time() |
| 958 |
if not self.stopping: |
| 959 |
self.idle_workers.append(self) |
| 960 |
|
| 961 |
if not future.cancelled(): |
| 962 |
if exc is not None: |
| 963 |
if isinstance(exc, StopIteration): |
| 964 |
new_exc = RuntimeError("coroutine raised StopIteration") |
| 965 |
new_exc.__cause__ = exc |
| 966 |
exc = new_exc |
| 967 |
|
| 968 |
future.set_exception(exc) |
| 969 |
else: |
| 970 |
future.set_result(result) |
| 971 |
|
| 972 |
def run(self) -> None: |
| 973 |
with claim_worker_thread(AsyncIOBackend, self.loop): |
| 974 |
while True: |
| 975 |
item = self.queue.get() |
| 976 |
if item is None: |
| 977 |
# Shutdown command received |
| 978 |
return |
| 979 |
|
| 980 |
context, func, args, future, cancel_scope = item |
| 981 |
if not future.cancelled(): |
| 982 |
result = None |
| 983 |
exception: BaseException | None = None |
| 984 |
threadlocals.current_cancel_scope = cancel_scope |
| 985 |
try: |
| 986 |
result = context.run(func, *args) |
| 987 |
except BaseException as exc: |
| 988 |
exception = exc |
| 989 |
finally: |
| 990 |
del threadlocals.current_cancel_scope |
| 991 |
|
| 992 |
if not self.loop.is_closed(): |
| 993 |
self.loop.call_soon_threadsafe( |
| 994 |
self._report_result, future, result, exception |
| 995 |
) |
| 996 |
|
| 997 |
del result, exception |
| 998 |
|
| 999 |
self.queue.task_done() |
| 1000 |
del item, context, func, args, future, cancel_scope |
| 1001 |
|
| 1002 |
def stop(self, f: asyncio.Task | None = None) -> None: |
| 1003 |
self.stopping = True |
| 1004 |
self.queue.put_nowait(None) |
| 1005 |
self.workers.discard(self) |
| 1006 |
try: |
| 1007 |
self.idle_workers.remove(self) |
| 1008 |
except ValueError: |
| 1009 |
pass |
| 1010 |
|
| 1011 |
|
| 1012 |
_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar( |
| 1013 |
"_threadpool_idle_workers" |
| 1014 |
) |
| 1015 |
_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers") |
| 1016 |
|
| 1017 |
|
| 1018 |
# |
| 1019 |
# Subprocesses |
| 1020 |
# |
| 1021 |
|
| 1022 |
|
| 1023 |
@dataclass(eq=False) |
| 1024 |
class StreamReaderWrapper(abc.ByteReceiveStream): |
| 1025 |
_stream: asyncio.StreamReader |
| 1026 |
|
| 1027 |
async def receive(self, max_bytes: int = 65536) -> bytes: |
| 1028 |
data = await self._stream.read(max_bytes) |
| 1029 |
if data: |
| 1030 |
return data |
| 1031 |
else: |
| 1032 |
raise EndOfStream |
| 1033 |
|
| 1034 |
async def aclose(self) -> None: |
| 1035 |
self._stream.set_exception(ClosedResourceError()) |
| 1036 |
await AsyncIOBackend.checkpoint() |
| 1037 |
|
| 1038 |
|
| 1039 |
@dataclass(eq=False) |
| 1040 |
class StreamWriterWrapper(abc.ByteSendStream): |
| 1041 |
_stream: asyncio.StreamWriter |
| 1042 |
_closed: bool = field(init=False, default=False) |
| 1043 |
|
| 1044 |
async def send(self, item: bytes) -> None: |
| 1045 |
await AsyncIOBackend.checkpoint_if_cancelled() |
| 1046 |
stream_paused = self._stream._protocol._paused # type: ignore[attr-defined] |
| 1047 |
try: |
| 1048 |
self._stream.write(item) |
| 1049 |
await self._stream.drain() |
| 1050 |
except (ConnectionResetError, BrokenPipeError, RuntimeError) as exc: |
| 1051 |
# If closed by us and/or the peer: |
| 1052 |
# * on stdlib, drain() raises ConnectionResetError or BrokenPipeError |
| 1053 |
# * on uvloop and Winloop, write() eventually starts raising RuntimeError |
| 1054 |
if self._closed: |
| 1055 |
raise ClosedResourceError from exc |
| 1056 |
elif self._stream.is_closing(): |
| 1057 |
raise BrokenResourceError from exc |
| 1058 |
|
| 1059 |
raise |
| 1060 |
|
| 1061 |
if not stream_paused: |
| 1062 |
await AsyncIOBackend.cancel_shielded_checkpoint() |
| 1063 |
|
| 1064 |
async def aclose(self) -> None: |
| 1065 |
self._closed = True |
| 1066 |
self._stream.close() |
| 1067 |
await AsyncIOBackend.checkpoint() |
| 1068 |
|
| 1069 |
|
| 1070 |
@dataclass(eq=False) |
| 1071 |
class Process(abc.Process): |
| 1072 |
_process: asyncio.subprocess.Process |
| 1073 |
_stdin: StreamWriterWrapper | None |
| 1074 |
_stdout: StreamReaderWrapper | None |
| 1075 |
_stderr: StreamReaderWrapper | None |
| 1076 |
|
| 1077 |
async def aclose(self) -> None: |
| 1078 |
with CancelScope(shield=True) as scope: |
| 1079 |
if self._stdin: |
| 1080 |
await self._stdin.aclose() |
| 1081 |
if self._stdout: |
| 1082 |
await self._stdout.aclose() |
| 1083 |
if self._stderr: |
| 1084 |
await self._stderr.aclose() |
| 1085 |
|
| 1086 |
scope.shield = False |
| 1087 |
try: |
| 1088 |
await self.wait() |
| 1089 |
except BaseException: |
| 1090 |
scope.shield = True |
| 1091 |
self.kill() |
| 1092 |
await self.wait() |
| 1093 |
raise |
| 1094 |
|
| 1095 |
async def wait(self) -> int: |
| 1096 |
return await self._process.wait() |
| 1097 |
|
| 1098 |
def terminate(self) -> None: |
| 1099 |
self._process.terminate() |
| 1100 |
|
| 1101 |
def kill(self) -> None: |
| 1102 |
self._process.kill() |
| 1103 |
|
| 1104 |
def send_signal(self, signal: int) -> None: |
| 1105 |
self._process.send_signal(signal) |
| 1106 |
|
| 1107 |
@property |
| 1108 |
def pid(self) -> int: |
| 1109 |
return self._process.pid |
| 1110 |
|
| 1111 |
@property |
| 1112 |
def returncode(self) -> int | None: |
| 1113 |
return self._process.returncode |
| 1114 |
|
| 1115 |
@property |
| 1116 |
def stdin(self) -> abc.ByteSendStream | None: |
| 1117 |
return self._stdin |
| 1118 |
|
| 1119 |
@property |
| 1120 |
def stdout(self) -> abc.ByteReceiveStream | None: |
| 1121 |
return self._stdout |
| 1122 |
|
| 1123 |
@property |
| 1124 |
def stderr(self) -> abc.ByteReceiveStream | None: |
| 1125 |
return self._stderr |
| 1126 |
|
| 1127 |
|
| 1128 |
def _forcibly_shutdown_process_pool_on_exit( |
| 1129 |
workers: set[Process], _task: object |
| 1130 |
) -> None: |
| 1131 |
""" |
| 1132 |
Forcibly shuts down worker processes belonging to this event loop.""" |
| 1133 |
child_watcher: asyncio.AbstractChildWatcher | None = None # type: ignore[name-defined] |
| 1134 |
if sys.version_info < (3, 12): |
| 1135 |
try: |
| 1136 |
child_watcher = asyncio.get_event_loop_policy().get_child_watcher() |
| 1137 |
except NotImplementedError: |
| 1138 |
pass |
| 1139 |
|
| 1140 |
# Close as much as possible (w/o async/await) to avoid warnings |
| 1141 |
for process in workers.copy(): |
| 1142 |
if process.returncode is None: |
| 1143 |
continue |
| 1144 |
|
| 1145 |
process._stdin._stream._transport.close() # type: ignore[union-attr] |
| 1146 |
process._stdout._stream._transport.close() # type: ignore[union-attr] |
| 1147 |
process._stderr._stream._transport.close() # type: ignore[union-attr] |
| 1148 |
process.kill() |
| 1149 |
if child_watcher: |
| 1150 |
child_watcher.remove_child_handler(process.pid) |
| 1151 |
|
| 1152 |
|
| 1153 |
async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None: |
| 1154 |
""" |
| 1155 |
Shuts down worker processes belonging to this event loop. |
| 1156 |
|
| 1157 |
NOTE: this only works when the event loop was started using asyncio.run() or |
| 1158 |
anyio.run(). |
| 1159 |
|
| 1160 |
""" |
| 1161 |
process: abc.Process |
| 1162 |
try: |
| 1163 |
await sleep(math.inf) |
| 1164 |
except asyncio.CancelledError: |
| 1165 |
workers = workers.copy() |
| 1166 |
for process in workers: |
| 1167 |
if process.returncode is None: |
| 1168 |
process.kill() |
| 1169 |
|
| 1170 |
for process in workers: |
| 1171 |
await process.aclose() |
| 1172 |
|
| 1173 |
|
| 1174 |
# |
| 1175 |
# Sockets and networking |
| 1176 |
# |
| 1177 |
|
| 1178 |
|
| 1179 |
class StreamProtocol(asyncio.Protocol): |
| 1180 |
read_queue: deque[bytes] |
| 1181 |
read_event: asyncio.Event |
| 1182 |
write_event: asyncio.Event |
| 1183 |
exception: Exception | None = None |
| 1184 |
is_at_eof: bool = False |
| 1185 |
|
| 1186 |
def connection_made(self, transport: asyncio.BaseTransport) -> None: |
| 1187 |
self.read_queue = deque() |
| 1188 |
self.read_event = asyncio.Event() |
| 1189 |
self.write_event = asyncio.Event() |
| 1190 |
self.write_event.set() |
| 1191 |
cast(asyncio.Transport, transport).set_write_buffer_limits(0) |
| 1192 |
|
| 1193 |
def connection_lost(self, exc: Exception | None) -> None: |
| 1194 |
if exc: |
| 1195 |
self.exception = BrokenResourceError() |
| 1196 |
self.exception.__cause__ = exc |
| 1197 |
|
| 1198 |
self.read_event.set() |
| 1199 |
self.write_event.set() |
| 1200 |
|
| 1201 |
def data_received(self, data: bytes) -> None: |
| 1202 |
# ProactorEventloop sometimes sends bytearray instead of bytes |
| 1203 |
self.read_queue.append(bytes(data)) |
| 1204 |
self.read_event.set() |
| 1205 |
|
| 1206 |
def eof_received(self) -> bool | None: |
| 1207 |
self.is_at_eof = True |
| 1208 |
self.read_event.set() |
| 1209 |
return True |
| 1210 |
|
| 1211 |
def pause_writing(self) -> None: |
| 1212 |
self.write_event = asyncio.Event() |
| 1213 |
|
| 1214 |
def resume_writing(self) -> None: |
| 1215 |
self.write_event.set() |
| 1216 |
|
| 1217 |
|
| 1218 |
class DatagramProtocol(asyncio.DatagramProtocol): |
| 1219 |
read_queue: deque[tuple[bytes, IPSockAddrType]] |
| 1220 |
read_event: asyncio.Event |
| 1221 |
write_event: asyncio.Event |
| 1222 |
exception: Exception | None = None |
| 1223 |
|
| 1224 |
def connection_made(self, transport: asyncio.BaseTransport) -> None: |
| 1225 |
self.read_queue = deque(maxlen=100) # arbitrary value |
| 1226 |
self.read_event = asyncio.Event() |
| 1227 |
self.write_event = asyncio.Event() |
| 1228 |
self.write_event.set() |
| 1229 |
|
| 1230 |
def connection_lost(self, exc: Exception | None) -> None: |
| 1231 |
self.read_event.set() |
| 1232 |
self.write_event.set() |
| 1233 |
|
| 1234 |
def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None: |
| 1235 |
addr = convert_ipv6_sockaddr(addr) |
| 1236 |
self.read_queue.append((data, addr)) |
| 1237 |
self.read_event.set() |
| 1238 |
|
| 1239 |
def error_received(self, exc: Exception) -> None: |
| 1240 |
self.exception = exc |
| 1241 |
|
| 1242 |
def pause_writing(self) -> None: |
| 1243 |
self.write_event.clear() |
| 1244 |
|
| 1245 |
def resume_writing(self) -> None: |
| 1246 |
self.write_event.set() |
| 1247 |
|
| 1248 |
|
| 1249 |
class SocketStream(abc.SocketStream): |
| 1250 |
def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol): |
| 1251 |
self._transport = transport |
| 1252 |
self._protocol = protocol |
| 1253 |
self._receive_guard = ResourceGuard("reading from") |
| 1254 |
self._send_guard = ResourceGuard("writing to") |
| 1255 |
self._closed = False |
| 1256 |
|
| 1257 |
@property |
| 1258 |
def _raw_socket(self) -> socket.socket: |
| 1259 |
return self._transport.get_extra_info("socket") |
| 1260 |
|
| 1261 |
async def receive(self, max_bytes: int = 65536) -> bytes: |
| 1262 |
with self._receive_guard: |
| 1263 |
if ( |
| 1264 |
not self._protocol.read_event.is_set() |
| 1265 |
and not self._transport.is_closing() |
| 1266 |
and not self._protocol.is_at_eof |
| 1267 |
): |
| 1268 |
self._transport.resume_reading() |
| 1269 |
await self._protocol.read_event.wait() |
| 1270 |
self._transport.pause_reading() |
| 1271 |
else: |
| 1272 |
await AsyncIOBackend.checkpoint() |
| 1273 |
|
| 1274 |
try: |
| 1275 |
chunk = self._protocol.read_queue.popleft() |
| 1276 |
except IndexError: |
| 1277 |
if self._closed: |
| 1278 |
raise ClosedResourceError from None |
| 1279 |
elif self._protocol.exception: |
| 1280 |
raise self._protocol.exception from None |
| 1281 |
else: |
| 1282 |
raise EndOfStream from None |
| 1283 |
|
| 1284 |
if len(chunk) > max_bytes: |
| 1285 |
# Split the oversized chunk |
| 1286 |
chunk, leftover = chunk[:max_bytes], chunk[max_bytes:] |
| 1287 |
self._protocol.read_queue.appendleft(leftover) |
| 1288 |
|
| 1289 |
# If the read queue is empty, clear the flag so that the next call will |
| 1290 |
# block until data is available |
| 1291 |
if not self._protocol.read_queue: |
| 1292 |
self._protocol.read_event.clear() |
| 1293 |
|
| 1294 |
return chunk |
| 1295 |
|
| 1296 |
async def send(self, item: bytes) -> None: |
| 1297 |
with self._send_guard: |
| 1298 |
await AsyncIOBackend.checkpoint() |
| 1299 |
|
| 1300 |
if self._closed: |
| 1301 |
raise ClosedResourceError |
| 1302 |
elif self._protocol.exception is not None: |
| 1303 |
raise self._protocol.exception |
| 1304 |
|
| 1305 |
try: |
| 1306 |
self._transport.write(item) |
| 1307 |
except RuntimeError as exc: |
| 1308 |
if self._transport.is_closing(): |
| 1309 |
raise BrokenResourceError from exc |
| 1310 |
else: |
| 1311 |
raise |
| 1312 |
|
| 1313 |
await self._protocol.write_event.wait() |
| 1314 |
|
| 1315 |
async def send_eof(self) -> None: |
| 1316 |
try: |
| 1317 |
self._transport.write_eof() |
| 1318 |
except OSError: |
| 1319 |
pass |
| 1320 |
|
| 1321 |
async def aclose(self) -> None: |
| 1322 |
self._closed = True |
| 1323 |
if not self._transport.is_closing(): |
| 1324 |
try: |
| 1325 |
self._transport.write_eof() |
| 1326 |
except OSError: |
| 1327 |
pass |
| 1328 |
|
| 1329 |
self._transport.close() |
| 1330 |
await sleep(0) |
| 1331 |
self._transport.abort() |
| 1332 |
|
| 1333 |
|
| 1334 |
class _RawSocketMixin: |
| 1335 |
_receive_future: asyncio.Future | None = None |
| 1336 |
_send_future: asyncio.Future | None = None |
| 1337 |
_closing = False |
| 1338 |
|
| 1339 |
def __init__(self, raw_socket: socket.socket): |
| 1340 |
self.__raw_socket = raw_socket |
| 1341 |
self._receive_guard = ResourceGuard("reading from") |
| 1342 |
self._send_guard = ResourceGuard("writing to") |
| 1343 |
|
| 1344 |
@property |
| 1345 |
def _raw_socket(self) -> socket.socket: |
| 1346 |
return self.__raw_socket |
| 1347 |
|
| 1348 |
def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: |
| 1349 |
def callback(f: object) -> None: |
| 1350 |
del self._receive_future |
| 1351 |
loop.remove_reader(self.__raw_socket) |
| 1352 |
|
| 1353 |
f = self._receive_future = asyncio.Future() |
| 1354 |
loop.add_reader(self.__raw_socket, f.set_result, None) |
| 1355 |
f.add_done_callback(callback) |
| 1356 |
return f |
| 1357 |
|
| 1358 |
def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: |
| 1359 |
def callback(f: object) -> None: |
| 1360 |
del self._send_future |
| 1361 |
loop.remove_writer(self.__raw_socket) |
| 1362 |
|
| 1363 |
f = self._send_future = asyncio.Future() |
| 1364 |
loop.add_writer(self.__raw_socket, f.set_result, None) |
| 1365 |
f.add_done_callback(callback) |
| 1366 |
return f |
| 1367 |
|
| 1368 |
async def aclose(self) -> None: |
| 1369 |
if not self._closing: |
| 1370 |
self._closing = True |
| 1371 |
if self.__raw_socket.fileno() != -1: |
| 1372 |
self.__raw_socket.close() |
| 1373 |
|
| 1374 |
if self._receive_future: |
| 1375 |
self._receive_future.set_result(None) |
| 1376 |
if self._send_future: |
| 1377 |
self._send_future.set_result(None) |
| 1378 |
|
| 1379 |
|
| 1380 |
class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream): |
| 1381 |
async def send_eof(self) -> None: |
| 1382 |
with self._send_guard: |
| 1383 |
self._raw_socket.shutdown(socket.SHUT_WR) |
| 1384 |
|
| 1385 |
async def receive(self, max_bytes: int = 65536) -> bytes: |
| 1386 |
loop = get_running_loop() |
| 1387 |
await AsyncIOBackend.checkpoint() |
| 1388 |
with self._receive_guard: |
| 1389 |
while True: |
| 1390 |
try: |
| 1391 |
data = self._raw_socket.recv(max_bytes) |
| 1392 |
except BlockingIOError: |
| 1393 |
await self._wait_until_readable(loop) |
| 1394 |
except OSError as exc: |
| 1395 |
if self._closing: |
| 1396 |
raise ClosedResourceError from None |
| 1397 |
else: |
| 1398 |
raise BrokenResourceError from exc |
| 1399 |
else: |
| 1400 |
if not data: |
| 1401 |
raise EndOfStream |
| 1402 |
|
| 1403 |
return data |
| 1404 |
|
| 1405 |
async def send(self, item: bytes) -> None: |
| 1406 |
loop = get_running_loop() |
| 1407 |
await AsyncIOBackend.checkpoint() |
| 1408 |
with self._send_guard: |
| 1409 |
view = memoryview(item) |
| 1410 |
while view: |
| 1411 |
try: |
| 1412 |
bytes_sent = self._raw_socket.send(view) |
| 1413 |
except BlockingIOError: |
| 1414 |
await self._wait_until_writable(loop) |
| 1415 |
except OSError as exc: |
| 1416 |
if self._closing: |
| 1417 |
raise ClosedResourceError from None |
| 1418 |
else: |
| 1419 |
raise BrokenResourceError from exc |
| 1420 |
else: |
| 1421 |
view = view[bytes_sent:] |
| 1422 |
|
| 1423 |
async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: |
| 1424 |
if not isinstance(msglen, int) or msglen < 0: |
| 1425 |
raise ValueError("msglen must be a non-negative integer") |
| 1426 |
if not isinstance(maxfds, int) or maxfds < 1: |
| 1427 |
raise ValueError("maxfds must be a positive integer") |
| 1428 |
|
| 1429 |
loop = get_running_loop() |
| 1430 |
fds = array.array("i") |
| 1431 |
await AsyncIOBackend.checkpoint() |
| 1432 |
with self._receive_guard: |
| 1433 |
while True: |
| 1434 |
try: |
| 1435 |
message, ancdata, flags, addr = self._raw_socket.recvmsg( |
| 1436 |
msglen, socket.CMSG_LEN(maxfds * fds.itemsize) |
| 1437 |
) |
| 1438 |
except BlockingIOError: |
| 1439 |
await self._wait_until_readable(loop) |
| 1440 |
except OSError as exc: |
| 1441 |
if self._closing: |
| 1442 |
raise ClosedResourceError from None |
| 1443 |
else: |
| 1444 |
raise BrokenResourceError from exc |
| 1445 |
else: |
| 1446 |
if not message and not ancdata: |
| 1447 |
raise EndOfStream |
| 1448 |
|
| 1449 |
break |
| 1450 |
|
| 1451 |
for cmsg_level, cmsg_type, cmsg_data in ancdata: |
| 1452 |
if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: |
| 1453 |
raise RuntimeError( |
| 1454 |
f"Received unexpected ancillary data; message = {message!r}, " |
| 1455 |
f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" |
| 1456 |
) |
| 1457 |
|
| 1458 |
fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
| 1459 |
|
| 1460 |
return message, list(fds) |
| 1461 |
|
| 1462 |
async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: |
| 1463 |
if not message: |
| 1464 |
raise ValueError("message must not be empty") |
| 1465 |
if not fds: |
| 1466 |
raise ValueError("fds must not be empty") |
| 1467 |
|
| 1468 |
loop = get_running_loop() |
| 1469 |
filenos: list[int] = [] |
| 1470 |
for fd in fds: |
| 1471 |
if isinstance(fd, int): |
| 1472 |
filenos.append(fd) |
| 1473 |
elif isinstance(fd, IOBase): |
| 1474 |
filenos.append(fd.fileno()) |
| 1475 |
|
| 1476 |
fdarray = array.array("i", filenos) |
| 1477 |
await AsyncIOBackend.checkpoint() |
| 1478 |
with self._send_guard: |
| 1479 |
while True: |
| 1480 |
try: |
| 1481 |
# The ignore can be removed after mypy picks up |
| 1482 |
# https://github.com/python/typeshed/pull/5545 |
| 1483 |
self._raw_socket.sendmsg( |
| 1484 |
[message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)] |
| 1485 |
) |
| 1486 |
break |
| 1487 |
except BlockingIOError: |
| 1488 |
await self._wait_until_writable(loop) |
| 1489 |
except OSError as exc: |
| 1490 |
if self._closing: |
| 1491 |
raise ClosedResourceError from None |
| 1492 |
else: |
| 1493 |
raise BrokenResourceError from exc |
| 1494 |
|
| 1495 |
|
| 1496 |
class TCPSocketListener(abc.SocketListener): |
| 1497 |
_accept_scope: CancelScope | None = None |
| 1498 |
_closed = False |
| 1499 |
|
| 1500 |
def __init__(self, raw_socket: socket.socket): |
| 1501 |
self.__raw_socket = raw_socket |
| 1502 |
self._loop = cast(asyncio.BaseEventLoop, get_running_loop()) |
| 1503 |
self._accept_guard = ResourceGuard("accepting connections from") |
| 1504 |
|
| 1505 |
@property |
| 1506 |
def _raw_socket(self) -> socket.socket: |
| 1507 |
return self.__raw_socket |
| 1508 |
|
| 1509 |
async def accept(self) -> abc.SocketStream: |
| 1510 |
if self._closed: |
| 1511 |
raise ClosedResourceError |
| 1512 |
|
| 1513 |
with self._accept_guard: |
| 1514 |
await AsyncIOBackend.checkpoint() |
| 1515 |
with CancelScope() as self._accept_scope: |
| 1516 |
try: |
| 1517 |
client_sock, _addr = await self._loop.sock_accept(self._raw_socket) |
| 1518 |
except asyncio.CancelledError: |
| 1519 |
# Workaround for https://bugs.python.org/issue41317 |
| 1520 |
try: |
| 1521 |
self._loop.remove_reader(self._raw_socket) |
| 1522 |
except (ValueError, NotImplementedError): |
| 1523 |
pass |
| 1524 |
|
| 1525 |
if self._closed: |
| 1526 |
raise ClosedResourceError from None |
| 1527 |
|
| 1528 |
raise |
| 1529 |
finally: |
| 1530 |
self._accept_scope = None |
| 1531 |
|
| 1532 |
client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 1533 |
transport, protocol = await self._loop.connect_accepted_socket( |
| 1534 |
StreamProtocol, client_sock |
| 1535 |
) |
| 1536 |
return SocketStream(transport, protocol) |
| 1537 |
|
| 1538 |
async def aclose(self) -> None: |
| 1539 |
if self._closed: |
| 1540 |
return |
| 1541 |
|
| 1542 |
self._closed = True |
| 1543 |
if self._accept_scope: |
| 1544 |
# Workaround for https://bugs.python.org/issue41317 |
| 1545 |
try: |
| 1546 |
self._loop.remove_reader(self._raw_socket) |
| 1547 |
except (ValueError, NotImplementedError): |
| 1548 |
pass |
| 1549 |
|
| 1550 |
self._accept_scope.cancel() |
| 1551 |
await sleep(0) |
| 1552 |
|
| 1553 |
self._raw_socket.close() |
| 1554 |
|
| 1555 |
|
| 1556 |
class UNIXSocketListener(abc.SocketListener): |
| 1557 |
def __init__(self, raw_socket: socket.socket): |
| 1558 |
self.__raw_socket = raw_socket |
| 1559 |
self._loop = get_running_loop() |
| 1560 |
self._accept_guard = ResourceGuard("accepting connections from") |
| 1561 |
self._closed = False |
| 1562 |
|
| 1563 |
async def accept(self) -> abc.SocketStream: |
| 1564 |
await AsyncIOBackend.checkpoint() |
| 1565 |
with self._accept_guard: |
| 1566 |
while True: |
| 1567 |
try: |
| 1568 |
client_sock, _ = self.__raw_socket.accept() |
| 1569 |
client_sock.setblocking(False) |
| 1570 |
return UNIXSocketStream(client_sock) |
| 1571 |
except BlockingIOError: |
| 1572 |
f: asyncio.Future = asyncio.Future() |
| 1573 |
self._loop.add_reader(self.__raw_socket, f.set_result, None) |
| 1574 |
f.add_done_callback( |
| 1575 |
lambda _: self._loop.remove_reader(self.__raw_socket) |
| 1576 |
) |
| 1577 |
await f |
| 1578 |
except OSError as exc: |
| 1579 |
if self._closed: |
| 1580 |
raise ClosedResourceError from None |
| 1581 |
else: |
| 1582 |
raise BrokenResourceError from exc |
| 1583 |
|
| 1584 |
async def aclose(self) -> None: |
| 1585 |
self._closed = True |
| 1586 |
self.__raw_socket.close() |
| 1587 |
|
| 1588 |
@property |
| 1589 |
def _raw_socket(self) -> socket.socket: |
| 1590 |
return self.__raw_socket |
| 1591 |
|
| 1592 |
|
| 1593 |
class UDPSocket(abc.UDPSocket): |
| 1594 |
def __init__( |
| 1595 |
self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol |
| 1596 |
): |
| 1597 |
self._transport = transport |
| 1598 |
self._protocol = protocol |
| 1599 |
self._receive_guard = ResourceGuard("reading from") |
| 1600 |
self._send_guard = ResourceGuard("writing to") |
| 1601 |
self._closed = False |
| 1602 |
|
| 1603 |
@property |
| 1604 |
def _raw_socket(self) -> socket.socket: |
| 1605 |
return self._transport.get_extra_info("socket") |
| 1606 |
|
| 1607 |
async def aclose(self) -> None: |
| 1608 |
self._closed = True |
| 1609 |
if not self._transport.is_closing(): |
| 1610 |
self._transport.close() |
| 1611 |
|
| 1612 |
async def receive(self) -> tuple[bytes, IPSockAddrType]: |
| 1613 |
with self._receive_guard: |
| 1614 |
await AsyncIOBackend.checkpoint() |
| 1615 |
|
| 1616 |
# If the buffer is empty, ask for more data |
| 1617 |
if not self._protocol.read_queue and not self._transport.is_closing(): |
| 1618 |
self._protocol.read_event.clear() |
| 1619 |
await self._protocol.read_event.wait() |
| 1620 |
|
| 1621 |
try: |
| 1622 |
return self._protocol.read_queue.popleft() |
| 1623 |
except IndexError: |
| 1624 |
if self._closed: |
| 1625 |
raise ClosedResourceError from None |
| 1626 |
else: |
| 1627 |
raise BrokenResourceError from None |
| 1628 |
|
| 1629 |
async def send(self, item: UDPPacketType) -> None: |
| 1630 |
with self._send_guard: |
| 1631 |
await AsyncIOBackend.checkpoint() |
| 1632 |
await self._protocol.write_event.wait() |
| 1633 |
if self._closed: |
| 1634 |
raise ClosedResourceError |
| 1635 |
elif self._transport.is_closing(): |
| 1636 |
raise BrokenResourceError |
| 1637 |
else: |
| 1638 |
self._transport.sendto(*item) |
| 1639 |
|
| 1640 |
|
| 1641 |
class ConnectedUDPSocket(abc.ConnectedUDPSocket): |
| 1642 |
def __init__( |
| 1643 |
self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol |
| 1644 |
): |
| 1645 |
self._transport = transport |
| 1646 |
self._protocol = protocol |
| 1647 |
self._receive_guard = ResourceGuard("reading from") |
| 1648 |
self._send_guard = ResourceGuard("writing to") |
| 1649 |
self._closed = False |
| 1650 |
|
| 1651 |
@property |
| 1652 |
def _raw_socket(self) -> socket.socket: |
| 1653 |
return self._transport.get_extra_info("socket") |
| 1654 |
|
| 1655 |
async def aclose(self) -> None: |
| 1656 |
self._closed = True |
| 1657 |
if not self._transport.is_closing(): |
| 1658 |
self._transport.close() |
| 1659 |
|
| 1660 |
async def receive(self) -> bytes: |
| 1661 |
with self._receive_guard: |
| 1662 |
await AsyncIOBackend.checkpoint() |
| 1663 |
|
| 1664 |
# If the buffer is empty, ask for more data |
| 1665 |
if not self._protocol.read_queue and not self._transport.is_closing(): |
| 1666 |
self._protocol.read_event.clear() |
| 1667 |
await self._protocol.read_event.wait() |
| 1668 |
|
| 1669 |
try: |
| 1670 |
packet = self._protocol.read_queue.popleft() |
| 1671 |
except IndexError: |
| 1672 |
if self._closed: |
| 1673 |
raise ClosedResourceError from None |
| 1674 |
else: |
| 1675 |
raise BrokenResourceError from None |
| 1676 |
|
| 1677 |
return packet[0] |
| 1678 |
|
| 1679 |
async def send(self, item: bytes) -> None: |
| 1680 |
with self._send_guard: |
| 1681 |
await AsyncIOBackend.checkpoint() |
| 1682 |
await self._protocol.write_event.wait() |
| 1683 |
if self._closed: |
| 1684 |
raise ClosedResourceError |
| 1685 |
elif self._transport.is_closing(): |
| 1686 |
raise BrokenResourceError |
| 1687 |
else: |
| 1688 |
self._transport.sendto(item) |
| 1689 |
|
| 1690 |
|
| 1691 |
class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket): |
| 1692 |
async def receive(self) -> UNIXDatagramPacketType: |
| 1693 |
loop = get_running_loop() |
| 1694 |
await AsyncIOBackend.checkpoint() |
| 1695 |
with self._receive_guard: |
| 1696 |
while True: |
| 1697 |
try: |
| 1698 |
data = self._raw_socket.recvfrom(65536) |
| 1699 |
except BlockingIOError: |
| 1700 |
await self._wait_until_readable(loop) |
| 1701 |
except OSError as exc: |
| 1702 |
if self._closing: |
| 1703 |
raise ClosedResourceError from None |
| 1704 |
else: |
| 1705 |
raise BrokenResourceError from exc |
| 1706 |
else: |
| 1707 |
return data |
| 1708 |
|
| 1709 |
async def send(self, item: UNIXDatagramPacketType) -> None: |
| 1710 |
loop = get_running_loop() |
| 1711 |
await AsyncIOBackend.checkpoint() |
| 1712 |
with self._send_guard: |
| 1713 |
while True: |
| 1714 |
try: |
| 1715 |
self._raw_socket.sendto(*item) |
| 1716 |
except BlockingIOError: |
| 1717 |
await self._wait_until_writable(loop) |
| 1718 |
except OSError as exc: |
| 1719 |
if self._closing: |
| 1720 |
raise ClosedResourceError from None |
| 1721 |
else: |
| 1722 |
raise BrokenResourceError from exc |
| 1723 |
else: |
| 1724 |
return |
| 1725 |
|
| 1726 |
|
| 1727 |
class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket): |
| 1728 |
async def receive(self) -> bytes: |
| 1729 |
loop = get_running_loop() |
| 1730 |
await AsyncIOBackend.checkpoint() |
| 1731 |
with self._receive_guard: |
| 1732 |
while True: |
| 1733 |
try: |
| 1734 |
data = self._raw_socket.recv(65536) |
| 1735 |
except BlockingIOError: |
| 1736 |
await self._wait_until_readable(loop) |
| 1737 |
except OSError as exc: |
| 1738 |
if self._closing: |
| 1739 |
raise ClosedResourceError from None |
| 1740 |
else: |
| 1741 |
raise BrokenResourceError from exc |
| 1742 |
else: |
| 1743 |
return data |
| 1744 |
|
| 1745 |
async def send(self, item: bytes) -> None: |
| 1746 |
loop = get_running_loop() |
| 1747 |
await AsyncIOBackend.checkpoint() |
| 1748 |
with self._send_guard: |
| 1749 |
while True: |
| 1750 |
try: |
| 1751 |
self._raw_socket.send(item) |
| 1752 |
except BlockingIOError: |
| 1753 |
await self._wait_until_writable(loop) |
| 1754 |
except OSError as exc: |
| 1755 |
if self._closing: |
| 1756 |
raise ClosedResourceError from None |
| 1757 |
else: |
| 1758 |
raise BrokenResourceError from exc |
| 1759 |
else: |
| 1760 |
return |
| 1761 |
|
| 1762 |
|
| 1763 |
_read_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("read_events") |
| 1764 |
_write_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("write_events") |
| 1765 |
|
| 1766 |
|
| 1767 |
# |
| 1768 |
# Synchronization |
| 1769 |
# |
| 1770 |
|
| 1771 |
|
| 1772 |
class Event(BaseEvent): |
| 1773 |
def __new__(cls) -> Event: |
| 1774 |
return object.__new__(cls) |
| 1775 |
|
| 1776 |
def __init__(self) -> None: |
| 1777 |
self._event = asyncio.Event() |
| 1778 |
|
| 1779 |
def set(self) -> None: |
| 1780 |
self._event.set() |
| 1781 |
|
| 1782 |
def is_set(self) -> bool: |
| 1783 |
return self._event.is_set() |
| 1784 |
|
| 1785 |
async def wait(self) -> None: |
| 1786 |
if self.is_set(): |
| 1787 |
await AsyncIOBackend.checkpoint() |
| 1788 |
else: |
| 1789 |
await self._event.wait() |
| 1790 |
|
| 1791 |
def statistics(self) -> EventStatistics: |
| 1792 |
return EventStatistics(len(self._event._waiters)) |
| 1793 |
|
| 1794 |
|
| 1795 |
class Lock(BaseLock): |
| 1796 |
def __new__(cls, *, fast_acquire: bool = False) -> Lock: |
| 1797 |
return object.__new__(cls) |
| 1798 |
|
| 1799 |
def __init__(self, *, fast_acquire: bool = False) -> None: |
| 1800 |
self._fast_acquire = fast_acquire |
| 1801 |
self._owner_task: asyncio.Task | None = None |
| 1802 |
self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque() |
| 1803 |
|
| 1804 |
async def acquire(self) -> None: |
| 1805 |
task = cast(asyncio.Task, current_task()) |
| 1806 |
if self._owner_task is None and not self._waiters: |
| 1807 |
await AsyncIOBackend.checkpoint_if_cancelled() |
| 1808 |
self._owner_task = task |
| 1809 |
|
| 1810 |
# Unless on the "fast path", yield control of the event loop so that other |
| 1811 |
# tasks can run too |
| 1812 |
if not self._fast_acquire: |
| 1813 |
try: |
| 1814 |
await AsyncIOBackend.cancel_shielded_checkpoint() |
| 1815 |
except CancelledError: |
| 1816 |
self.release() |
| 1817 |
raise |
| 1818 |
|
| 1819 |
return |
| 1820 |
|
| 1821 |
if self._owner_task == task: |
| 1822 |
raise RuntimeError("Attempted to acquire an already held Lock") |
| 1823 |
|
| 1824 |
fut: asyncio.Future[None] = asyncio.Future() |
| 1825 |
item = task, fut |
| 1826 |
self._waiters.append(item) |
| 1827 |
try: |
| 1828 |
await fut |
| 1829 |
except CancelledError: |
| 1830 |
self._waiters.remove(item) |
| 1831 |
if self._owner_task is task: |
| 1832 |
self.release() |
| 1833 |
|
| 1834 |
raise |
| 1835 |
|
| 1836 |
self._waiters.remove(item) |
| 1837 |
|
| 1838 |
def acquire_nowait(self) -> None: |
| 1839 |
task = cast(asyncio.Task, current_task()) |
| 1840 |
if self._owner_task is None and not self._waiters: |
| 1841 |
self._owner_task = task |
| 1842 |
return |
| 1843 |
|
| 1844 |
if self._owner_task is task: |
| 1845 |
raise RuntimeError("Attempted to acquire an already held Lock") |
| 1846 |
|
| 1847 |
raise WouldBlock |
| 1848 |
|
| 1849 |
def locked(self) -> bool: |
| 1850 |
return self._owner_task is not None |
| 1851 |
|
| 1852 |
def release(self) -> None: |
| 1853 |
if self._owner_task != current_task(): |
| 1854 |
raise RuntimeError("The current task is not holding this lock") |
| 1855 |
|
| 1856 |
for task, fut in self._waiters: |
| 1857 |
if not fut.cancelled(): |
| 1858 |
self._owner_task = task |
| 1859 |
fut.set_result(None) |
| 1860 |
return |
| 1861 |
|
| 1862 |
self._owner_task = None |
| 1863 |
|
| 1864 |
def statistics(self) -> LockStatistics: |
| 1865 |
task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None |
| 1866 |
return LockStatistics(self.locked(), task_info, len(self._waiters)) |
| 1867 |
|
| 1868 |
|
| 1869 |
class Semaphore(BaseSemaphore): |
| 1870 |
def __new__( |
| 1871 |
cls, |
| 1872 |
initial_value: int, |
| 1873 |
*, |
| 1874 |
max_value: int | None = None, |
| 1875 |
fast_acquire: bool = False, |
| 1876 |
) -> Semaphore: |
| 1877 |
return object.__new__(cls) |
| 1878 |
|
| 1879 |
def __init__( |
| 1880 |
self, |
| 1881 |
initial_value: int, |
| 1882 |
*, |
| 1883 |
max_value: int | None = None, |
| 1884 |
fast_acquire: bool = False, |
| 1885 |
): |
| 1886 |
super().__init__(initial_value, max_value=max_value) |
| 1887 |
self._value = initial_value |
| 1888 |
self._max_value = max_value |
| 1889 |
self._fast_acquire = fast_acquire |
| 1890 |
self._waiters: deque[asyncio.Future[None]] = deque() |
| 1891 |
|
| 1892 |
async def acquire(self) -> None: |
| 1893 |
if self._value > 0 and not self._waiters: |
| 1894 |
await AsyncIOBackend.checkpoint_if_cancelled() |
| 1895 |
self._value -= 1 |
| 1896 |
|
| 1897 |
# Unless on the "fast path", yield control of the event loop so that other |
| 1898 |
# tasks can run too |
| 1899 |
if not self._fast_acquire: |
| 1900 |
try: |
| 1901 |
await AsyncIOBackend.cancel_shielded_checkpoint() |
| 1902 |
except CancelledError: |
| 1903 |
self.release() |
| 1904 |
raise |
| 1905 |
|
| 1906 |
return |
| 1907 |
|
| 1908 |
fut: asyncio.Future[None] = asyncio.Future() |
| 1909 |
self._waiters.append(fut) |
| 1910 |
try: |
| 1911 |
await fut |
| 1912 |
except CancelledError: |
| 1913 |
try: |
| 1914 |
self._waiters.remove(fut) |
| 1915 |
except ValueError: |
| 1916 |
self.release() |
| 1917 |
|
| 1918 |
raise |
| 1919 |
|
| 1920 |
def acquire_nowait(self) -> None: |
| 1921 |
if self._value == 0: |
| 1922 |
raise WouldBlock |
| 1923 |
|
| 1924 |
self._value -= 1 |
| 1925 |
|
| 1926 |
def release(self) -> None: |
| 1927 |
if self._max_value is not None and self._value == self._max_value: |
| 1928 |
raise ValueError("semaphore released too many times") |
| 1929 |
|
| 1930 |
for fut in self._waiters: |
| 1931 |
if not fut.cancelled(): |
| 1932 |
fut.set_result(None) |
| 1933 |
self._waiters.remove(fut) |
| 1934 |
return |
| 1935 |
|
| 1936 |
self._value += 1 |
| 1937 |
|
| 1938 |
@property |
| 1939 |
def value(self) -> int: |
| 1940 |
return self._value |
| 1941 |
|
| 1942 |
@property |
| 1943 |
def max_value(self) -> int | None: |
| 1944 |
return self._max_value |
| 1945 |
|
| 1946 |
def statistics(self) -> SemaphoreStatistics: |
| 1947 |
return SemaphoreStatistics(len(self._waiters)) |
| 1948 |
|
| 1949 |
|
| 1950 |
class CapacityLimiter(BaseCapacityLimiter): |
| 1951 |
_total_tokens: float = 0 |
| 1952 |
|
| 1953 |
def __new__(cls, total_tokens: float) -> CapacityLimiter: |
| 1954 |
return object.__new__(cls) |
| 1955 |
|
| 1956 |
def __init__(self, total_tokens: float): |
| 1957 |
self._borrowers: set[Any] = set() |
| 1958 |
self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict() |
| 1959 |
self.total_tokens = total_tokens |
| 1960 |
|
| 1961 |
async def __aenter__(self) -> None: |
| 1962 |
await self.acquire() |
| 1963 |
|
| 1964 |
async def __aexit__( |
| 1965 |
self, |
| 1966 |
exc_type: type[BaseException] | None, |
| 1967 |
exc_val: BaseException | None, |
| 1968 |
exc_tb: TracebackType | None, |
| 1969 |
) -> None: |
| 1970 |
self.release() |
| 1971 |
|
| 1972 |
@property |
| 1973 |
def total_tokens(self) -> float: |
| 1974 |
return self._total_tokens |
| 1975 |
|
| 1976 |
@total_tokens.setter |
| 1977 |
def total_tokens(self, value: float) -> None: |
| 1978 |
if not isinstance(value, int) and not math.isinf(value): |
| 1979 |
raise TypeError("total_tokens must be an int or math.inf") |
| 1980 |
|
| 1981 |
if value < 0: |
| 1982 |
raise ValueError("total_tokens must be >= 0") |
| 1983 |
|
| 1984 |
waiters_to_notify = max(value - self._total_tokens, 0) |
| 1985 |
self._total_tokens = value |
| 1986 |
|
| 1987 |
# Notify waiting tasks that they have acquired the limiter |
| 1988 |
while self._wait_queue and waiters_to_notify: |
| 1989 |
event = self._wait_queue.popitem(last=False)[1] |
| 1990 |
event.set() |
| 1991 |
waiters_to_notify -= 1 |
| 1992 |
|
| 1993 |
@property |
| 1994 |
def borrowed_tokens(self) -> int: |
| 1995 |
return len(self._borrowers) |
| 1996 |
|
| 1997 |
@property |
| 1998 |
def available_tokens(self) -> float: |
| 1999 |
return self._total_tokens - len(self._borrowers) |
| 2000 |
|
| 2001 |
def _notify_next_waiter(self) -> None: |
| 2002 |
"""Notify the next task in line if this limiter has free capacity now.""" |
| 2003 |
if self._wait_queue and len(self._borrowers) < self._total_tokens: |
| 2004 |
event = self._wait_queue.popitem(last=False)[1] |
| 2005 |
event.set() |
| 2006 |
|
| 2007 |
def acquire_nowait(self) -> None: |
| 2008 |
self.acquire_on_behalf_of_nowait(current_task()) |
| 2009 |
|
| 2010 |
def acquire_on_behalf_of_nowait(self, borrower: object) -> None: |
| 2011 |
if borrower in self._borrowers: |
| 2012 |
raise RuntimeError( |
| 2013 |
"this borrower is already holding one of this CapacityLimiter's tokens" |
| 2014 |
) |
| 2015 |
|
| 2016 |
if self._wait_queue or len(self._borrowers) >= self._total_tokens: |
| 2017 |
raise WouldBlock |
| 2018 |
|
| 2019 |
self._borrowers.add(borrower) |
| 2020 |
|
| 2021 |
async def acquire(self) -> None: |
| 2022 |
return await self.acquire_on_behalf_of(current_task()) |
| 2023 |
|
| 2024 |
async def acquire_on_behalf_of(self, borrower: object) -> None: |
| 2025 |
await AsyncIOBackend.checkpoint_if_cancelled() |
| 2026 |
try: |
| 2027 |
self.acquire_on_behalf_of_nowait(borrower) |
| 2028 |
except WouldBlock: |
| 2029 |
event = asyncio.Event() |
| 2030 |
self._wait_queue[borrower] = event |
| 2031 |
try: |
| 2032 |
await event.wait() |
| 2033 |
except BaseException: |
| 2034 |
self._wait_queue.pop(borrower, None) |
| 2035 |
if event.is_set(): |
| 2036 |
self._notify_next_waiter() |
| 2037 |
|
| 2038 |
raise |
| 2039 |
|
| 2040 |
self._borrowers.add(borrower) |
| 2041 |
else: |
| 2042 |
try: |
| 2043 |
await AsyncIOBackend.cancel_shielded_checkpoint() |
| 2044 |
except BaseException: |
| 2045 |
self.release() |
| 2046 |
raise |
| 2047 |
|
| 2048 |
def release(self) -> None: |
| 2049 |
self.release_on_behalf_of(current_task()) |
| 2050 |
|
| 2051 |
def release_on_behalf_of(self, borrower: object) -> None: |
| 2052 |
try: |
| 2053 |
self._borrowers.remove(borrower) |
| 2054 |
except KeyError: |
| 2055 |
raise RuntimeError( |
| 2056 |
"this borrower isn't holding any of this CapacityLimiter's tokens" |
| 2057 |
) from None |
| 2058 |
|
| 2059 |
self._notify_next_waiter() |
| 2060 |
|
| 2061 |
def statistics(self) -> CapacityLimiterStatistics: |
| 2062 |
return CapacityLimiterStatistics( |
| 2063 |
self.borrowed_tokens, |
| 2064 |
self.total_tokens, |
| 2065 |
tuple(self._borrowers), |
| 2066 |
len(self._wait_queue), |
| 2067 |
) |
| 2068 |
|
| 2069 |
|
| 2070 |
_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter") |
| 2071 |
|
| 2072 |
|
| 2073 |
# |
| 2074 |
# Operating system signals |
| 2075 |
# |
| 2076 |
|
| 2077 |
|
| 2078 |
class _SignalReceiver: |
| 2079 |
def __init__(self, signals: tuple[Signals, ...]): |
| 2080 |
self._signals = signals |
| 2081 |
self._loop = get_running_loop() |
| 2082 |
self._signal_queue: deque[Signals] = deque() |
| 2083 |
self._future: asyncio.Future = asyncio.Future() |
| 2084 |
self._handled_signals: set[Signals] = set() |
| 2085 |
|
| 2086 |
def _deliver(self, signum: Signals) -> None: |
| 2087 |
self._signal_queue.append(signum) |
| 2088 |
if not self._future.done(): |
| 2089 |
self._future.set_result(None) |
| 2090 |
|
| 2091 |
def __enter__(self) -> _SignalReceiver: |
| 2092 |
for sig in set(self._signals): |
| 2093 |
self._loop.add_signal_handler(sig, self._deliver, sig) |
| 2094 |
self._handled_signals.add(sig) |
| 2095 |
|
| 2096 |
return self |
| 2097 |
|
| 2098 |
def __exit__( |
| 2099 |
self, |
| 2100 |
exc_type: type[BaseException] | None, |
| 2101 |
exc_val: BaseException | None, |
| 2102 |
exc_tb: TracebackType | None, |
| 2103 |
) -> None: |
| 2104 |
for sig in self._handled_signals: |
| 2105 |
self._loop.remove_signal_handler(sig) |
| 2106 |
|
| 2107 |
def __aiter__(self) -> _SignalReceiver: |
| 2108 |
return self |
| 2109 |
|
| 2110 |
async def __anext__(self) -> Signals: |
| 2111 |
await AsyncIOBackend.checkpoint() |
| 2112 |
if not self._signal_queue: |
| 2113 |
self._future = asyncio.Future() |
| 2114 |
await self._future |
| 2115 |
|
| 2116 |
return self._signal_queue.popleft() |
| 2117 |
|
| 2118 |
|
| 2119 |
# |
| 2120 |
# Testing and debugging |
| 2121 |
# |
| 2122 |
|
| 2123 |
|
| 2124 |
class AsyncIOTaskInfo(TaskInfo): |
| 2125 |
def __init__(self, task: asyncio.Task): |
| 2126 |
task_state = _task_states.get(task) |
| 2127 |
if task_state is None: |
| 2128 |
parent_id = None |
| 2129 |
else: |
| 2130 |
parent_id = task_state.parent_id |
| 2131 |
|
| 2132 |
coro = task.get_coro() |
| 2133 |
assert coro is not None, "created TaskInfo from a completed Task" |
| 2134 |
super().__init__(id(task), parent_id, task.get_name(), coro) |
| 2135 |
self._task = weakref.ref(task) |
| 2136 |
|
| 2137 |
def has_pending_cancellation(self) -> bool: |
| 2138 |
if not (task := self._task()): |
| 2139 |
# If the task isn't around anymore, it won't have a pending cancellation |
| 2140 |
return False |
| 2141 |
|
| 2142 |
if task._must_cancel: # type: ignore[attr-defined] |
| 2143 |
return True |
| 2144 |
elif ( |
| 2145 |
isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined] |
| 2146 |
and task._fut_waiter.cancelled() # type: ignore[attr-defined] |
| 2147 |
): |
| 2148 |
return True |
| 2149 |
|
| 2150 |
if task_state := _task_states.get(task): |
| 2151 |
if cancel_scope := task_state.cancel_scope: |
| 2152 |
return cancel_scope._effectively_cancelled |
| 2153 |
|
| 2154 |
return False |
| 2155 |
|
| 2156 |
|
| 2157 |
class TestRunner(abc.TestRunner): |
| 2158 |
_send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]] |
| 2159 |
|
| 2160 |
def __init__( |
| 2161 |
self, |
| 2162 |
*, |
| 2163 |
debug: bool | None = None, |
| 2164 |
use_uvloop: bool = False, |
| 2165 |
loop_factory: Callable[[], AbstractEventLoop] | None = None, |
| 2166 |
) -> None: |
| 2167 |
if use_uvloop and loop_factory is None: |
| 2168 |
if sys.platform != "win32": |
| 2169 |
import uvloop |
| 2170 |
|
| 2171 |
loop_factory = uvloop.new_event_loop |
| 2172 |
else: |
| 2173 |
import winloop |
| 2174 |
|
| 2175 |
loop_factory = winloop.new_event_loop |
| 2176 |
|
| 2177 |
self._runner = Runner(debug=debug, loop_factory=loop_factory) |
| 2178 |
self._exceptions: list[BaseException] = [] |
| 2179 |
self._runner_task: asyncio.Task | None = None |
| 2180 |
|
| 2181 |
def __enter__(self) -> TestRunner: |
| 2182 |
self._runner.__enter__() |
| 2183 |
self.get_loop().set_exception_handler(self._exception_handler) |
| 2184 |
return self |
| 2185 |
|
| 2186 |
def __exit__( |
| 2187 |
self, |
| 2188 |
exc_type: type[BaseException] | None, |
| 2189 |
exc_val: BaseException | None, |
| 2190 |
exc_tb: TracebackType | None, |
| 2191 |
) -> None: |
| 2192 |
self._runner.__exit__(exc_type, exc_val, exc_tb) |
| 2193 |
|
| 2194 |
def get_loop(self) -> AbstractEventLoop: |
| 2195 |
return self._runner.get_loop() |
| 2196 |
|
| 2197 |
def _exception_handler( |
| 2198 |
self, loop: asyncio.AbstractEventLoop, context: dict[str, Any] |
| 2199 |
) -> None: |
| 2200 |
if isinstance(context.get("exception"), Exception): |
| 2201 |
self._exceptions.append(context["exception"]) |
| 2202 |
else: |
| 2203 |
loop.default_exception_handler(context) |
| 2204 |
|
| 2205 |
def _raise_async_exceptions(self) -> None: |
| 2206 |
# Re-raise any exceptions raised in asynchronous callbacks |
| 2207 |
if self._exceptions: |
| 2208 |
exceptions, self._exceptions = self._exceptions, [] |
| 2209 |
if len(exceptions) == 1: |
| 2210 |
raise exceptions[0] |
| 2211 |
elif exceptions: |
| 2212 |
raise BaseExceptionGroup( |
| 2213 |
"Multiple exceptions occurred in asynchronous callbacks", exceptions |
| 2214 |
) |
| 2215 |
|
| 2216 |
async def _run_tests_and_fixtures( |
| 2217 |
self, |
| 2218 |
receive_stream: MemoryObjectReceiveStream[ |
| 2219 |
tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]] |
| 2220 |
], |
| 2221 |
) -> None: |
| 2222 |
from _pytest.outcomes import OutcomeException |
| 2223 |
|
| 2224 |
with receive_stream, self._send_stream: |
| 2225 |
async for coro, future in receive_stream: |
| 2226 |
try: |
| 2227 |
retval = await coro |
| 2228 |
except CancelledError as exc: |
| 2229 |
if not future.cancelled(): |
| 2230 |
future.cancel(*exc.args) |
| 2231 |
|
| 2232 |
raise |
| 2233 |
except BaseException as exc: |
| 2234 |
if not future.cancelled(): |
| 2235 |
future.set_exception(exc) |
| 2236 |
|
| 2237 |
if not isinstance(exc, (Exception, OutcomeException)): |
| 2238 |
raise |
| 2239 |
else: |
| 2240 |
if not future.cancelled(): |
| 2241 |
future.set_result(retval) |
| 2242 |
|
| 2243 |
async def _call_in_runner_task( |
| 2244 |
self, |
| 2245 |
func: Callable[P, Awaitable[T_Retval]], |
| 2246 |
*args: P.args, |
| 2247 |
**kwargs: P.kwargs, |
| 2248 |
) -> T_Retval: |
| 2249 |
if not self._runner_task: |
| 2250 |
self._send_stream, receive_stream = create_memory_object_stream[ |
| 2251 |
tuple[Awaitable[Any], asyncio.Future] |
| 2252 |
](1) |
| 2253 |
self._runner_task = self.get_loop().create_task( |
| 2254 |
self._run_tests_and_fixtures(receive_stream) |
| 2255 |
) |
| 2256 |
|
| 2257 |
coro = func(*args, **kwargs) |
| 2258 |
future: asyncio.Future[T_Retval] = self.get_loop().create_future() |
| 2259 |
self._send_stream.send_nowait((coro, future)) |
| 2260 |
return await future |
| 2261 |
|
| 2262 |
def run_asyncgen_fixture( |
| 2263 |
self, |
| 2264 |
fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], |
| 2265 |
kwargs: dict[str, Any], |
| 2266 |
) -> Iterable[T_Retval]: |
| 2267 |
asyncgen = fixture_func(**kwargs) |
| 2268 |
fixturevalue: T_Retval = self.get_loop().run_until_complete( |
| 2269 |
self._call_in_runner_task(asyncgen.asend, None) |
| 2270 |
) |
| 2271 |
self._raise_async_exceptions() |
| 2272 |
|
| 2273 |
yield fixturevalue |
| 2274 |
|
| 2275 |
try: |
| 2276 |
self.get_loop().run_until_complete( |
| 2277 |
self._call_in_runner_task(asyncgen.asend, None) |
| 2278 |
) |
| 2279 |
except StopAsyncIteration: |
| 2280 |
self._raise_async_exceptions() |
| 2281 |
else: |
| 2282 |
self.get_loop().run_until_complete(asyncgen.aclose()) |
| 2283 |
raise RuntimeError("Async generator fixture did not stop") |
| 2284 |
|
| 2285 |
def run_fixture( |
| 2286 |
self, |
| 2287 |
fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], |
| 2288 |
kwargs: dict[str, Any], |
| 2289 |
) -> T_Retval: |
| 2290 |
retval = self.get_loop().run_until_complete( |
| 2291 |
self._call_in_runner_task(fixture_func, **kwargs) |
| 2292 |
) |
| 2293 |
self._raise_async_exceptions() |
| 2294 |
return retval |
| 2295 |
|
| 2296 |
def run_test( |
| 2297 |
self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] |
| 2298 |
) -> None: |
| 2299 |
try: |
| 2300 |
self.get_loop().run_until_complete( |
| 2301 |
self._call_in_runner_task(test_func, **kwargs) |
| 2302 |
) |
| 2303 |
except Exception as exc: |
| 2304 |
self._exceptions.append(exc) |
| 2305 |
|
| 2306 |
self._raise_async_exceptions() |
| 2307 |
|
| 2308 |
|
| 2309 |
class AsyncIOBackend(AsyncBackend): |
| 2310 |
@classmethod |
| 2311 |
def run( |
| 2312 |
cls, |
| 2313 |
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], |
| 2314 |
args: tuple[Unpack[PosArgsT]], |
| 2315 |
kwargs: dict[str, Any], |
| 2316 |
options: dict[str, Any], |
| 2317 |
) -> T_Retval: |
| 2318 |
@wraps(func) |
| 2319 |
async def wrapper() -> T_Retval: |
| 2320 |
task = cast(asyncio.Task, current_task()) |
| 2321 |
task.set_name(get_callable_name(func)) |
| 2322 |
_task_states[task] = TaskState(None, None) |
| 2323 |
|
| 2324 |
try: |
| 2325 |
return await func(*args) |
| 2326 |
finally: |
| 2327 |
del _task_states[task] |
| 2328 |
|
| 2329 |
debug = options.get("debug", None) |
| 2330 |
loop_factory = options.get("loop_factory", None) |
| 2331 |
if loop_factory is None and options.get("use_uvloop", False): |
| 2332 |
if sys.platform != "win32": |
| 2333 |
import uvloop |
| 2334 |
|
| 2335 |
loop_factory = uvloop.new_event_loop |
| 2336 |
else: |
| 2337 |
import winloop |
| 2338 |
|
| 2339 |
loop_factory = winloop.new_event_loop |
| 2340 |
|
| 2341 |
with Runner(debug=debug, loop_factory=loop_factory) as runner: |
| 2342 |
return runner.run(wrapper()) |
| 2343 |
|
| 2344 |
@classmethod |
| 2345 |
def current_token(cls) -> object: |
| 2346 |
return get_running_loop() |
| 2347 |
|
| 2348 |
@classmethod |
| 2349 |
def current_time(cls) -> float: |
| 2350 |
return get_running_loop().time() |
| 2351 |
|
| 2352 |
@classmethod |
| 2353 |
def cancelled_exception_class(cls) -> type[BaseException]: |
| 2354 |
return CancelledError |
| 2355 |
|
| 2356 |
@classmethod |
| 2357 |
async def checkpoint(cls) -> None: |
| 2358 |
await sleep(0) |
| 2359 |
|
| 2360 |
@classmethod |
| 2361 |
async def checkpoint_if_cancelled(cls) -> None: |
| 2362 |
task = current_task() |
| 2363 |
if task is None: |
| 2364 |
return |
| 2365 |
|
| 2366 |
try: |
| 2367 |
cancel_scope = _task_states[task].cancel_scope |
| 2368 |
except KeyError: |
| 2369 |
return |
| 2370 |
|
| 2371 |
while cancel_scope: |
| 2372 |
if cancel_scope.cancel_called: |
| 2373 |
await sleep(0) |
| 2374 |
elif cancel_scope.shield: |
| 2375 |
break |
| 2376 |
else: |
| 2377 |
cancel_scope = cancel_scope._parent_scope |
| 2378 |
|
| 2379 |
@classmethod |
| 2380 |
async def cancel_shielded_checkpoint(cls) -> None: |
| 2381 |
with CancelScope(shield=True): |
| 2382 |
await sleep(0) |
| 2383 |
|
| 2384 |
@classmethod |
| 2385 |
async def sleep(cls, delay: float) -> None: |
| 2386 |
await sleep(delay) |
| 2387 |
|
| 2388 |
@classmethod |
| 2389 |
def create_cancel_scope( |
| 2390 |
cls, *, deadline: float = math.inf, shield: bool = False |
| 2391 |
) -> CancelScope: |
| 2392 |
return CancelScope(deadline=deadline, shield=shield) |
| 2393 |
|
| 2394 |
@classmethod |
| 2395 |
def current_effective_deadline(cls) -> float: |
| 2396 |
if (task := current_task()) is None: |
| 2397 |
return math.inf |
| 2398 |
|
| 2399 |
try: |
| 2400 |
cancel_scope = _task_states[task].cancel_scope |
| 2401 |
except KeyError: |
| 2402 |
return math.inf |
| 2403 |
|
| 2404 |
deadline = math.inf |
| 2405 |
while cancel_scope: |
| 2406 |
deadline = min(deadline, cancel_scope.deadline) |
| 2407 |
if cancel_scope._cancel_called: |
| 2408 |
deadline = -math.inf |
| 2409 |
break |
| 2410 |
elif cancel_scope.shield: |
| 2411 |
break |
| 2412 |
else: |
| 2413 |
cancel_scope = cancel_scope._parent_scope |
| 2414 |
|
| 2415 |
return deadline |
| 2416 |
|
| 2417 |
@classmethod |
| 2418 |
def create_task_group(cls) -> abc.TaskGroup: |
| 2419 |
return TaskGroup() |
| 2420 |
|
| 2421 |
@classmethod |
| 2422 |
def create_event(cls) -> abc.Event: |
| 2423 |
return Event() |
| 2424 |
|
| 2425 |
@classmethod |
| 2426 |
def create_lock(cls, *, fast_acquire: bool) -> abc.Lock: |
| 2427 |
return Lock(fast_acquire=fast_acquire) |
| 2428 |
|
| 2429 |
@classmethod |
| 2430 |
def create_semaphore( |
| 2431 |
cls, |
| 2432 |
initial_value: int, |
| 2433 |
*, |
| 2434 |
max_value: int | None = None, |
| 2435 |
fast_acquire: bool = False, |
| 2436 |
) -> abc.Semaphore: |
| 2437 |
return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) |
| 2438 |
|
| 2439 |
@classmethod |
| 2440 |
def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter: |
| 2441 |
return CapacityLimiter(total_tokens) |
| 2442 |
|
| 2443 |
@classmethod |
| 2444 |
async def run_sync_in_worker_thread( # type: ignore[return] |
| 2445 |
cls, |
| 2446 |
func: Callable[[Unpack[PosArgsT]], T_Retval], |
| 2447 |
args: tuple[Unpack[PosArgsT]], |
| 2448 |
abandon_on_cancel: bool = False, |
| 2449 |
limiter: abc.CapacityLimiter | None = None, |
| 2450 |
) -> T_Retval: |
| 2451 |
await cls.checkpoint() |
| 2452 |
|
| 2453 |
# If this is the first run in this event loop thread, set up the necessary |
| 2454 |
# variables |
| 2455 |
try: |
| 2456 |
idle_workers = _threadpool_idle_workers.get() |
| 2457 |
workers = _threadpool_workers.get() |
| 2458 |
except LookupError: |
| 2459 |
idle_workers = deque() |
| 2460 |
workers = set() |
| 2461 |
_threadpool_idle_workers.set(idle_workers) |
| 2462 |
_threadpool_workers.set(workers) |
| 2463 |
|
| 2464 |
async with limiter or cls.current_default_thread_limiter(): |
| 2465 |
with CancelScope(shield=not abandon_on_cancel) as scope: |
| 2466 |
future = asyncio.Future[T_Retval]() |
| 2467 |
root_task = find_root_task() |
| 2468 |
if not idle_workers: |
| 2469 |
worker = WorkerThread(root_task, workers, idle_workers) |
| 2470 |
worker.start() |
| 2471 |
workers.add(worker) |
| 2472 |
root_task.add_done_callback( |
| 2473 |
worker.stop, context=contextvars.Context() |
| 2474 |
) |
| 2475 |
else: |
| 2476 |
worker = idle_workers.pop() |
| 2477 |
|
| 2478 |
# Prune any other workers that have been idle for MAX_IDLE_TIME |
| 2479 |
# seconds or longer |
| 2480 |
now = cls.current_time() |
| 2481 |
while idle_workers: |
| 2482 |
if ( |
| 2483 |
now - idle_workers[0].idle_since |
| 2484 |
< WorkerThread.MAX_IDLE_TIME |
| 2485 |
): |
| 2486 |
break |
| 2487 |
|
| 2488 |
expired_worker = idle_workers.popleft() |
| 2489 |
expired_worker.root_task.remove_done_callback( |
| 2490 |
expired_worker.stop |
| 2491 |
) |
| 2492 |
expired_worker.stop() |
| 2493 |
|
| 2494 |
context = copy_context() |
| 2495 |
context.run(set_current_async_library, None) |
| 2496 |
if abandon_on_cancel or scope._parent_scope is None: |
| 2497 |
worker_scope = scope |
| 2498 |
else: |
| 2499 |
worker_scope = scope._parent_scope |
| 2500 |
|
| 2501 |
worker.queue.put_nowait((context, func, args, future, worker_scope)) |
| 2502 |
return await future |
| 2503 |
|
| 2504 |
@classmethod |
| 2505 |
def check_cancelled(cls) -> None: |
| 2506 |
scope: CancelScope | None = threadlocals.current_cancel_scope |
| 2507 |
while scope is not None: |
| 2508 |
if scope.cancel_called: |
| 2509 |
raise CancelledError(f"Cancelled by cancel scope {id(scope):x}") |
| 2510 |
|
| 2511 |
if scope.shield: |
| 2512 |
return |
| 2513 |
|
| 2514 |
scope = scope._parent_scope |
| 2515 |
|
| 2516 |
@classmethod |
| 2517 |
def run_async_from_thread( |
| 2518 |
cls, |
| 2519 |
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], |
| 2520 |
args: tuple[Unpack[PosArgsT]], |
| 2521 |
token: object, |
| 2522 |
) -> T_Retval: |
| 2523 |
async def task_wrapper() -> T_Retval: |
| 2524 |
__tracebackhide__ = True |
| 2525 |
if scope is not None: |
| 2526 |
task = cast(asyncio.Task, current_task()) |
| 2527 |
_task_states[task] = TaskState(None, scope) |
| 2528 |
scope._tasks.add(task) |
| 2529 |
try: |
| 2530 |
return await func(*args) |
| 2531 |
except CancelledError as exc: |
| 2532 |
raise concurrent.futures.CancelledError(str(exc)) from None |
| 2533 |
finally: |
| 2534 |
if scope is not None: |
| 2535 |
scope._tasks.discard(task) |
| 2536 |
|
| 2537 |
loop = cast( |
| 2538 |
"AbstractEventLoop", token or threadlocals.current_token.native_token |
| 2539 |
) |
| 2540 |
if loop.is_closed(): |
| 2541 |
raise RunFinishedError |
| 2542 |
|
| 2543 |
context = copy_context() |
| 2544 |
context.run(set_current_async_library, "asyncio") |
| 2545 |
scope = getattr(threadlocals, "current_cancel_scope", None) |
| 2546 |
f: concurrent.futures.Future[T_Retval] = context.run( |
| 2547 |
asyncio.run_coroutine_threadsafe, task_wrapper(), loop=loop |
| 2548 |
) |
| 2549 |
return f.result() |
| 2550 |
|
| 2551 |
@classmethod |
| 2552 |
def run_sync_from_thread( |
| 2553 |
cls, |
| 2554 |
func: Callable[[Unpack[PosArgsT]], T_Retval], |
| 2555 |
args: tuple[Unpack[PosArgsT]], |
| 2556 |
token: object, |
| 2557 |
) -> T_Retval: |
| 2558 |
@wraps(func) |
| 2559 |
def wrapper() -> None: |
| 2560 |
try: |
| 2561 |
set_current_async_library("asyncio") |
| 2562 |
f.set_result(func(*args)) |
| 2563 |
except BaseException as exc: |
| 2564 |
f.set_exception(exc) |
| 2565 |
if not isinstance(exc, Exception): |
| 2566 |
raise |
| 2567 |
|
| 2568 |
loop = cast( |
| 2569 |
"AbstractEventLoop", token or threadlocals.current_token.native_token |
| 2570 |
) |
| 2571 |
if loop.is_closed(): |
| 2572 |
raise RunFinishedError |
| 2573 |
|
| 2574 |
f: concurrent.futures.Future[T_Retval] = Future() |
| 2575 |
loop.call_soon_threadsafe(wrapper) |
| 2576 |
return f.result() |
| 2577 |
|
| 2578 |
@classmethod |
| 2579 |
async def open_process( |
| 2580 |
cls, |
| 2581 |
command: StrOrBytesPath | Sequence[StrOrBytesPath], |
| 2582 |
*, |
| 2583 |
stdin: int | IO[Any] | None, |
| 2584 |
stdout: int | IO[Any] | None, |
| 2585 |
stderr: int | IO[Any] | None, |
| 2586 |
**kwargs: Any, |
| 2587 |
) -> Process: |
| 2588 |
await cls.checkpoint() |
| 2589 |
if isinstance(command, PathLike): |
| 2590 |
command = os.fspath(command) |
| 2591 |
|
| 2592 |
if isinstance(command, (str, bytes)): |
| 2593 |
process = await asyncio.create_subprocess_shell( |
| 2594 |
command, |
| 2595 |
stdin=stdin, |
| 2596 |
stdout=stdout, |
| 2597 |
stderr=stderr, |
| 2598 |
**kwargs, |
| 2599 |
) |
| 2600 |
else: |
| 2601 |
process = await asyncio.create_subprocess_exec( |
| 2602 |
*command, |
| 2603 |
stdin=stdin, |
| 2604 |
stdout=stdout, |
| 2605 |
stderr=stderr, |
| 2606 |
**kwargs, |
| 2607 |
) |
| 2608 |
|
| 2609 |
stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None |
| 2610 |
stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None |
| 2611 |
stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None |
| 2612 |
return Process(process, stdin_stream, stdout_stream, stderr_stream) |
| 2613 |
|
| 2614 |
@classmethod |
| 2615 |
def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: |
| 2616 |
create_task( |
| 2617 |
_shutdown_process_pool_on_exit(workers), |
| 2618 |
name="AnyIO process pool shutdown task", |
| 2619 |
) |
| 2620 |
find_root_task().add_done_callback( |
| 2621 |
partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type] |
| 2622 |
) |
| 2623 |
|
| 2624 |
@classmethod |
| 2625 |
async def connect_tcp( |
| 2626 |
cls, host: str, port: int, local_address: IPSockAddrType | None = None |
| 2627 |
) -> abc.SocketStream: |
| 2628 |
transport, protocol = cast( |
| 2629 |
tuple[asyncio.Transport, StreamProtocol], |
| 2630 |
await get_running_loop().create_connection( |
| 2631 |
StreamProtocol, host, port, local_addr=local_address |
| 2632 |
), |
| 2633 |
) |
| 2634 |
transport.pause_reading() |
| 2635 |
return SocketStream(transport, protocol) |
| 2636 |
|
| 2637 |
@classmethod |
| 2638 |
async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: |
| 2639 |
await cls.checkpoint() |
| 2640 |
loop = get_running_loop() |
| 2641 |
raw_socket = socket.socket(socket.AF_UNIX) |
| 2642 |
raw_socket.setblocking(False) |
| 2643 |
while True: |
| 2644 |
try: |
| 2645 |
raw_socket.connect(path) |
| 2646 |
except BlockingIOError: |
| 2647 |
f: asyncio.Future = asyncio.Future() |
| 2648 |
loop.add_writer(raw_socket, f.set_result, None) |
| 2649 |
f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) |
| 2650 |
await f |
| 2651 |
except BaseException: |
| 2652 |
raw_socket.close() |
| 2653 |
raise |
| 2654 |
else: |
| 2655 |
return UNIXSocketStream(raw_socket) |
| 2656 |
|
| 2657 |
@classmethod |
| 2658 |
def create_tcp_listener(cls, sock: socket.socket) -> SocketListener: |
| 2659 |
return TCPSocketListener(sock) |
| 2660 |
|
| 2661 |
@classmethod |
| 2662 |
def create_unix_listener(cls, sock: socket.socket) -> SocketListener: |
| 2663 |
return UNIXSocketListener(sock) |
| 2664 |
|
| 2665 |
@classmethod |
| 2666 |
async def create_udp_socket( |
| 2667 |
cls, |
| 2668 |
family: AddressFamily, |
| 2669 |
local_address: IPSockAddrType | None, |
| 2670 |
remote_address: IPSockAddrType | None, |
| 2671 |
reuse_port: bool, |
| 2672 |
) -> UDPSocket | ConnectedUDPSocket: |
| 2673 |
transport, protocol = await get_running_loop().create_datagram_endpoint( |
| 2674 |
DatagramProtocol, |
| 2675 |
local_addr=local_address, |
| 2676 |
remote_addr=remote_address, |
| 2677 |
family=family, |
| 2678 |
reuse_port=reuse_port, |
| 2679 |
) |
| 2680 |
if protocol.exception: |
| 2681 |
transport.close() |
| 2682 |
raise protocol.exception |
| 2683 |
|
| 2684 |
if not remote_address: |
| 2685 |
return UDPSocket(transport, protocol) |
| 2686 |
else: |
| 2687 |
return ConnectedUDPSocket(transport, protocol) |
| 2688 |
|
| 2689 |
@classmethod |
| 2690 |
async def create_unix_datagram_socket( # type: ignore[override] |
| 2691 |
cls, raw_socket: socket.socket, remote_path: str | bytes | None |
| 2692 |
) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: |
| 2693 |
await cls.checkpoint() |
| 2694 |
loop = get_running_loop() |
| 2695 |
|
| 2696 |
if remote_path: |
| 2697 |
while True: |
| 2698 |
try: |
| 2699 |
raw_socket.connect(remote_path) |
| 2700 |
except BlockingIOError: |
| 2701 |
f: asyncio.Future = asyncio.Future() |
| 2702 |
loop.add_writer(raw_socket, f.set_result, None) |
| 2703 |
f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) |
| 2704 |
await f |
| 2705 |
except BaseException: |
| 2706 |
raw_socket.close() |
| 2707 |
raise |
| 2708 |
else: |
| 2709 |
return ConnectedUNIXDatagramSocket(raw_socket) |
| 2710 |
else: |
| 2711 |
return UNIXDatagramSocket(raw_socket) |
| 2712 |
|
| 2713 |
@classmethod |
| 2714 |
async def getaddrinfo( |
| 2715 |
cls, |
| 2716 |
host: bytes | str | None, |
| 2717 |
port: str | int | None, |
| 2718 |
*, |
| 2719 |
family: int | AddressFamily = 0, |
| 2720 |
type: int | SocketKind = 0, |
| 2721 |
proto: int = 0, |
| 2722 |
flags: int = 0, |
| 2723 |
) -> Sequence[ |
| 2724 |
tuple[ |
| 2725 |
AddressFamily, |
| 2726 |
SocketKind, |
| 2727 |
int, |
| 2728 |
str, |
| 2729 |
tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], |
| 2730 |
] |
| 2731 |
]: |
| 2732 |
return await get_running_loop().getaddrinfo( |
| 2733 |
host, port, family=family, type=type, proto=proto, flags=flags |
| 2734 |
) |
| 2735 |
|
| 2736 |
@classmethod |
| 2737 |
async def getnameinfo( |
| 2738 |
cls, sockaddr: IPSockAddrType, flags: int = 0 |
| 2739 |
) -> tuple[str, str]: |
| 2740 |
return await get_running_loop().getnameinfo(sockaddr, flags) |
| 2741 |
|
| 2742 |
@classmethod |
| 2743 |
async def wait_readable(cls, obj: FileDescriptorLike) -> None: |
| 2744 |
try: |
| 2745 |
read_events = _read_events.get() |
| 2746 |
except LookupError: |
| 2747 |
read_events = {} |
| 2748 |
_read_events.set(read_events) |
| 2749 |
|
| 2750 |
fd = obj if isinstance(obj, int) else obj.fileno() |
| 2751 |
if read_events.get(fd): |
| 2752 |
raise BusyResourceError("reading from") |
| 2753 |
|
| 2754 |
loop = get_running_loop() |
| 2755 |
fut: asyncio.Future[bool] = loop.create_future() |
| 2756 |
|
| 2757 |
def cb() -> None: |
| 2758 |
try: |
| 2759 |
del read_events[fd] |
| 2760 |
except KeyError: |
| 2761 |
pass |
| 2762 |
else: |
| 2763 |
remove_reader(fd) |
| 2764 |
|
| 2765 |
try: |
| 2766 |
fut.set_result(True) |
| 2767 |
except asyncio.InvalidStateError: |
| 2768 |
pass |
| 2769 |
|
| 2770 |
try: |
| 2771 |
loop.add_reader(fd, cb) |
| 2772 |
except NotImplementedError: |
| 2773 |
from anyio._core._asyncio_selector_thread import get_selector |
| 2774 |
|
| 2775 |
selector = get_selector() |
| 2776 |
selector.add_reader(fd, cb) |
| 2777 |
remove_reader = selector.remove_reader |
| 2778 |
else: |
| 2779 |
remove_reader = loop.remove_reader |
| 2780 |
|
| 2781 |
read_events[fd] = fut |
| 2782 |
try: |
| 2783 |
success = await fut |
| 2784 |
finally: |
| 2785 |
try: |
| 2786 |
del read_events[fd] |
| 2787 |
except KeyError: |
| 2788 |
pass |
| 2789 |
else: |
| 2790 |
remove_reader(fd) |
| 2791 |
|
| 2792 |
if not success: |
| 2793 |
raise ClosedResourceError |
| 2794 |
|
| 2795 |
@classmethod |
| 2796 |
async def wait_writable(cls, obj: FileDescriptorLike) -> None: |
| 2797 |
try: |
| 2798 |
write_events = _write_events.get() |
| 2799 |
except LookupError: |
| 2800 |
write_events = {} |
| 2801 |
_write_events.set(write_events) |
| 2802 |
|
| 2803 |
fd = obj if isinstance(obj, int) else obj.fileno() |
| 2804 |
if write_events.get(fd): |
| 2805 |
raise BusyResourceError("writing to") |
| 2806 |
|
| 2807 |
loop = get_running_loop() |
| 2808 |
fut: asyncio.Future[bool] = loop.create_future() |
| 2809 |
|
| 2810 |
def cb() -> None: |
| 2811 |
try: |
| 2812 |
del write_events[fd] |
| 2813 |
except KeyError: |
| 2814 |
pass |
| 2815 |
else: |
| 2816 |
remove_writer(fd) |
| 2817 |
|
| 2818 |
try: |
| 2819 |
fut.set_result(True) |
| 2820 |
except asyncio.InvalidStateError: |
| 2821 |
pass |
| 2822 |
|
| 2823 |
try: |
| 2824 |
loop.add_writer(fd, cb) |
| 2825 |
except NotImplementedError: |
| 2826 |
from anyio._core._asyncio_selector_thread import get_selector |
| 2827 |
|
| 2828 |
selector = get_selector() |
| 2829 |
selector.add_writer(fd, cb) |
| 2830 |
remove_writer = selector.remove_writer |
| 2831 |
else: |
| 2832 |
remove_writer = loop.remove_writer |
| 2833 |
|
| 2834 |
write_events[fd] = fut |
| 2835 |
try: |
| 2836 |
success = await fut |
| 2837 |
finally: |
| 2838 |
try: |
| 2839 |
del write_events[fd] |
| 2840 |
except KeyError: |
| 2841 |
pass |
| 2842 |
else: |
| 2843 |
remove_writer(fd) |
| 2844 |
|
| 2845 |
if not success: |
| 2846 |
raise ClosedResourceError |
| 2847 |
|
| 2848 |
@classmethod |
| 2849 |
def notify_closing(cls, obj: FileDescriptorLike) -> None: |
| 2850 |
fd = obj if isinstance(obj, int) else obj.fileno() |
| 2851 |
loop = get_running_loop() |
| 2852 |
|
| 2853 |
try: |
| 2854 |
write_events = _write_events.get() |
| 2855 |
except LookupError: |
| 2856 |
pass |
| 2857 |
else: |
| 2858 |
try: |
| 2859 |
fut = write_events.pop(fd) |
| 2860 |
except KeyError: |
| 2861 |
pass |
| 2862 |
else: |
| 2863 |
try: |
| 2864 |
fut.set_result(False) |
| 2865 |
except asyncio.InvalidStateError: |
| 2866 |
pass |
| 2867 |
|
| 2868 |
try: |
| 2869 |
loop.remove_writer(fd) |
| 2870 |
except NotImplementedError: |
| 2871 |
from anyio._core._asyncio_selector_thread import get_selector |
| 2872 |
|
| 2873 |
get_selector().remove_writer(fd) |
| 2874 |
|
| 2875 |
try: |
| 2876 |
read_events = _read_events.get() |
| 2877 |
except LookupError: |
| 2878 |
pass |
| 2879 |
else: |
| 2880 |
try: |
| 2881 |
fut = read_events.pop(fd) |
| 2882 |
except KeyError: |
| 2883 |
pass |
| 2884 |
else: |
| 2885 |
try: |
| 2886 |
fut.set_result(False) |
| 2887 |
except asyncio.InvalidStateError: |
| 2888 |
pass |
| 2889 |
|
| 2890 |
try: |
| 2891 |
loop.remove_reader(fd) |
| 2892 |
except NotImplementedError: |
| 2893 |
from anyio._core._asyncio_selector_thread import get_selector |
| 2894 |
|
| 2895 |
get_selector().remove_reader(fd) |
| 2896 |
|
| 2897 |
@classmethod |
| 2898 |
async def wrap_listener_socket(cls, sock: socket.socket) -> SocketListener: |
| 2899 |
return TCPSocketListener(sock) |
| 2900 |
|
| 2901 |
@classmethod |
| 2902 |
async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: |
| 2903 |
transport, protocol = await get_running_loop().create_connection( |
| 2904 |
StreamProtocol, sock=sock |
| 2905 |
) |
| 2906 |
return SocketStream(transport, protocol) |
| 2907 |
|
| 2908 |
@classmethod |
| 2909 |
async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: |
| 2910 |
return UNIXSocketStream(sock) |
| 2911 |
|
| 2912 |
@classmethod |
| 2913 |
async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: |
| 2914 |
transport, protocol = await get_running_loop().create_datagram_endpoint( |
| 2915 |
DatagramProtocol, sock=sock |
| 2916 |
) |
| 2917 |
return UDPSocket(transport, protocol) |
| 2918 |
|
| 2919 |
@classmethod |
| 2920 |
async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: |
| 2921 |
transport, protocol = await get_running_loop().create_datagram_endpoint( |
| 2922 |
DatagramProtocol, sock=sock |
| 2923 |
) |
| 2924 |
return ConnectedUDPSocket(transport, protocol) |
| 2925 |
|
| 2926 |
@classmethod |
| 2927 |
async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: |
| 2928 |
return UNIXDatagramSocket(sock) |
| 2929 |
|
| 2930 |
@classmethod |
| 2931 |
async def wrap_connected_unix_datagram_socket( |
| 2932 |
cls, sock: socket.socket |
| 2933 |
) -> ConnectedUNIXDatagramSocket: |
| 2934 |
return ConnectedUNIXDatagramSocket(sock) |
| 2935 |
|
| 2936 |
@classmethod |
| 2937 |
def current_default_thread_limiter(cls) -> CapacityLimiter: |
| 2938 |
try: |
| 2939 |
return _default_thread_limiter.get() |
| 2940 |
except LookupError: |
| 2941 |
limiter = CapacityLimiter(40) |
| 2942 |
_default_thread_limiter.set(limiter) |
| 2943 |
return limiter |
| 2944 |
|
| 2945 |
@classmethod |
| 2946 |
def open_signal_receiver( |
| 2947 |
cls, *signals: Signals |
| 2948 |
) -> AbstractContextManager[AsyncIterator[Signals]]: |
| 2949 |
return _SignalReceiver(signals) |
| 2950 |
|
| 2951 |
@classmethod |
| 2952 |
def get_current_task(cls) -> TaskInfo: |
| 2953 |
return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type] |
| 2954 |
|
| 2955 |
@classmethod |
| 2956 |
def get_running_tasks(cls) -> Sequence[TaskInfo]: |
| 2957 |
return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()] |
| 2958 |
|
| 2959 |
@classmethod |
| 2960 |
async def wait_all_tasks_blocked(cls) -> None: |
| 2961 |
await cls.checkpoint() |
| 2962 |
this_task = current_task() |
| 2963 |
while True: |
| 2964 |
for task in all_tasks(): |
| 2965 |
if task is this_task: |
| 2966 |
continue |
| 2967 |
|
| 2968 |
waiter = task._fut_waiter # type: ignore[attr-defined] |
| 2969 |
if waiter is None or waiter.done(): |
| 2970 |
await sleep(0.1) |
| 2971 |
break |
| 2972 |
else: |
| 2973 |
return |
| 2974 |
|
| 2975 |
@classmethod |
| 2976 |
def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: |
| 2977 |
return TestRunner(**options) |
| 2978 |
|
| 2979 |
|
| 2980 |
backend_class = AsyncIOBackend |