Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/__init__.py +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/_asyncio.py +2851 -0
- minigpt2/lib/python3.10/site-packages/anyio/_backends/_trio.py +1334 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__init__.py +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_eventloop.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_exceptions.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_fileio.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_resources.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_signals.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_sockets.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_streams.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_synchronization.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_tasks.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_testing.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_typedattr.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py +150 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_eventloop.py +166 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_exceptions.py +89 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_fileio.py +674 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_resources.py +18 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_signals.py +27 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_sockets.py +787 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_streams.py +52 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_subprocesses.py +196 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_synchronization.py +733 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_tasks.py +158 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_testing.py +78 -0
- minigpt2/lib/python3.10/site-packages/anyio/_core/_typedattr.py +81 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/__init__.py +55 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_resources.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_streams.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_tasks.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_eventloop.py +376 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_resources.py +33 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_sockets.py +194 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_streams.py +203 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_subprocesses.py +79 -0
- minigpt2/lib/python3.10/site-packages/anyio/abc/_tasks.py +101 -0
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.99 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc
ADDED
|
Binary file (17.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc
ADDED
|
Binary file (5.15 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc
ADDED
|
Binary file (5.92 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc
ADDED
|
Binary file (6.58 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc
ADDED
|
Binary file (2.6 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_backends/__init__.py
ADDED
|
File without changes
|
minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (169 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc
ADDED
|
Binary file (78.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc
ADDED
|
Binary file (44.2 kB). View file
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import array
|
| 4 |
+
import asyncio
|
| 5 |
+
import concurrent.futures
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import socket
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
import weakref
|
| 12 |
+
from asyncio import (
|
| 13 |
+
AbstractEventLoop,
|
| 14 |
+
CancelledError,
|
| 15 |
+
all_tasks,
|
| 16 |
+
create_task,
|
| 17 |
+
current_task,
|
| 18 |
+
get_running_loop,
|
| 19 |
+
sleep,
|
| 20 |
+
)
|
| 21 |
+
from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined]
|
| 22 |
+
from collections import OrderedDict, deque
|
| 23 |
+
from collections.abc import (
|
| 24 |
+
AsyncGenerator,
|
| 25 |
+
AsyncIterator,
|
| 26 |
+
Awaitable,
|
| 27 |
+
Callable,
|
| 28 |
+
Collection,
|
| 29 |
+
Coroutine,
|
| 30 |
+
Iterable,
|
| 31 |
+
Iterator,
|
| 32 |
+
MutableMapping,
|
| 33 |
+
Sequence,
|
| 34 |
+
)
|
| 35 |
+
from concurrent.futures import Future
|
| 36 |
+
from contextlib import AbstractContextManager, suppress
|
| 37 |
+
from contextvars import Context, copy_context
|
| 38 |
+
from dataclasses import dataclass
|
| 39 |
+
from functools import partial, wraps
|
| 40 |
+
from inspect import (
|
| 41 |
+
CORO_RUNNING,
|
| 42 |
+
CORO_SUSPENDED,
|
| 43 |
+
getcoroutinestate,
|
| 44 |
+
iscoroutine,
|
| 45 |
+
)
|
| 46 |
+
from io import IOBase
|
| 47 |
+
from os import PathLike
|
| 48 |
+
from queue import Queue
|
| 49 |
+
from signal import Signals
|
| 50 |
+
from socket import AddressFamily, SocketKind
|
| 51 |
+
from threading import Thread
|
| 52 |
+
from types import TracebackType
|
| 53 |
+
from typing import (
|
| 54 |
+
IO,
|
| 55 |
+
TYPE_CHECKING,
|
| 56 |
+
Any,
|
| 57 |
+
Optional,
|
| 58 |
+
TypeVar,
|
| 59 |
+
cast,
|
| 60 |
+
)
|
| 61 |
+
from weakref import WeakKeyDictionary
|
| 62 |
+
|
| 63 |
+
import sniffio
|
| 64 |
+
|
| 65 |
+
from .. import (
|
| 66 |
+
CapacityLimiterStatistics,
|
| 67 |
+
EventStatistics,
|
| 68 |
+
LockStatistics,
|
| 69 |
+
TaskInfo,
|
| 70 |
+
abc,
|
| 71 |
+
)
|
| 72 |
+
from .._core._eventloop import claim_worker_thread, threadlocals
|
| 73 |
+
from .._core._exceptions import (
|
| 74 |
+
BrokenResourceError,
|
| 75 |
+
BusyResourceError,
|
| 76 |
+
ClosedResourceError,
|
| 77 |
+
EndOfStream,
|
| 78 |
+
WouldBlock,
|
| 79 |
+
iterate_exceptions,
|
| 80 |
+
)
|
| 81 |
+
from .._core._sockets import convert_ipv6_sockaddr
|
| 82 |
+
from .._core._streams import create_memory_object_stream
|
| 83 |
+
from .._core._synchronization import (
|
| 84 |
+
CapacityLimiter as BaseCapacityLimiter,
|
| 85 |
+
)
|
| 86 |
+
from .._core._synchronization import Event as BaseEvent
|
| 87 |
+
from .._core._synchronization import Lock as BaseLock
|
| 88 |
+
from .._core._synchronization import (
|
| 89 |
+
ResourceGuard,
|
| 90 |
+
SemaphoreStatistics,
|
| 91 |
+
)
|
| 92 |
+
from .._core._synchronization import Semaphore as BaseSemaphore
|
| 93 |
+
from .._core._tasks import CancelScope as BaseCancelScope
|
| 94 |
+
from ..abc import (
|
| 95 |
+
AsyncBackend,
|
| 96 |
+
IPSockAddrType,
|
| 97 |
+
SocketListener,
|
| 98 |
+
UDPPacketType,
|
| 99 |
+
UNIXDatagramPacketType,
|
| 100 |
+
)
|
| 101 |
+
from ..abc._eventloop import StrOrBytesPath
|
| 102 |
+
from ..lowlevel import RunVar
|
| 103 |
+
from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
|
| 104 |
+
|
| 105 |
+
if TYPE_CHECKING:
|
| 106 |
+
from _typeshed import FileDescriptorLike
|
| 107 |
+
else:
|
| 108 |
+
FileDescriptorLike = object
|
| 109 |
+
|
| 110 |
+
if sys.version_info >= (3, 10):
|
| 111 |
+
from typing import ParamSpec
|
| 112 |
+
else:
|
| 113 |
+
from typing_extensions import ParamSpec
|
| 114 |
+
|
| 115 |
+
if sys.version_info >= (3, 11):
|
| 116 |
+
from asyncio import Runner
|
| 117 |
+
from typing import TypeVarTuple, Unpack
|
| 118 |
+
else:
|
| 119 |
+
import contextvars
|
| 120 |
+
import enum
|
| 121 |
+
import signal
|
| 122 |
+
from asyncio import coroutines, events, exceptions, tasks
|
| 123 |
+
|
| 124 |
+
from exceptiongroup import BaseExceptionGroup
|
| 125 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 126 |
+
|
| 127 |
+
class _State(enum.Enum):
|
| 128 |
+
CREATED = "created"
|
| 129 |
+
INITIALIZED = "initialized"
|
| 130 |
+
CLOSED = "closed"
|
| 131 |
+
|
| 132 |
+
class Runner:
|
| 133 |
+
# Copied from CPython 3.11
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
*,
|
| 137 |
+
debug: bool | None = None,
|
| 138 |
+
loop_factory: Callable[[], AbstractEventLoop] | None = None,
|
| 139 |
+
):
|
| 140 |
+
self._state = _State.CREATED
|
| 141 |
+
self._debug = debug
|
| 142 |
+
self._loop_factory = loop_factory
|
| 143 |
+
self._loop: AbstractEventLoop | None = None
|
| 144 |
+
self._context = None
|
| 145 |
+
self._interrupt_count = 0
|
| 146 |
+
self._set_event_loop = False
|
| 147 |
+
|
| 148 |
+
def __enter__(self) -> Runner:
|
| 149 |
+
self._lazy_init()
|
| 150 |
+
return self
|
| 151 |
+
|
| 152 |
+
def __exit__(
|
| 153 |
+
self,
|
| 154 |
+
exc_type: type[BaseException],
|
| 155 |
+
exc_val: BaseException,
|
| 156 |
+
exc_tb: TracebackType,
|
| 157 |
+
) -> None:
|
| 158 |
+
self.close()
|
| 159 |
+
|
| 160 |
+
def close(self) -> None:
|
| 161 |
+
"""Shutdown and close event loop."""
|
| 162 |
+
if self._state is not _State.INITIALIZED:
|
| 163 |
+
return
|
| 164 |
+
try:
|
| 165 |
+
loop = self._loop
|
| 166 |
+
_cancel_all_tasks(loop)
|
| 167 |
+
loop.run_until_complete(loop.shutdown_asyncgens())
|
| 168 |
+
if hasattr(loop, "shutdown_default_executor"):
|
| 169 |
+
loop.run_until_complete(loop.shutdown_default_executor())
|
| 170 |
+
else:
|
| 171 |
+
loop.run_until_complete(_shutdown_default_executor(loop))
|
| 172 |
+
finally:
|
| 173 |
+
if self._set_event_loop:
|
| 174 |
+
events.set_event_loop(None)
|
| 175 |
+
loop.close()
|
| 176 |
+
self._loop = None
|
| 177 |
+
self._state = _State.CLOSED
|
| 178 |
+
|
| 179 |
+
def get_loop(self) -> AbstractEventLoop:
|
| 180 |
+
"""Return embedded event loop."""
|
| 181 |
+
self._lazy_init()
|
| 182 |
+
return self._loop
|
| 183 |
+
|
| 184 |
+
def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval:
|
| 185 |
+
"""Run a coroutine inside the embedded event loop."""
|
| 186 |
+
if not coroutines.iscoroutine(coro):
|
| 187 |
+
raise ValueError(f"a coroutine was expected, got {coro!r}")
|
| 188 |
+
|
| 189 |
+
if events._get_running_loop() is not None:
|
| 190 |
+
# fail fast with short traceback
|
| 191 |
+
raise RuntimeError(
|
| 192 |
+
"Runner.run() cannot be called from a running event loop"
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
self._lazy_init()
|
| 196 |
+
|
| 197 |
+
if context is None:
|
| 198 |
+
context = self._context
|
| 199 |
+
task = context.run(self._loop.create_task, coro)
|
| 200 |
+
|
| 201 |
+
if (
|
| 202 |
+
threading.current_thread() is threading.main_thread()
|
| 203 |
+
and signal.getsignal(signal.SIGINT) is signal.default_int_handler
|
| 204 |
+
):
|
| 205 |
+
sigint_handler = partial(self._on_sigint, main_task=task)
|
| 206 |
+
try:
|
| 207 |
+
signal.signal(signal.SIGINT, sigint_handler)
|
| 208 |
+
except ValueError:
|
| 209 |
+
# `signal.signal` may throw if `threading.main_thread` does
|
| 210 |
+
# not support signals (e.g. embedded interpreter with signals
|
| 211 |
+
# not registered - see gh-91880)
|
| 212 |
+
sigint_handler = None
|
| 213 |
+
else:
|
| 214 |
+
sigint_handler = None
|
| 215 |
+
|
| 216 |
+
self._interrupt_count = 0
|
| 217 |
+
try:
|
| 218 |
+
return self._loop.run_until_complete(task)
|
| 219 |
+
except exceptions.CancelledError:
|
| 220 |
+
if self._interrupt_count > 0:
|
| 221 |
+
uncancel = getattr(task, "uncancel", None)
|
| 222 |
+
if uncancel is not None and uncancel() == 0:
|
| 223 |
+
raise KeyboardInterrupt()
|
| 224 |
+
raise # CancelledError
|
| 225 |
+
finally:
|
| 226 |
+
if (
|
| 227 |
+
sigint_handler is not None
|
| 228 |
+
and signal.getsignal(signal.SIGINT) is sigint_handler
|
| 229 |
+
):
|
| 230 |
+
signal.signal(signal.SIGINT, signal.default_int_handler)
|
| 231 |
+
|
| 232 |
+
def _lazy_init(self) -> None:
|
| 233 |
+
if self._state is _State.CLOSED:
|
| 234 |
+
raise RuntimeError("Runner is closed")
|
| 235 |
+
if self._state is _State.INITIALIZED:
|
| 236 |
+
return
|
| 237 |
+
if self._loop_factory is None:
|
| 238 |
+
self._loop = events.new_event_loop()
|
| 239 |
+
if not self._set_event_loop:
|
| 240 |
+
# Call set_event_loop only once to avoid calling
|
| 241 |
+
# attach_loop multiple times on child watchers
|
| 242 |
+
events.set_event_loop(self._loop)
|
| 243 |
+
self._set_event_loop = True
|
| 244 |
+
else:
|
| 245 |
+
self._loop = self._loop_factory()
|
| 246 |
+
if self._debug is not None:
|
| 247 |
+
self._loop.set_debug(self._debug)
|
| 248 |
+
self._context = contextvars.copy_context()
|
| 249 |
+
self._state = _State.INITIALIZED
|
| 250 |
+
|
| 251 |
+
def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None:
|
| 252 |
+
self._interrupt_count += 1
|
| 253 |
+
if self._interrupt_count == 1 and not main_task.done():
|
| 254 |
+
main_task.cancel()
|
| 255 |
+
# wakeup loop if it is blocked by select() with long timeout
|
| 256 |
+
self._loop.call_soon_threadsafe(lambda: None)
|
| 257 |
+
return
|
| 258 |
+
raise KeyboardInterrupt()
|
| 259 |
+
|
| 260 |
+
def _cancel_all_tasks(loop: AbstractEventLoop) -> None:
|
| 261 |
+
to_cancel = tasks.all_tasks(loop)
|
| 262 |
+
if not to_cancel:
|
| 263 |
+
return
|
| 264 |
+
|
| 265 |
+
for task in to_cancel:
|
| 266 |
+
task.cancel()
|
| 267 |
+
|
| 268 |
+
loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
|
| 269 |
+
|
| 270 |
+
for task in to_cancel:
|
| 271 |
+
if task.cancelled():
|
| 272 |
+
continue
|
| 273 |
+
if task.exception() is not None:
|
| 274 |
+
loop.call_exception_handler(
|
| 275 |
+
{
|
| 276 |
+
"message": "unhandled exception during asyncio.run() shutdown",
|
| 277 |
+
"exception": task.exception(),
|
| 278 |
+
"task": task,
|
| 279 |
+
}
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
async def _shutdown_default_executor(loop: AbstractEventLoop) -> None:
|
| 283 |
+
"""Schedule the shutdown of the default executor."""
|
| 284 |
+
|
| 285 |
+
def _do_shutdown(future: asyncio.futures.Future) -> None:
|
| 286 |
+
try:
|
| 287 |
+
loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined]
|
| 288 |
+
loop.call_soon_threadsafe(future.set_result, None)
|
| 289 |
+
except Exception as ex:
|
| 290 |
+
loop.call_soon_threadsafe(future.set_exception, ex)
|
| 291 |
+
|
| 292 |
+
loop._executor_shutdown_called = True
|
| 293 |
+
if loop._default_executor is None:
|
| 294 |
+
return
|
| 295 |
+
future = loop.create_future()
|
| 296 |
+
thread = threading.Thread(target=_do_shutdown, args=(future,))
|
| 297 |
+
thread.start()
|
| 298 |
+
try:
|
| 299 |
+
await future
|
| 300 |
+
finally:
|
| 301 |
+
thread.join()
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
T_Retval = TypeVar("T_Retval")
|
| 305 |
+
T_contra = TypeVar("T_contra", contravariant=True)
|
| 306 |
+
PosArgsT = TypeVarTuple("PosArgsT")
|
| 307 |
+
P = ParamSpec("P")
|
| 308 |
+
|
| 309 |
+
_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def find_root_task() -> asyncio.Task:
|
| 313 |
+
root_task = _root_task.get(None)
|
| 314 |
+
if root_task is not None and not root_task.done():
|
| 315 |
+
return root_task
|
| 316 |
+
|
| 317 |
+
# Look for a task that has been started via run_until_complete()
|
| 318 |
+
for task in all_tasks():
|
| 319 |
+
if task._callbacks and not task.done():
|
| 320 |
+
callbacks = [cb for cb, context in task._callbacks]
|
| 321 |
+
for cb in callbacks:
|
| 322 |
+
if (
|
| 323 |
+
cb is _run_until_complete_cb
|
| 324 |
+
or getattr(cb, "__module__", None) == "uvloop.loop"
|
| 325 |
+
):
|
| 326 |
+
_root_task.set(task)
|
| 327 |
+
return task
|
| 328 |
+
|
| 329 |
+
# Look up the topmost task in the AnyIO task tree, if possible
|
| 330 |
+
task = cast(asyncio.Task, current_task())
|
| 331 |
+
state = _task_states.get(task)
|
| 332 |
+
if state:
|
| 333 |
+
cancel_scope = state.cancel_scope
|
| 334 |
+
while cancel_scope and cancel_scope._parent_scope is not None:
|
| 335 |
+
cancel_scope = cancel_scope._parent_scope
|
| 336 |
+
|
| 337 |
+
if cancel_scope is not None:
|
| 338 |
+
return cast(asyncio.Task, cancel_scope._host_task)
|
| 339 |
+
|
| 340 |
+
return task
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def get_callable_name(func: Callable) -> str:
|
| 344 |
+
module = getattr(func, "__module__", None)
|
| 345 |
+
qualname = getattr(func, "__qualname__", None)
|
| 346 |
+
return ".".join([x for x in (module, qualname) if x])
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
#
|
| 350 |
+
# Event loop
|
| 351 |
+
#
|
| 352 |
+
|
| 353 |
+
_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary()
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _task_started(task: asyncio.Task) -> bool:
|
| 357 |
+
"""Return ``True`` if the task has been started and has not finished."""
|
| 358 |
+
# The task coro should never be None here, as we never add finished tasks to the
|
| 359 |
+
# task list
|
| 360 |
+
coro = task.get_coro()
|
| 361 |
+
assert coro is not None
|
| 362 |
+
try:
|
| 363 |
+
return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED)
|
| 364 |
+
except AttributeError:
|
| 365 |
+
# task coro is async_genenerator_asend https://bugs.python.org/issue37771
|
| 366 |
+
raise Exception(f"Cannot determine if task {task} has started or not") from None
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
#
|
| 370 |
+
# Timeouts and cancellation
|
| 371 |
+
#
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def is_anyio_cancellation(exc: CancelledError) -> bool:
|
| 375 |
+
# Sometimes third party frameworks catch a CancelledError and raise a new one, so as
|
| 376 |
+
# a workaround we have to look at the previous ones in __context__ too for a
|
| 377 |
+
# matching cancel message
|
| 378 |
+
while True:
|
| 379 |
+
if (
|
| 380 |
+
exc.args
|
| 381 |
+
and isinstance(exc.args[0], str)
|
| 382 |
+
and exc.args[0].startswith("Cancelled by cancel scope ")
|
| 383 |
+
):
|
| 384 |
+
return True
|
| 385 |
+
|
| 386 |
+
if isinstance(exc.__context__, CancelledError):
|
| 387 |
+
exc = exc.__context__
|
| 388 |
+
continue
|
| 389 |
+
|
| 390 |
+
return False
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class CancelScope(BaseCancelScope):
|
| 394 |
+
def __new__(
|
| 395 |
+
cls, *, deadline: float = math.inf, shield: bool = False
|
| 396 |
+
) -> CancelScope:
|
| 397 |
+
return object.__new__(cls)
|
| 398 |
+
|
| 399 |
+
def __init__(self, deadline: float = math.inf, shield: bool = False):
|
| 400 |
+
self._deadline = deadline
|
| 401 |
+
self._shield = shield
|
| 402 |
+
self._parent_scope: CancelScope | None = None
|
| 403 |
+
self._child_scopes: set[CancelScope] = set()
|
| 404 |
+
self._cancel_called = False
|
| 405 |
+
self._cancelled_caught = False
|
| 406 |
+
self._active = False
|
| 407 |
+
self._timeout_handle: asyncio.TimerHandle | None = None
|
| 408 |
+
self._cancel_handle: asyncio.Handle | None = None
|
| 409 |
+
self._tasks: set[asyncio.Task] = set()
|
| 410 |
+
self._host_task: asyncio.Task | None = None
|
| 411 |
+
if sys.version_info >= (3, 11):
|
| 412 |
+
self._pending_uncancellations: int | None = 0
|
| 413 |
+
else:
|
| 414 |
+
self._pending_uncancellations = None
|
| 415 |
+
|
| 416 |
+
def __enter__(self) -> CancelScope:
|
| 417 |
+
if self._active:
|
| 418 |
+
raise RuntimeError(
|
| 419 |
+
"Each CancelScope may only be used for a single 'with' block"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
self._host_task = host_task = cast(asyncio.Task, current_task())
|
| 423 |
+
self._tasks.add(host_task)
|
| 424 |
+
try:
|
| 425 |
+
task_state = _task_states[host_task]
|
| 426 |
+
except KeyError:
|
| 427 |
+
task_state = TaskState(None, self)
|
| 428 |
+
_task_states[host_task] = task_state
|
| 429 |
+
else:
|
| 430 |
+
self._parent_scope = task_state.cancel_scope
|
| 431 |
+
task_state.cancel_scope = self
|
| 432 |
+
if self._parent_scope is not None:
|
| 433 |
+
# If using an eager task factory, the parent scope may not even contain
|
| 434 |
+
# the host task
|
| 435 |
+
self._parent_scope._child_scopes.add(self)
|
| 436 |
+
self._parent_scope._tasks.discard(host_task)
|
| 437 |
+
|
| 438 |
+
self._timeout()
|
| 439 |
+
self._active = True
|
| 440 |
+
|
| 441 |
+
# Start cancelling the host task if the scope was cancelled before entering
|
| 442 |
+
if self._cancel_called:
|
| 443 |
+
self._deliver_cancellation(self)
|
| 444 |
+
|
| 445 |
+
return self
|
| 446 |
+
|
| 447 |
+
def __exit__(
|
| 448 |
+
self,
|
| 449 |
+
exc_type: type[BaseException] | None,
|
| 450 |
+
exc_val: BaseException | None,
|
| 451 |
+
exc_tb: TracebackType | None,
|
| 452 |
+
) -> bool | None:
|
| 453 |
+
del exc_tb
|
| 454 |
+
|
| 455 |
+
if not self._active:
|
| 456 |
+
raise RuntimeError("This cancel scope is not active")
|
| 457 |
+
if current_task() is not self._host_task:
|
| 458 |
+
raise RuntimeError(
|
| 459 |
+
"Attempted to exit cancel scope in a different task than it was "
|
| 460 |
+
"entered in"
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
assert self._host_task is not None
|
| 464 |
+
host_task_state = _task_states.get(self._host_task)
|
| 465 |
+
if host_task_state is None or host_task_state.cancel_scope is not self:
|
| 466 |
+
raise RuntimeError(
|
| 467 |
+
"Attempted to exit a cancel scope that isn't the current tasks's "
|
| 468 |
+
"current cancel scope"
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
try:
|
| 472 |
+
self._active = False
|
| 473 |
+
if self._timeout_handle:
|
| 474 |
+
self._timeout_handle.cancel()
|
| 475 |
+
self._timeout_handle = None
|
| 476 |
+
|
| 477 |
+
self._tasks.remove(self._host_task)
|
| 478 |
+
if self._parent_scope is not None:
|
| 479 |
+
self._parent_scope._child_scopes.remove(self)
|
| 480 |
+
self._parent_scope._tasks.add(self._host_task)
|
| 481 |
+
|
| 482 |
+
host_task_state.cancel_scope = self._parent_scope
|
| 483 |
+
|
| 484 |
+
# Restart the cancellation effort in the closest visible, cancelled parent
|
| 485 |
+
# scope if necessary
|
| 486 |
+
self._restart_cancellation_in_parent()
|
| 487 |
+
|
| 488 |
+
# We only swallow the exception iff it was an AnyIO CancelledError, either
|
| 489 |
+
# directly as exc_val or inside an exception group and there are no cancelled
|
| 490 |
+
# parent cancel scopes visible to us here
|
| 491 |
+
if self._cancel_called and not self._parent_cancellation_is_visible_to_us:
|
| 492 |
+
# For each level-cancel() call made on the host task, call uncancel()
|
| 493 |
+
while self._pending_uncancellations:
|
| 494 |
+
self._host_task.uncancel()
|
| 495 |
+
self._pending_uncancellations -= 1
|
| 496 |
+
|
| 497 |
+
# Update cancelled_caught and check for exceptions we must not swallow
|
| 498 |
+
cannot_swallow_exc_val = False
|
| 499 |
+
if exc_val is not None:
|
| 500 |
+
for exc in iterate_exceptions(exc_val):
|
| 501 |
+
if isinstance(exc, CancelledError) and is_anyio_cancellation(
|
| 502 |
+
exc
|
| 503 |
+
):
|
| 504 |
+
self._cancelled_caught = True
|
| 505 |
+
else:
|
| 506 |
+
cannot_swallow_exc_val = True
|
| 507 |
+
|
| 508 |
+
return self._cancelled_caught and not cannot_swallow_exc_val
|
| 509 |
+
else:
|
| 510 |
+
if self._pending_uncancellations:
|
| 511 |
+
assert self._parent_scope is not None
|
| 512 |
+
assert self._parent_scope._pending_uncancellations is not None
|
| 513 |
+
self._parent_scope._pending_uncancellations += (
|
| 514 |
+
self._pending_uncancellations
|
| 515 |
+
)
|
| 516 |
+
self._pending_uncancellations = 0
|
| 517 |
+
|
| 518 |
+
return False
|
| 519 |
+
finally:
|
| 520 |
+
self._host_task = None
|
| 521 |
+
del exc_val
|
| 522 |
+
|
| 523 |
+
@property
|
| 524 |
+
def _effectively_cancelled(self) -> bool:
|
| 525 |
+
cancel_scope: CancelScope | None = self
|
| 526 |
+
while cancel_scope is not None:
|
| 527 |
+
if cancel_scope._cancel_called:
|
| 528 |
+
return True
|
| 529 |
+
|
| 530 |
+
if cancel_scope.shield:
|
| 531 |
+
return False
|
| 532 |
+
|
| 533 |
+
cancel_scope = cancel_scope._parent_scope
|
| 534 |
+
|
| 535 |
+
return False
|
| 536 |
+
|
| 537 |
+
@property
|
| 538 |
+
def _parent_cancellation_is_visible_to_us(self) -> bool:
|
| 539 |
+
return (
|
| 540 |
+
self._parent_scope is not None
|
| 541 |
+
and not self.shield
|
| 542 |
+
and self._parent_scope._effectively_cancelled
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
def _timeout(self) -> None:
|
| 546 |
+
if self._deadline != math.inf:
|
| 547 |
+
loop = get_running_loop()
|
| 548 |
+
if loop.time() >= self._deadline:
|
| 549 |
+
self.cancel()
|
| 550 |
+
else:
|
| 551 |
+
self._timeout_handle = loop.call_at(self._deadline, self._timeout)
|
| 552 |
+
|
| 553 |
+
def _deliver_cancellation(self, origin: CancelScope) -> bool:
|
| 554 |
+
"""
|
| 555 |
+
Deliver cancellation to directly contained tasks and nested cancel scopes.
|
| 556 |
+
|
| 557 |
+
Schedule another run at the end if we still have tasks eligible for
|
| 558 |
+
cancellation.
|
| 559 |
+
|
| 560 |
+
:param origin: the cancel scope that originated the cancellation
|
| 561 |
+
:return: ``True`` if the delivery needs to be retried on the next cycle
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
should_retry = False
|
| 565 |
+
current = current_task()
|
| 566 |
+
for task in self._tasks:
|
| 567 |
+
should_retry = True
|
| 568 |
+
if task._must_cancel: # type: ignore[attr-defined]
|
| 569 |
+
continue
|
| 570 |
+
|
| 571 |
+
# The task is eligible for cancellation if it has started
|
| 572 |
+
if task is not current and (task is self._host_task or _task_started(task)):
|
| 573 |
+
waiter = task._fut_waiter # type: ignore[attr-defined]
|
| 574 |
+
if not isinstance(waiter, asyncio.Future) or not waiter.done():
|
| 575 |
+
task.cancel(f"Cancelled by cancel scope {id(origin):x}")
|
| 576 |
+
if (
|
| 577 |
+
task is origin._host_task
|
| 578 |
+
and origin._pending_uncancellations is not None
|
| 579 |
+
):
|
| 580 |
+
origin._pending_uncancellations += 1
|
| 581 |
+
|
| 582 |
+
# Deliver cancellation to child scopes that aren't shielded or running their own
|
| 583 |
+
# cancellation callbacks
|
| 584 |
+
for scope in self._child_scopes:
|
| 585 |
+
if not scope._shield and not scope.cancel_called:
|
| 586 |
+
should_retry = scope._deliver_cancellation(origin) or should_retry
|
| 587 |
+
|
| 588 |
+
# Schedule another callback if there are still tasks left
|
| 589 |
+
if origin is self:
|
| 590 |
+
if should_retry:
|
| 591 |
+
self._cancel_handle = get_running_loop().call_soon(
|
| 592 |
+
self._deliver_cancellation, origin
|
| 593 |
+
)
|
| 594 |
+
else:
|
| 595 |
+
self._cancel_handle = None
|
| 596 |
+
|
| 597 |
+
return should_retry
|
| 598 |
+
|
| 599 |
+
def _restart_cancellation_in_parent(self) -> None:
|
| 600 |
+
"""
|
| 601 |
+
Restart the cancellation effort in the closest directly cancelled parent scope.
|
| 602 |
+
|
| 603 |
+
"""
|
| 604 |
+
scope = self._parent_scope
|
| 605 |
+
while scope is not None:
|
| 606 |
+
if scope._cancel_called:
|
| 607 |
+
if scope._cancel_handle is None:
|
| 608 |
+
scope._deliver_cancellation(scope)
|
| 609 |
+
|
| 610 |
+
break
|
| 611 |
+
|
| 612 |
+
# No point in looking beyond any shielded scope
|
| 613 |
+
if scope._shield:
|
| 614 |
+
break
|
| 615 |
+
|
| 616 |
+
scope = scope._parent_scope
|
| 617 |
+
|
| 618 |
+
def cancel(self) -> None:
|
| 619 |
+
if not self._cancel_called:
|
| 620 |
+
if self._timeout_handle:
|
| 621 |
+
self._timeout_handle.cancel()
|
| 622 |
+
self._timeout_handle = None
|
| 623 |
+
|
| 624 |
+
self._cancel_called = True
|
| 625 |
+
if self._host_task is not None:
|
| 626 |
+
self._deliver_cancellation(self)
|
| 627 |
+
|
| 628 |
+
@property
|
| 629 |
+
def deadline(self) -> float:
|
| 630 |
+
return self._deadline
|
| 631 |
+
|
| 632 |
+
@deadline.setter
|
| 633 |
+
def deadline(self, value: float) -> None:
|
| 634 |
+
self._deadline = float(value)
|
| 635 |
+
if self._timeout_handle is not None:
|
| 636 |
+
self._timeout_handle.cancel()
|
| 637 |
+
self._timeout_handle = None
|
| 638 |
+
|
| 639 |
+
if self._active and not self._cancel_called:
|
| 640 |
+
self._timeout()
|
| 641 |
+
|
| 642 |
+
@property
|
| 643 |
+
def cancel_called(self) -> bool:
|
| 644 |
+
return self._cancel_called
|
| 645 |
+
|
| 646 |
+
@property
|
| 647 |
+
def cancelled_caught(self) -> bool:
|
| 648 |
+
return self._cancelled_caught
|
| 649 |
+
|
| 650 |
+
@property
|
| 651 |
+
def shield(self) -> bool:
|
| 652 |
+
return self._shield
|
| 653 |
+
|
| 654 |
+
@shield.setter
|
| 655 |
+
def shield(self, value: bool) -> None:
|
| 656 |
+
if self._shield != value:
|
| 657 |
+
self._shield = value
|
| 658 |
+
if not value:
|
| 659 |
+
self._restart_cancellation_in_parent()
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
#
|
| 663 |
+
# Task states
|
| 664 |
+
#
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
class TaskState:
|
| 668 |
+
"""
|
| 669 |
+
Encapsulates auxiliary task information that cannot be added to the Task instance
|
| 670 |
+
itself because there are no guarantees about its implementation.
|
| 671 |
+
"""
|
| 672 |
+
|
| 673 |
+
__slots__ = "parent_id", "cancel_scope", "__weakref__"
|
| 674 |
+
|
| 675 |
+
def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None):
|
| 676 |
+
self.parent_id = parent_id
|
| 677 |
+
self.cancel_scope = cancel_scope
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
class TaskStateStore(MutableMapping["Awaitable[Any] | asyncio.Task", TaskState]):
|
| 681 |
+
def __init__(self) -> None:
|
| 682 |
+
self._task_states = WeakKeyDictionary[asyncio.Task, TaskState]()
|
| 683 |
+
self._preliminary_task_states: dict[Awaitable[Any], TaskState] = {}
|
| 684 |
+
|
| 685 |
+
def __getitem__(self, key: Awaitable[Any] | asyncio.Task, /) -> TaskState:
|
| 686 |
+
assert isinstance(key, asyncio.Task)
|
| 687 |
+
try:
|
| 688 |
+
return self._task_states[key]
|
| 689 |
+
except KeyError:
|
| 690 |
+
if coro := key.get_coro():
|
| 691 |
+
if state := self._preliminary_task_states.get(coro):
|
| 692 |
+
return state
|
| 693 |
+
|
| 694 |
+
raise KeyError(key)
|
| 695 |
+
|
| 696 |
+
def __setitem__(
|
| 697 |
+
self, key: asyncio.Task | Awaitable[Any], value: TaskState, /
|
| 698 |
+
) -> None:
|
| 699 |
+
if isinstance(key, asyncio.Task):
|
| 700 |
+
self._task_states[key] = value
|
| 701 |
+
else:
|
| 702 |
+
self._preliminary_task_states[key] = value
|
| 703 |
+
|
| 704 |
+
def __delitem__(self, key: asyncio.Task | Awaitable[Any], /) -> None:
|
| 705 |
+
if isinstance(key, asyncio.Task):
|
| 706 |
+
del self._task_states[key]
|
| 707 |
+
else:
|
| 708 |
+
del self._preliminary_task_states[key]
|
| 709 |
+
|
| 710 |
+
def __len__(self) -> int:
|
| 711 |
+
return len(self._task_states) + len(self._preliminary_task_states)
|
| 712 |
+
|
| 713 |
+
def __iter__(self) -> Iterator[Awaitable[Any] | asyncio.Task]:
|
| 714 |
+
yield from self._task_states
|
| 715 |
+
yield from self._preliminary_task_states
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
_task_states = TaskStateStore()
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
#
|
| 722 |
+
# Task groups
|
| 723 |
+
#
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
class _AsyncioTaskStatus(abc.TaskStatus):
|
| 727 |
+
def __init__(self, future: asyncio.Future, parent_id: int):
|
| 728 |
+
self._future = future
|
| 729 |
+
self._parent_id = parent_id
|
| 730 |
+
|
| 731 |
+
def started(self, value: T_contra | None = None) -> None:
|
| 732 |
+
try:
|
| 733 |
+
self._future.set_result(value)
|
| 734 |
+
except asyncio.InvalidStateError:
|
| 735 |
+
if not self._future.cancelled():
|
| 736 |
+
raise RuntimeError(
|
| 737 |
+
"called 'started' twice on the same task status"
|
| 738 |
+
) from None
|
| 739 |
+
|
| 740 |
+
task = cast(asyncio.Task, current_task())
|
| 741 |
+
_task_states[task].parent_id = self._parent_id
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
async def _wait(tasks: Iterable[asyncio.Task[object]]) -> None:
|
| 745 |
+
tasks = set(tasks)
|
| 746 |
+
waiter = get_running_loop().create_future()
|
| 747 |
+
|
| 748 |
+
def on_completion(task: asyncio.Task[object]) -> None:
|
| 749 |
+
tasks.discard(task)
|
| 750 |
+
if not tasks and not waiter.done():
|
| 751 |
+
waiter.set_result(None)
|
| 752 |
+
|
| 753 |
+
for task in tasks:
|
| 754 |
+
task.add_done_callback(on_completion)
|
| 755 |
+
del task
|
| 756 |
+
|
| 757 |
+
try:
|
| 758 |
+
await waiter
|
| 759 |
+
finally:
|
| 760 |
+
while tasks:
|
| 761 |
+
tasks.pop().remove_done_callback(on_completion)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class TaskGroup(abc.TaskGroup):
|
| 765 |
+
def __init__(self) -> None:
|
| 766 |
+
self.cancel_scope: CancelScope = CancelScope()
|
| 767 |
+
self._active = False
|
| 768 |
+
self._exceptions: list[BaseException] = []
|
| 769 |
+
self._tasks: set[asyncio.Task] = set()
|
| 770 |
+
|
| 771 |
+
async def __aenter__(self) -> TaskGroup:
|
| 772 |
+
self.cancel_scope.__enter__()
|
| 773 |
+
self._active = True
|
| 774 |
+
return self
|
| 775 |
+
|
| 776 |
+
async def __aexit__(
|
| 777 |
+
self,
|
| 778 |
+
exc_type: type[BaseException] | None,
|
| 779 |
+
exc_val: BaseException | None,
|
| 780 |
+
exc_tb: TracebackType | None,
|
| 781 |
+
) -> bool | None:
|
| 782 |
+
try:
|
| 783 |
+
if exc_val is not None:
|
| 784 |
+
self.cancel_scope.cancel()
|
| 785 |
+
if not isinstance(exc_val, CancelledError):
|
| 786 |
+
self._exceptions.append(exc_val)
|
| 787 |
+
|
| 788 |
+
try:
|
| 789 |
+
if self._tasks:
|
| 790 |
+
with CancelScope() as wait_scope:
|
| 791 |
+
while self._tasks:
|
| 792 |
+
try:
|
| 793 |
+
await _wait(self._tasks)
|
| 794 |
+
except CancelledError as exc:
|
| 795 |
+
# Shield the scope against further cancellation attempts,
|
| 796 |
+
# as they're not productive (#695)
|
| 797 |
+
wait_scope.shield = True
|
| 798 |
+
self.cancel_scope.cancel()
|
| 799 |
+
|
| 800 |
+
# Set exc_val from the cancellation exception if it was
|
| 801 |
+
# previously unset. However, we should not replace a native
|
| 802 |
+
# cancellation exception with one raise by a cancel scope.
|
| 803 |
+
if exc_val is None or (
|
| 804 |
+
isinstance(exc_val, CancelledError)
|
| 805 |
+
and not is_anyio_cancellation(exc)
|
| 806 |
+
):
|
| 807 |
+
exc_val = exc
|
| 808 |
+
else:
|
| 809 |
+
# If there are no child tasks to wait on, run at least one checkpoint
|
| 810 |
+
# anyway
|
| 811 |
+
await AsyncIOBackend.cancel_shielded_checkpoint()
|
| 812 |
+
|
| 813 |
+
self._active = False
|
| 814 |
+
if self._exceptions:
|
| 815 |
+
raise BaseExceptionGroup(
|
| 816 |
+
"unhandled errors in a TaskGroup", self._exceptions
|
| 817 |
+
)
|
| 818 |
+
elif exc_val:
|
| 819 |
+
raise exc_val
|
| 820 |
+
except BaseException as exc:
|
| 821 |
+
if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
|
| 822 |
+
return True
|
| 823 |
+
|
| 824 |
+
raise
|
| 825 |
+
|
| 826 |
+
return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb)
|
| 827 |
+
finally:
|
| 828 |
+
del exc_val, exc_tb, self._exceptions
|
| 829 |
+
|
| 830 |
+
def _spawn(
|
| 831 |
+
self,
|
| 832 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
|
| 833 |
+
args: tuple[Unpack[PosArgsT]],
|
| 834 |
+
name: object,
|
| 835 |
+
task_status_future: asyncio.Future | None = None,
|
| 836 |
+
) -> asyncio.Task:
|
| 837 |
+
def task_done(_task: asyncio.Task) -> None:
|
| 838 |
+
# task_state = _task_states[_task]
|
| 839 |
+
assert task_state.cancel_scope is not None
|
| 840 |
+
assert _task in task_state.cancel_scope._tasks
|
| 841 |
+
task_state.cancel_scope._tasks.remove(_task)
|
| 842 |
+
self._tasks.remove(task)
|
| 843 |
+
del _task_states[_task]
|
| 844 |
+
|
| 845 |
+
try:
|
| 846 |
+
exc = _task.exception()
|
| 847 |
+
except CancelledError as e:
|
| 848 |
+
while isinstance(e.__context__, CancelledError):
|
| 849 |
+
e = e.__context__
|
| 850 |
+
|
| 851 |
+
exc = e
|
| 852 |
+
|
| 853 |
+
if exc is not None:
|
| 854 |
+
# The future can only be in the cancelled state if the host task was
|
| 855 |
+
# cancelled, so return immediately instead of adding one more
|
| 856 |
+
# CancelledError to the exceptions list
|
| 857 |
+
if task_status_future is not None and task_status_future.cancelled():
|
| 858 |
+
return
|
| 859 |
+
|
| 860 |
+
if task_status_future is None or task_status_future.done():
|
| 861 |
+
if not isinstance(exc, CancelledError):
|
| 862 |
+
self._exceptions.append(exc)
|
| 863 |
+
|
| 864 |
+
if not self.cancel_scope._effectively_cancelled:
|
| 865 |
+
self.cancel_scope.cancel()
|
| 866 |
+
else:
|
| 867 |
+
task_status_future.set_exception(exc)
|
| 868 |
+
elif task_status_future is not None and not task_status_future.done():
|
| 869 |
+
task_status_future.set_exception(
|
| 870 |
+
RuntimeError("Child exited without calling task_status.started()")
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
if not self._active:
|
| 874 |
+
raise RuntimeError(
|
| 875 |
+
"This task group is not active; no new tasks can be started."
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
kwargs = {}
|
| 879 |
+
if task_status_future:
|
| 880 |
+
parent_id = id(current_task())
|
| 881 |
+
kwargs["task_status"] = _AsyncioTaskStatus(
|
| 882 |
+
task_status_future, id(self.cancel_scope._host_task)
|
| 883 |
+
)
|
| 884 |
+
else:
|
| 885 |
+
parent_id = id(self.cancel_scope._host_task)
|
| 886 |
+
|
| 887 |
+
coro = func(*args, **kwargs)
|
| 888 |
+
if not iscoroutine(coro):
|
| 889 |
+
prefix = f"{func.__module__}." if hasattr(func, "__module__") else ""
|
| 890 |
+
raise TypeError(
|
| 891 |
+
f"Expected {prefix}{func.__qualname__}() to return a coroutine, but "
|
| 892 |
+
f"the return value ({coro!r}) is not a coroutine object"
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
# Make the spawned task inherit the task group's cancel scope
|
| 896 |
+
_task_states[coro] = task_state = TaskState(
|
| 897 |
+
parent_id=parent_id, cancel_scope=self.cancel_scope
|
| 898 |
+
)
|
| 899 |
+
name = get_callable_name(func) if name is None else str(name)
|
| 900 |
+
try:
|
| 901 |
+
task = create_task(coro, name=name)
|
| 902 |
+
finally:
|
| 903 |
+
del _task_states[coro]
|
| 904 |
+
|
| 905 |
+
_task_states[task] = task_state
|
| 906 |
+
self.cancel_scope._tasks.add(task)
|
| 907 |
+
self._tasks.add(task)
|
| 908 |
+
|
| 909 |
+
if task.done():
|
| 910 |
+
# This can happen with eager task factories
|
| 911 |
+
task_done(task)
|
| 912 |
+
else:
|
| 913 |
+
task.add_done_callback(task_done)
|
| 914 |
+
|
| 915 |
+
return task
|
| 916 |
+
|
| 917 |
+
def start_soon(
|
| 918 |
+
self,
|
| 919 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
|
| 920 |
+
*args: Unpack[PosArgsT],
|
| 921 |
+
name: object = None,
|
| 922 |
+
) -> None:
|
| 923 |
+
self._spawn(func, args, name)
|
| 924 |
+
|
| 925 |
+
async def start(
|
| 926 |
+
self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None
|
| 927 |
+
) -> Any:
|
| 928 |
+
future: asyncio.Future = asyncio.Future()
|
| 929 |
+
task = self._spawn(func, args, name, future)
|
| 930 |
+
|
| 931 |
+
# If the task raises an exception after sending a start value without a switch
|
| 932 |
+
# point between, the task group is cancelled and this method never proceeds to
|
| 933 |
+
# process the completed future. That's why we have to have a shielded cancel
|
| 934 |
+
# scope here.
|
| 935 |
+
try:
|
| 936 |
+
return await future
|
| 937 |
+
except CancelledError:
|
| 938 |
+
# Cancel the task and wait for it to exit before returning
|
| 939 |
+
task.cancel()
|
| 940 |
+
with CancelScope(shield=True), suppress(CancelledError):
|
| 941 |
+
await task
|
| 942 |
+
|
| 943 |
+
raise
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
#
|
| 947 |
+
# Threads
|
| 948 |
+
#
|
| 949 |
+
|
| 950 |
+
_Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]]
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class WorkerThread(Thread):
|
| 954 |
+
MAX_IDLE_TIME = 10 # seconds
|
| 955 |
+
|
| 956 |
+
def __init__(
|
| 957 |
+
self,
|
| 958 |
+
root_task: asyncio.Task,
|
| 959 |
+
workers: set[WorkerThread],
|
| 960 |
+
idle_workers: deque[WorkerThread],
|
| 961 |
+
):
|
| 962 |
+
super().__init__(name="AnyIO worker thread")
|
| 963 |
+
self.root_task = root_task
|
| 964 |
+
self.workers = workers
|
| 965 |
+
self.idle_workers = idle_workers
|
| 966 |
+
self.loop = root_task._loop
|
| 967 |
+
self.queue: Queue[
|
| 968 |
+
tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None
|
| 969 |
+
] = Queue(2)
|
| 970 |
+
self.idle_since = AsyncIOBackend.current_time()
|
| 971 |
+
self.stopping = False
|
| 972 |
+
|
| 973 |
+
def _report_result(
|
| 974 |
+
self, future: asyncio.Future, result: Any, exc: BaseException | None
|
| 975 |
+
) -> None:
|
| 976 |
+
self.idle_since = AsyncIOBackend.current_time()
|
| 977 |
+
if not self.stopping:
|
| 978 |
+
self.idle_workers.append(self)
|
| 979 |
+
|
| 980 |
+
if not future.cancelled():
|
| 981 |
+
if exc is not None:
|
| 982 |
+
if isinstance(exc, StopIteration):
|
| 983 |
+
new_exc = RuntimeError("coroutine raised StopIteration")
|
| 984 |
+
new_exc.__cause__ = exc
|
| 985 |
+
exc = new_exc
|
| 986 |
+
|
| 987 |
+
future.set_exception(exc)
|
| 988 |
+
else:
|
| 989 |
+
future.set_result(result)
|
| 990 |
+
|
| 991 |
+
def run(self) -> None:
|
| 992 |
+
with claim_worker_thread(AsyncIOBackend, self.loop):
|
| 993 |
+
while True:
|
| 994 |
+
item = self.queue.get()
|
| 995 |
+
if item is None:
|
| 996 |
+
# Shutdown command received
|
| 997 |
+
return
|
| 998 |
+
|
| 999 |
+
context, func, args, future, cancel_scope = item
|
| 1000 |
+
if not future.cancelled():
|
| 1001 |
+
result = None
|
| 1002 |
+
exception: BaseException | None = None
|
| 1003 |
+
threadlocals.current_cancel_scope = cancel_scope
|
| 1004 |
+
try:
|
| 1005 |
+
result = context.run(func, *args)
|
| 1006 |
+
except BaseException as exc:
|
| 1007 |
+
exception = exc
|
| 1008 |
+
finally:
|
| 1009 |
+
del threadlocals.current_cancel_scope
|
| 1010 |
+
|
| 1011 |
+
if not self.loop.is_closed():
|
| 1012 |
+
self.loop.call_soon_threadsafe(
|
| 1013 |
+
self._report_result, future, result, exception
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
self.queue.task_done()
|
| 1017 |
+
|
| 1018 |
+
def stop(self, f: asyncio.Task | None = None) -> None:
|
| 1019 |
+
self.stopping = True
|
| 1020 |
+
self.queue.put_nowait(None)
|
| 1021 |
+
self.workers.discard(self)
|
| 1022 |
+
try:
|
| 1023 |
+
self.idle_workers.remove(self)
|
| 1024 |
+
except ValueError:
|
| 1025 |
+
pass
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar(
|
| 1029 |
+
"_threadpool_idle_workers"
|
| 1030 |
+
)
|
| 1031 |
+
_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers")
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
class BlockingPortal(abc.BlockingPortal):
|
| 1035 |
+
def __new__(cls) -> BlockingPortal:
|
| 1036 |
+
return object.__new__(cls)
|
| 1037 |
+
|
| 1038 |
+
def __init__(self) -> None:
|
| 1039 |
+
super().__init__()
|
| 1040 |
+
self._loop = get_running_loop()
|
| 1041 |
+
|
| 1042 |
+
def _spawn_task_from_thread(
|
| 1043 |
+
self,
|
| 1044 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
|
| 1045 |
+
args: tuple[Unpack[PosArgsT]],
|
| 1046 |
+
kwargs: dict[str, Any],
|
| 1047 |
+
name: object,
|
| 1048 |
+
future: Future[T_Retval],
|
| 1049 |
+
) -> None:
|
| 1050 |
+
AsyncIOBackend.run_sync_from_thread(
|
| 1051 |
+
partial(self._task_group.start_soon, name=name),
|
| 1052 |
+
(self._call_func, func, args, kwargs, future),
|
| 1053 |
+
self._loop,
|
| 1054 |
+
)
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
#
|
| 1058 |
+
# Subprocesses
|
| 1059 |
+
#
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
@dataclass(eq=False)
|
| 1063 |
+
class StreamReaderWrapper(abc.ByteReceiveStream):
|
| 1064 |
+
_stream: asyncio.StreamReader
|
| 1065 |
+
|
| 1066 |
+
async def receive(self, max_bytes: int = 65536) -> bytes:
|
| 1067 |
+
data = await self._stream.read(max_bytes)
|
| 1068 |
+
if data:
|
| 1069 |
+
return data
|
| 1070 |
+
else:
|
| 1071 |
+
raise EndOfStream
|
| 1072 |
+
|
| 1073 |
+
async def aclose(self) -> None:
|
| 1074 |
+
self._stream.set_exception(ClosedResourceError())
|
| 1075 |
+
await AsyncIOBackend.checkpoint()
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
@dataclass(eq=False)
|
| 1079 |
+
class StreamWriterWrapper(abc.ByteSendStream):
|
| 1080 |
+
_stream: asyncio.StreamWriter
|
| 1081 |
+
|
| 1082 |
+
async def send(self, item: bytes) -> None:
|
| 1083 |
+
self._stream.write(item)
|
| 1084 |
+
await self._stream.drain()
|
| 1085 |
+
|
| 1086 |
+
async def aclose(self) -> None:
|
| 1087 |
+
self._stream.close()
|
| 1088 |
+
await AsyncIOBackend.checkpoint()
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
@dataclass(eq=False)
|
| 1092 |
+
class Process(abc.Process):
|
| 1093 |
+
_process: asyncio.subprocess.Process
|
| 1094 |
+
_stdin: StreamWriterWrapper | None
|
| 1095 |
+
_stdout: StreamReaderWrapper | None
|
| 1096 |
+
_stderr: StreamReaderWrapper | None
|
| 1097 |
+
|
| 1098 |
+
async def aclose(self) -> None:
|
| 1099 |
+
with CancelScope(shield=True) as scope:
|
| 1100 |
+
if self._stdin:
|
| 1101 |
+
await self._stdin.aclose()
|
| 1102 |
+
if self._stdout:
|
| 1103 |
+
await self._stdout.aclose()
|
| 1104 |
+
if self._stderr:
|
| 1105 |
+
await self._stderr.aclose()
|
| 1106 |
+
|
| 1107 |
+
scope.shield = False
|
| 1108 |
+
try:
|
| 1109 |
+
await self.wait()
|
| 1110 |
+
except BaseException:
|
| 1111 |
+
scope.shield = True
|
| 1112 |
+
self.kill()
|
| 1113 |
+
await self.wait()
|
| 1114 |
+
raise
|
| 1115 |
+
|
| 1116 |
+
async def wait(self) -> int:
|
| 1117 |
+
return await self._process.wait()
|
| 1118 |
+
|
| 1119 |
+
def terminate(self) -> None:
|
| 1120 |
+
self._process.terminate()
|
| 1121 |
+
|
| 1122 |
+
def kill(self) -> None:
|
| 1123 |
+
self._process.kill()
|
| 1124 |
+
|
| 1125 |
+
def send_signal(self, signal: int) -> None:
|
| 1126 |
+
self._process.send_signal(signal)
|
| 1127 |
+
|
| 1128 |
+
@property
|
| 1129 |
+
def pid(self) -> int:
|
| 1130 |
+
return self._process.pid
|
| 1131 |
+
|
| 1132 |
+
@property
|
| 1133 |
+
def returncode(self) -> int | None:
|
| 1134 |
+
return self._process.returncode
|
| 1135 |
+
|
| 1136 |
+
@property
|
| 1137 |
+
def stdin(self) -> abc.ByteSendStream | None:
|
| 1138 |
+
return self._stdin
|
| 1139 |
+
|
| 1140 |
+
@property
|
| 1141 |
+
def stdout(self) -> abc.ByteReceiveStream | None:
|
| 1142 |
+
return self._stdout
|
| 1143 |
+
|
| 1144 |
+
@property
|
| 1145 |
+
def stderr(self) -> abc.ByteReceiveStream | None:
|
| 1146 |
+
return self._stderr
|
| 1147 |
+
|
| 1148 |
+
|
| 1149 |
+
def _forcibly_shutdown_process_pool_on_exit(
|
| 1150 |
+
workers: set[Process], _task: object
|
| 1151 |
+
) -> None:
|
| 1152 |
+
"""
|
| 1153 |
+
Forcibly shuts down worker processes belonging to this event loop."""
|
| 1154 |
+
child_watcher: asyncio.AbstractChildWatcher | None = None
|
| 1155 |
+
if sys.version_info < (3, 12):
|
| 1156 |
+
try:
|
| 1157 |
+
child_watcher = asyncio.get_event_loop_policy().get_child_watcher()
|
| 1158 |
+
except NotImplementedError:
|
| 1159 |
+
pass
|
| 1160 |
+
|
| 1161 |
+
# Close as much as possible (w/o async/await) to avoid warnings
|
| 1162 |
+
for process in workers:
|
| 1163 |
+
if process.returncode is None:
|
| 1164 |
+
continue
|
| 1165 |
+
|
| 1166 |
+
process._stdin._stream._transport.close() # type: ignore[union-attr]
|
| 1167 |
+
process._stdout._stream._transport.close() # type: ignore[union-attr]
|
| 1168 |
+
process._stderr._stream._transport.close() # type: ignore[union-attr]
|
| 1169 |
+
process.kill()
|
| 1170 |
+
if child_watcher:
|
| 1171 |
+
child_watcher.remove_child_handler(process.pid)
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None:
|
| 1175 |
+
"""
|
| 1176 |
+
Shuts down worker processes belonging to this event loop.
|
| 1177 |
+
|
| 1178 |
+
NOTE: this only works when the event loop was started using asyncio.run() or
|
| 1179 |
+
anyio.run().
|
| 1180 |
+
|
| 1181 |
+
"""
|
| 1182 |
+
process: abc.Process
|
| 1183 |
+
try:
|
| 1184 |
+
await sleep(math.inf)
|
| 1185 |
+
except asyncio.CancelledError:
|
| 1186 |
+
for process in workers:
|
| 1187 |
+
if process.returncode is None:
|
| 1188 |
+
process.kill()
|
| 1189 |
+
|
| 1190 |
+
for process in workers:
|
| 1191 |
+
await process.aclose()
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
#
|
| 1195 |
+
# Sockets and networking
|
| 1196 |
+
#
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
class StreamProtocol(asyncio.Protocol):
|
| 1200 |
+
read_queue: deque[bytes]
|
| 1201 |
+
read_event: asyncio.Event
|
| 1202 |
+
write_event: asyncio.Event
|
| 1203 |
+
exception: Exception | None = None
|
| 1204 |
+
is_at_eof: bool = False
|
| 1205 |
+
|
| 1206 |
+
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
| 1207 |
+
self.read_queue = deque()
|
| 1208 |
+
self.read_event = asyncio.Event()
|
| 1209 |
+
self.write_event = asyncio.Event()
|
| 1210 |
+
self.write_event.set()
|
| 1211 |
+
cast(asyncio.Transport, transport).set_write_buffer_limits(0)
|
| 1212 |
+
|
| 1213 |
+
def connection_lost(self, exc: Exception | None) -> None:
|
| 1214 |
+
if exc:
|
| 1215 |
+
self.exception = BrokenResourceError()
|
| 1216 |
+
self.exception.__cause__ = exc
|
| 1217 |
+
|
| 1218 |
+
self.read_event.set()
|
| 1219 |
+
self.write_event.set()
|
| 1220 |
+
|
| 1221 |
+
def data_received(self, data: bytes) -> None:
|
| 1222 |
+
# ProactorEventloop sometimes sends bytearray instead of bytes
|
| 1223 |
+
self.read_queue.append(bytes(data))
|
| 1224 |
+
self.read_event.set()
|
| 1225 |
+
|
| 1226 |
+
def eof_received(self) -> bool | None:
|
| 1227 |
+
self.is_at_eof = True
|
| 1228 |
+
self.read_event.set()
|
| 1229 |
+
return True
|
| 1230 |
+
|
| 1231 |
+
def pause_writing(self) -> None:
|
| 1232 |
+
self.write_event = asyncio.Event()
|
| 1233 |
+
|
| 1234 |
+
def resume_writing(self) -> None:
|
| 1235 |
+
self.write_event.set()
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
class DatagramProtocol(asyncio.DatagramProtocol):
|
| 1239 |
+
read_queue: deque[tuple[bytes, IPSockAddrType]]
|
| 1240 |
+
read_event: asyncio.Event
|
| 1241 |
+
write_event: asyncio.Event
|
| 1242 |
+
exception: Exception | None = None
|
| 1243 |
+
|
| 1244 |
+
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
| 1245 |
+
self.read_queue = deque(maxlen=100) # arbitrary value
|
| 1246 |
+
self.read_event = asyncio.Event()
|
| 1247 |
+
self.write_event = asyncio.Event()
|
| 1248 |
+
self.write_event.set()
|
| 1249 |
+
|
| 1250 |
+
def connection_lost(self, exc: Exception | None) -> None:
|
| 1251 |
+
self.read_event.set()
|
| 1252 |
+
self.write_event.set()
|
| 1253 |
+
|
| 1254 |
+
def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None:
|
| 1255 |
+
addr = convert_ipv6_sockaddr(addr)
|
| 1256 |
+
self.read_queue.append((data, addr))
|
| 1257 |
+
self.read_event.set()
|
| 1258 |
+
|
| 1259 |
+
def error_received(self, exc: Exception) -> None:
|
| 1260 |
+
self.exception = exc
|
| 1261 |
+
|
| 1262 |
+
def pause_writing(self) -> None:
|
| 1263 |
+
self.write_event.clear()
|
| 1264 |
+
|
| 1265 |
+
def resume_writing(self) -> None:
|
| 1266 |
+
self.write_event.set()
|
| 1267 |
+
|
| 1268 |
+
|
| 1269 |
+
class SocketStream(abc.SocketStream):
|
| 1270 |
+
def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol):
|
| 1271 |
+
self._transport = transport
|
| 1272 |
+
self._protocol = protocol
|
| 1273 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 1274 |
+
self._send_guard = ResourceGuard("writing to")
|
| 1275 |
+
self._closed = False
|
| 1276 |
+
|
| 1277 |
+
@property
|
| 1278 |
+
def _raw_socket(self) -> socket.socket:
|
| 1279 |
+
return self._transport.get_extra_info("socket")
|
| 1280 |
+
|
| 1281 |
+
async def receive(self, max_bytes: int = 65536) -> bytes:
|
| 1282 |
+
with self._receive_guard:
|
| 1283 |
+
if (
|
| 1284 |
+
not self._protocol.read_event.is_set()
|
| 1285 |
+
and not self._transport.is_closing()
|
| 1286 |
+
and not self._protocol.is_at_eof
|
| 1287 |
+
):
|
| 1288 |
+
self._transport.resume_reading()
|
| 1289 |
+
await self._protocol.read_event.wait()
|
| 1290 |
+
self._transport.pause_reading()
|
| 1291 |
+
else:
|
| 1292 |
+
await AsyncIOBackend.checkpoint()
|
| 1293 |
+
|
| 1294 |
+
try:
|
| 1295 |
+
chunk = self._protocol.read_queue.popleft()
|
| 1296 |
+
except IndexError:
|
| 1297 |
+
if self._closed:
|
| 1298 |
+
raise ClosedResourceError from None
|
| 1299 |
+
elif self._protocol.exception:
|
| 1300 |
+
raise self._protocol.exception from None
|
| 1301 |
+
else:
|
| 1302 |
+
raise EndOfStream from None
|
| 1303 |
+
|
| 1304 |
+
if len(chunk) > max_bytes:
|
| 1305 |
+
# Split the oversized chunk
|
| 1306 |
+
chunk, leftover = chunk[:max_bytes], chunk[max_bytes:]
|
| 1307 |
+
self._protocol.read_queue.appendleft(leftover)
|
| 1308 |
+
|
| 1309 |
+
# If the read queue is empty, clear the flag so that the next call will
|
| 1310 |
+
# block until data is available
|
| 1311 |
+
if not self._protocol.read_queue:
|
| 1312 |
+
self._protocol.read_event.clear()
|
| 1313 |
+
|
| 1314 |
+
return chunk
|
| 1315 |
+
|
| 1316 |
+
async def send(self, item: bytes) -> None:
|
| 1317 |
+
with self._send_guard:
|
| 1318 |
+
await AsyncIOBackend.checkpoint()
|
| 1319 |
+
|
| 1320 |
+
if self._closed:
|
| 1321 |
+
raise ClosedResourceError
|
| 1322 |
+
elif self._protocol.exception is not None:
|
| 1323 |
+
raise self._protocol.exception
|
| 1324 |
+
|
| 1325 |
+
try:
|
| 1326 |
+
self._transport.write(item)
|
| 1327 |
+
except RuntimeError as exc:
|
| 1328 |
+
if self._transport.is_closing():
|
| 1329 |
+
raise BrokenResourceError from exc
|
| 1330 |
+
else:
|
| 1331 |
+
raise
|
| 1332 |
+
|
| 1333 |
+
await self._protocol.write_event.wait()
|
| 1334 |
+
|
| 1335 |
+
async def send_eof(self) -> None:
|
| 1336 |
+
try:
|
| 1337 |
+
self._transport.write_eof()
|
| 1338 |
+
except OSError:
|
| 1339 |
+
pass
|
| 1340 |
+
|
| 1341 |
+
async def aclose(self) -> None:
|
| 1342 |
+
if not self._transport.is_closing():
|
| 1343 |
+
self._closed = True
|
| 1344 |
+
try:
|
| 1345 |
+
self._transport.write_eof()
|
| 1346 |
+
except OSError:
|
| 1347 |
+
pass
|
| 1348 |
+
|
| 1349 |
+
self._transport.close()
|
| 1350 |
+
await sleep(0)
|
| 1351 |
+
self._transport.abort()
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
class _RawSocketMixin:
|
| 1355 |
+
_receive_future: asyncio.Future | None = None
|
| 1356 |
+
_send_future: asyncio.Future | None = None
|
| 1357 |
+
_closing = False
|
| 1358 |
+
|
| 1359 |
+
def __init__(self, raw_socket: socket.socket):
|
| 1360 |
+
self.__raw_socket = raw_socket
|
| 1361 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 1362 |
+
self._send_guard = ResourceGuard("writing to")
|
| 1363 |
+
|
| 1364 |
+
@property
|
| 1365 |
+
def _raw_socket(self) -> socket.socket:
|
| 1366 |
+
return self.__raw_socket
|
| 1367 |
+
|
| 1368 |
+
def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future:
|
| 1369 |
+
def callback(f: object) -> None:
|
| 1370 |
+
del self._receive_future
|
| 1371 |
+
loop.remove_reader(self.__raw_socket)
|
| 1372 |
+
|
| 1373 |
+
f = self._receive_future = asyncio.Future()
|
| 1374 |
+
loop.add_reader(self.__raw_socket, f.set_result, None)
|
| 1375 |
+
f.add_done_callback(callback)
|
| 1376 |
+
return f
|
| 1377 |
+
|
| 1378 |
+
def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future:
|
| 1379 |
+
def callback(f: object) -> None:
|
| 1380 |
+
del self._send_future
|
| 1381 |
+
loop.remove_writer(self.__raw_socket)
|
| 1382 |
+
|
| 1383 |
+
f = self._send_future = asyncio.Future()
|
| 1384 |
+
loop.add_writer(self.__raw_socket, f.set_result, None)
|
| 1385 |
+
f.add_done_callback(callback)
|
| 1386 |
+
return f
|
| 1387 |
+
|
| 1388 |
+
async def aclose(self) -> None:
|
| 1389 |
+
if not self._closing:
|
| 1390 |
+
self._closing = True
|
| 1391 |
+
if self.__raw_socket.fileno() != -1:
|
| 1392 |
+
self.__raw_socket.close()
|
| 1393 |
+
|
| 1394 |
+
if self._receive_future:
|
| 1395 |
+
self._receive_future.set_result(None)
|
| 1396 |
+
if self._send_future:
|
| 1397 |
+
self._send_future.set_result(None)
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream):
|
| 1401 |
+
async def send_eof(self) -> None:
|
| 1402 |
+
with self._send_guard:
|
| 1403 |
+
self._raw_socket.shutdown(socket.SHUT_WR)
|
| 1404 |
+
|
| 1405 |
+
async def receive(self, max_bytes: int = 65536) -> bytes:
|
| 1406 |
+
loop = get_running_loop()
|
| 1407 |
+
await AsyncIOBackend.checkpoint()
|
| 1408 |
+
with self._receive_guard:
|
| 1409 |
+
while True:
|
| 1410 |
+
try:
|
| 1411 |
+
data = self._raw_socket.recv(max_bytes)
|
| 1412 |
+
except BlockingIOError:
|
| 1413 |
+
await self._wait_until_readable(loop)
|
| 1414 |
+
except OSError as exc:
|
| 1415 |
+
if self._closing:
|
| 1416 |
+
raise ClosedResourceError from None
|
| 1417 |
+
else:
|
| 1418 |
+
raise BrokenResourceError from exc
|
| 1419 |
+
else:
|
| 1420 |
+
if not data:
|
| 1421 |
+
raise EndOfStream
|
| 1422 |
+
|
| 1423 |
+
return data
|
| 1424 |
+
|
| 1425 |
+
async def send(self, item: bytes) -> None:
|
| 1426 |
+
loop = get_running_loop()
|
| 1427 |
+
await AsyncIOBackend.checkpoint()
|
| 1428 |
+
with self._send_guard:
|
| 1429 |
+
view = memoryview(item)
|
| 1430 |
+
while view:
|
| 1431 |
+
try:
|
| 1432 |
+
bytes_sent = self._raw_socket.send(view)
|
| 1433 |
+
except BlockingIOError:
|
| 1434 |
+
await self._wait_until_writable(loop)
|
| 1435 |
+
except OSError as exc:
|
| 1436 |
+
if self._closing:
|
| 1437 |
+
raise ClosedResourceError from None
|
| 1438 |
+
else:
|
| 1439 |
+
raise BrokenResourceError from exc
|
| 1440 |
+
else:
|
| 1441 |
+
view = view[bytes_sent:]
|
| 1442 |
+
|
| 1443 |
+
async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
|
| 1444 |
+
if not isinstance(msglen, int) or msglen < 0:
|
| 1445 |
+
raise ValueError("msglen must be a non-negative integer")
|
| 1446 |
+
if not isinstance(maxfds, int) or maxfds < 1:
|
| 1447 |
+
raise ValueError("maxfds must be a positive integer")
|
| 1448 |
+
|
| 1449 |
+
loop = get_running_loop()
|
| 1450 |
+
fds = array.array("i")
|
| 1451 |
+
await AsyncIOBackend.checkpoint()
|
| 1452 |
+
with self._receive_guard:
|
| 1453 |
+
while True:
|
| 1454 |
+
try:
|
| 1455 |
+
message, ancdata, flags, addr = self._raw_socket.recvmsg(
|
| 1456 |
+
msglen, socket.CMSG_LEN(maxfds * fds.itemsize)
|
| 1457 |
+
)
|
| 1458 |
+
except BlockingIOError:
|
| 1459 |
+
await self._wait_until_readable(loop)
|
| 1460 |
+
except OSError as exc:
|
| 1461 |
+
if self._closing:
|
| 1462 |
+
raise ClosedResourceError from None
|
| 1463 |
+
else:
|
| 1464 |
+
raise BrokenResourceError from exc
|
| 1465 |
+
else:
|
| 1466 |
+
if not message and not ancdata:
|
| 1467 |
+
raise EndOfStream
|
| 1468 |
+
|
| 1469 |
+
break
|
| 1470 |
+
|
| 1471 |
+
for cmsg_level, cmsg_type, cmsg_data in ancdata:
|
| 1472 |
+
if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS:
|
| 1473 |
+
raise RuntimeError(
|
| 1474 |
+
f"Received unexpected ancillary data; message = {message!r}, "
|
| 1475 |
+
f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}"
|
| 1476 |
+
)
|
| 1477 |
+
|
| 1478 |
+
fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
|
| 1479 |
+
|
| 1480 |
+
return message, list(fds)
|
| 1481 |
+
|
| 1482 |
+
async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
|
| 1483 |
+
if not message:
|
| 1484 |
+
raise ValueError("message must not be empty")
|
| 1485 |
+
if not fds:
|
| 1486 |
+
raise ValueError("fds must not be empty")
|
| 1487 |
+
|
| 1488 |
+
loop = get_running_loop()
|
| 1489 |
+
filenos: list[int] = []
|
| 1490 |
+
for fd in fds:
|
| 1491 |
+
if isinstance(fd, int):
|
| 1492 |
+
filenos.append(fd)
|
| 1493 |
+
elif isinstance(fd, IOBase):
|
| 1494 |
+
filenos.append(fd.fileno())
|
| 1495 |
+
|
| 1496 |
+
fdarray = array.array("i", filenos)
|
| 1497 |
+
await AsyncIOBackend.checkpoint()
|
| 1498 |
+
with self._send_guard:
|
| 1499 |
+
while True:
|
| 1500 |
+
try:
|
| 1501 |
+
# The ignore can be removed after mypy picks up
|
| 1502 |
+
# https://github.com/python/typeshed/pull/5545
|
| 1503 |
+
self._raw_socket.sendmsg(
|
| 1504 |
+
[message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)]
|
| 1505 |
+
)
|
| 1506 |
+
break
|
| 1507 |
+
except BlockingIOError:
|
| 1508 |
+
await self._wait_until_writable(loop)
|
| 1509 |
+
except OSError as exc:
|
| 1510 |
+
if self._closing:
|
| 1511 |
+
raise ClosedResourceError from None
|
| 1512 |
+
else:
|
| 1513 |
+
raise BrokenResourceError from exc
|
| 1514 |
+
|
| 1515 |
+
|
| 1516 |
+
class TCPSocketListener(abc.SocketListener):
|
| 1517 |
+
_accept_scope: CancelScope | None = None
|
| 1518 |
+
_closed = False
|
| 1519 |
+
|
| 1520 |
+
def __init__(self, raw_socket: socket.socket):
|
| 1521 |
+
self.__raw_socket = raw_socket
|
| 1522 |
+
self._loop = cast(asyncio.BaseEventLoop, get_running_loop())
|
| 1523 |
+
self._accept_guard = ResourceGuard("accepting connections from")
|
| 1524 |
+
|
| 1525 |
+
@property
|
| 1526 |
+
def _raw_socket(self) -> socket.socket:
|
| 1527 |
+
return self.__raw_socket
|
| 1528 |
+
|
| 1529 |
+
async def accept(self) -> abc.SocketStream:
|
| 1530 |
+
if self._closed:
|
| 1531 |
+
raise ClosedResourceError
|
| 1532 |
+
|
| 1533 |
+
with self._accept_guard:
|
| 1534 |
+
await AsyncIOBackend.checkpoint()
|
| 1535 |
+
with CancelScope() as self._accept_scope:
|
| 1536 |
+
try:
|
| 1537 |
+
client_sock, _addr = await self._loop.sock_accept(self._raw_socket)
|
| 1538 |
+
except asyncio.CancelledError:
|
| 1539 |
+
# Workaround for https://bugs.python.org/issue41317
|
| 1540 |
+
try:
|
| 1541 |
+
self._loop.remove_reader(self._raw_socket)
|
| 1542 |
+
except (ValueError, NotImplementedError):
|
| 1543 |
+
pass
|
| 1544 |
+
|
| 1545 |
+
if self._closed:
|
| 1546 |
+
raise ClosedResourceError from None
|
| 1547 |
+
|
| 1548 |
+
raise
|
| 1549 |
+
finally:
|
| 1550 |
+
self._accept_scope = None
|
| 1551 |
+
|
| 1552 |
+
client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 1553 |
+
transport, protocol = await self._loop.connect_accepted_socket(
|
| 1554 |
+
StreamProtocol, client_sock
|
| 1555 |
+
)
|
| 1556 |
+
return SocketStream(transport, protocol)
|
| 1557 |
+
|
| 1558 |
+
async def aclose(self) -> None:
|
| 1559 |
+
if self._closed:
|
| 1560 |
+
return
|
| 1561 |
+
|
| 1562 |
+
self._closed = True
|
| 1563 |
+
if self._accept_scope:
|
| 1564 |
+
# Workaround for https://bugs.python.org/issue41317
|
| 1565 |
+
try:
|
| 1566 |
+
self._loop.remove_reader(self._raw_socket)
|
| 1567 |
+
except (ValueError, NotImplementedError):
|
| 1568 |
+
pass
|
| 1569 |
+
|
| 1570 |
+
self._accept_scope.cancel()
|
| 1571 |
+
await sleep(0)
|
| 1572 |
+
|
| 1573 |
+
self._raw_socket.close()
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
class UNIXSocketListener(abc.SocketListener):
|
| 1577 |
+
def __init__(self, raw_socket: socket.socket):
|
| 1578 |
+
self.__raw_socket = raw_socket
|
| 1579 |
+
self._loop = get_running_loop()
|
| 1580 |
+
self._accept_guard = ResourceGuard("accepting connections from")
|
| 1581 |
+
self._closed = False
|
| 1582 |
+
|
| 1583 |
+
async def accept(self) -> abc.SocketStream:
|
| 1584 |
+
await AsyncIOBackend.checkpoint()
|
| 1585 |
+
with self._accept_guard:
|
| 1586 |
+
while True:
|
| 1587 |
+
try:
|
| 1588 |
+
client_sock, _ = self.__raw_socket.accept()
|
| 1589 |
+
client_sock.setblocking(False)
|
| 1590 |
+
return UNIXSocketStream(client_sock)
|
| 1591 |
+
except BlockingIOError:
|
| 1592 |
+
f: asyncio.Future = asyncio.Future()
|
| 1593 |
+
self._loop.add_reader(self.__raw_socket, f.set_result, None)
|
| 1594 |
+
f.add_done_callback(
|
| 1595 |
+
lambda _: self._loop.remove_reader(self.__raw_socket)
|
| 1596 |
+
)
|
| 1597 |
+
await f
|
| 1598 |
+
except OSError as exc:
|
| 1599 |
+
if self._closed:
|
| 1600 |
+
raise ClosedResourceError from None
|
| 1601 |
+
else:
|
| 1602 |
+
raise BrokenResourceError from exc
|
| 1603 |
+
|
| 1604 |
+
async def aclose(self) -> None:
|
| 1605 |
+
self._closed = True
|
| 1606 |
+
self.__raw_socket.close()
|
| 1607 |
+
|
| 1608 |
+
@property
|
| 1609 |
+
def _raw_socket(self) -> socket.socket:
|
| 1610 |
+
return self.__raw_socket
|
| 1611 |
+
|
| 1612 |
+
|
| 1613 |
+
class UDPSocket(abc.UDPSocket):
|
| 1614 |
+
def __init__(
|
| 1615 |
+
self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol
|
| 1616 |
+
):
|
| 1617 |
+
self._transport = transport
|
| 1618 |
+
self._protocol = protocol
|
| 1619 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 1620 |
+
self._send_guard = ResourceGuard("writing to")
|
| 1621 |
+
self._closed = False
|
| 1622 |
+
|
| 1623 |
+
@property
|
| 1624 |
+
def _raw_socket(self) -> socket.socket:
|
| 1625 |
+
return self._transport.get_extra_info("socket")
|
| 1626 |
+
|
| 1627 |
+
async def aclose(self) -> None:
|
| 1628 |
+
if not self._transport.is_closing():
|
| 1629 |
+
self._closed = True
|
| 1630 |
+
self._transport.close()
|
| 1631 |
+
|
| 1632 |
+
async def receive(self) -> tuple[bytes, IPSockAddrType]:
|
| 1633 |
+
with self._receive_guard:
|
| 1634 |
+
await AsyncIOBackend.checkpoint()
|
| 1635 |
+
|
| 1636 |
+
# If the buffer is empty, ask for more data
|
| 1637 |
+
if not self._protocol.read_queue and not self._transport.is_closing():
|
| 1638 |
+
self._protocol.read_event.clear()
|
| 1639 |
+
await self._protocol.read_event.wait()
|
| 1640 |
+
|
| 1641 |
+
try:
|
| 1642 |
+
return self._protocol.read_queue.popleft()
|
| 1643 |
+
except IndexError:
|
| 1644 |
+
if self._closed:
|
| 1645 |
+
raise ClosedResourceError from None
|
| 1646 |
+
else:
|
| 1647 |
+
raise BrokenResourceError from None
|
| 1648 |
+
|
| 1649 |
+
async def send(self, item: UDPPacketType) -> None:
|
| 1650 |
+
with self._send_guard:
|
| 1651 |
+
await AsyncIOBackend.checkpoint()
|
| 1652 |
+
await self._protocol.write_event.wait()
|
| 1653 |
+
if self._closed:
|
| 1654 |
+
raise ClosedResourceError
|
| 1655 |
+
elif self._transport.is_closing():
|
| 1656 |
+
raise BrokenResourceError
|
| 1657 |
+
else:
|
| 1658 |
+
self._transport.sendto(*item)
|
| 1659 |
+
|
| 1660 |
+
|
| 1661 |
+
class ConnectedUDPSocket(abc.ConnectedUDPSocket):
|
| 1662 |
+
def __init__(
|
| 1663 |
+
self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol
|
| 1664 |
+
):
|
| 1665 |
+
self._transport = transport
|
| 1666 |
+
self._protocol = protocol
|
| 1667 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 1668 |
+
self._send_guard = ResourceGuard("writing to")
|
| 1669 |
+
self._closed = False
|
| 1670 |
+
|
| 1671 |
+
@property
|
| 1672 |
+
def _raw_socket(self) -> socket.socket:
|
| 1673 |
+
return self._transport.get_extra_info("socket")
|
| 1674 |
+
|
| 1675 |
+
async def aclose(self) -> None:
|
| 1676 |
+
if not self._transport.is_closing():
|
| 1677 |
+
self._closed = True
|
| 1678 |
+
self._transport.close()
|
| 1679 |
+
|
| 1680 |
+
async def receive(self) -> bytes:
|
| 1681 |
+
with self._receive_guard:
|
| 1682 |
+
await AsyncIOBackend.checkpoint()
|
| 1683 |
+
|
| 1684 |
+
# If the buffer is empty, ask for more data
|
| 1685 |
+
if not self._protocol.read_queue and not self._transport.is_closing():
|
| 1686 |
+
self._protocol.read_event.clear()
|
| 1687 |
+
await self._protocol.read_event.wait()
|
| 1688 |
+
|
| 1689 |
+
try:
|
| 1690 |
+
packet = self._protocol.read_queue.popleft()
|
| 1691 |
+
except IndexError:
|
| 1692 |
+
if self._closed:
|
| 1693 |
+
raise ClosedResourceError from None
|
| 1694 |
+
else:
|
| 1695 |
+
raise BrokenResourceError from None
|
| 1696 |
+
|
| 1697 |
+
return packet[0]
|
| 1698 |
+
|
| 1699 |
+
async def send(self, item: bytes) -> None:
|
| 1700 |
+
with self._send_guard:
|
| 1701 |
+
await AsyncIOBackend.checkpoint()
|
| 1702 |
+
await self._protocol.write_event.wait()
|
| 1703 |
+
if self._closed:
|
| 1704 |
+
raise ClosedResourceError
|
| 1705 |
+
elif self._transport.is_closing():
|
| 1706 |
+
raise BrokenResourceError
|
| 1707 |
+
else:
|
| 1708 |
+
self._transport.sendto(item)
|
| 1709 |
+
|
| 1710 |
+
|
| 1711 |
+
class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket):
|
| 1712 |
+
async def receive(self) -> UNIXDatagramPacketType:
|
| 1713 |
+
loop = get_running_loop()
|
| 1714 |
+
await AsyncIOBackend.checkpoint()
|
| 1715 |
+
with self._receive_guard:
|
| 1716 |
+
while True:
|
| 1717 |
+
try:
|
| 1718 |
+
data = self._raw_socket.recvfrom(65536)
|
| 1719 |
+
except BlockingIOError:
|
| 1720 |
+
await self._wait_until_readable(loop)
|
| 1721 |
+
except OSError as exc:
|
| 1722 |
+
if self._closing:
|
| 1723 |
+
raise ClosedResourceError from None
|
| 1724 |
+
else:
|
| 1725 |
+
raise BrokenResourceError from exc
|
| 1726 |
+
else:
|
| 1727 |
+
return data
|
| 1728 |
+
|
| 1729 |
+
async def send(self, item: UNIXDatagramPacketType) -> None:
|
| 1730 |
+
loop = get_running_loop()
|
| 1731 |
+
await AsyncIOBackend.checkpoint()
|
| 1732 |
+
with self._send_guard:
|
| 1733 |
+
while True:
|
| 1734 |
+
try:
|
| 1735 |
+
self._raw_socket.sendto(*item)
|
| 1736 |
+
except BlockingIOError:
|
| 1737 |
+
await self._wait_until_writable(loop)
|
| 1738 |
+
except OSError as exc:
|
| 1739 |
+
if self._closing:
|
| 1740 |
+
raise ClosedResourceError from None
|
| 1741 |
+
else:
|
| 1742 |
+
raise BrokenResourceError from exc
|
| 1743 |
+
else:
|
| 1744 |
+
return
|
| 1745 |
+
|
| 1746 |
+
|
| 1747 |
+
class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket):
|
| 1748 |
+
async def receive(self) -> bytes:
|
| 1749 |
+
loop = get_running_loop()
|
| 1750 |
+
await AsyncIOBackend.checkpoint()
|
| 1751 |
+
with self._receive_guard:
|
| 1752 |
+
while True:
|
| 1753 |
+
try:
|
| 1754 |
+
data = self._raw_socket.recv(65536)
|
| 1755 |
+
except BlockingIOError:
|
| 1756 |
+
await self._wait_until_readable(loop)
|
| 1757 |
+
except OSError as exc:
|
| 1758 |
+
if self._closing:
|
| 1759 |
+
raise ClosedResourceError from None
|
| 1760 |
+
else:
|
| 1761 |
+
raise BrokenResourceError from exc
|
| 1762 |
+
else:
|
| 1763 |
+
return data
|
| 1764 |
+
|
| 1765 |
+
async def send(self, item: bytes) -> None:
|
| 1766 |
+
loop = get_running_loop()
|
| 1767 |
+
await AsyncIOBackend.checkpoint()
|
| 1768 |
+
with self._send_guard:
|
| 1769 |
+
while True:
|
| 1770 |
+
try:
|
| 1771 |
+
self._raw_socket.send(item)
|
| 1772 |
+
except BlockingIOError:
|
| 1773 |
+
await self._wait_until_writable(loop)
|
| 1774 |
+
except OSError as exc:
|
| 1775 |
+
if self._closing:
|
| 1776 |
+
raise ClosedResourceError from None
|
| 1777 |
+
else:
|
| 1778 |
+
raise BrokenResourceError from exc
|
| 1779 |
+
else:
|
| 1780 |
+
return
|
| 1781 |
+
|
| 1782 |
+
|
| 1783 |
+
_read_events: RunVar[dict[int, asyncio.Event]] = RunVar("read_events")
|
| 1784 |
+
_write_events: RunVar[dict[int, asyncio.Event]] = RunVar("write_events")
|
| 1785 |
+
|
| 1786 |
+
|
| 1787 |
+
#
|
| 1788 |
+
# Synchronization
|
| 1789 |
+
#
|
| 1790 |
+
|
| 1791 |
+
|
| 1792 |
+
class Event(BaseEvent):
|
| 1793 |
+
def __new__(cls) -> Event:
|
| 1794 |
+
return object.__new__(cls)
|
| 1795 |
+
|
| 1796 |
+
def __init__(self) -> None:
|
| 1797 |
+
self._event = asyncio.Event()
|
| 1798 |
+
|
| 1799 |
+
def set(self) -> None:
|
| 1800 |
+
self._event.set()
|
| 1801 |
+
|
| 1802 |
+
def is_set(self) -> bool:
|
| 1803 |
+
return self._event.is_set()
|
| 1804 |
+
|
| 1805 |
+
async def wait(self) -> None:
|
| 1806 |
+
if self.is_set():
|
| 1807 |
+
await AsyncIOBackend.checkpoint()
|
| 1808 |
+
else:
|
| 1809 |
+
await self._event.wait()
|
| 1810 |
+
|
| 1811 |
+
def statistics(self) -> EventStatistics:
|
| 1812 |
+
return EventStatistics(len(self._event._waiters))
|
| 1813 |
+
|
| 1814 |
+
|
| 1815 |
+
class Lock(BaseLock):
|
| 1816 |
+
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
|
| 1817 |
+
return object.__new__(cls)
|
| 1818 |
+
|
| 1819 |
+
def __init__(self, *, fast_acquire: bool = False) -> None:
|
| 1820 |
+
self._fast_acquire = fast_acquire
|
| 1821 |
+
self._owner_task: asyncio.Task | None = None
|
| 1822 |
+
self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque()
|
| 1823 |
+
|
| 1824 |
+
async def acquire(self) -> None:
|
| 1825 |
+
task = cast(asyncio.Task, current_task())
|
| 1826 |
+
if self._owner_task is None and not self._waiters:
|
| 1827 |
+
await AsyncIOBackend.checkpoint_if_cancelled()
|
| 1828 |
+
self._owner_task = task
|
| 1829 |
+
|
| 1830 |
+
# Unless on the "fast path", yield control of the event loop so that other
|
| 1831 |
+
# tasks can run too
|
| 1832 |
+
if not self._fast_acquire:
|
| 1833 |
+
try:
|
| 1834 |
+
await AsyncIOBackend.cancel_shielded_checkpoint()
|
| 1835 |
+
except CancelledError:
|
| 1836 |
+
self.release()
|
| 1837 |
+
raise
|
| 1838 |
+
|
| 1839 |
+
return
|
| 1840 |
+
|
| 1841 |
+
if self._owner_task == task:
|
| 1842 |
+
raise RuntimeError("Attempted to acquire an already held Lock")
|
| 1843 |
+
|
| 1844 |
+
fut: asyncio.Future[None] = asyncio.Future()
|
| 1845 |
+
item = task, fut
|
| 1846 |
+
self._waiters.append(item)
|
| 1847 |
+
try:
|
| 1848 |
+
await fut
|
| 1849 |
+
except CancelledError:
|
| 1850 |
+
self._waiters.remove(item)
|
| 1851 |
+
if self._owner_task is task:
|
| 1852 |
+
self.release()
|
| 1853 |
+
|
| 1854 |
+
raise
|
| 1855 |
+
|
| 1856 |
+
self._waiters.remove(item)
|
| 1857 |
+
|
| 1858 |
+
def acquire_nowait(self) -> None:
|
| 1859 |
+
task = cast(asyncio.Task, current_task())
|
| 1860 |
+
if self._owner_task is None and not self._waiters:
|
| 1861 |
+
self._owner_task = task
|
| 1862 |
+
return
|
| 1863 |
+
|
| 1864 |
+
if self._owner_task is task:
|
| 1865 |
+
raise RuntimeError("Attempted to acquire an already held Lock")
|
| 1866 |
+
|
| 1867 |
+
raise WouldBlock
|
| 1868 |
+
|
| 1869 |
+
def locked(self) -> bool:
|
| 1870 |
+
return self._owner_task is not None
|
| 1871 |
+
|
| 1872 |
+
def release(self) -> None:
|
| 1873 |
+
if self._owner_task != current_task():
|
| 1874 |
+
raise RuntimeError("The current task is not holding this lock")
|
| 1875 |
+
|
| 1876 |
+
for task, fut in self._waiters:
|
| 1877 |
+
if not fut.cancelled():
|
| 1878 |
+
self._owner_task = task
|
| 1879 |
+
fut.set_result(None)
|
| 1880 |
+
return
|
| 1881 |
+
|
| 1882 |
+
self._owner_task = None
|
| 1883 |
+
|
| 1884 |
+
def statistics(self) -> LockStatistics:
|
| 1885 |
+
task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None
|
| 1886 |
+
return LockStatistics(self.locked(), task_info, len(self._waiters))
|
| 1887 |
+
|
| 1888 |
+
|
| 1889 |
+
class Semaphore(BaseSemaphore):
|
| 1890 |
+
def __new__(
|
| 1891 |
+
cls,
|
| 1892 |
+
initial_value: int,
|
| 1893 |
+
*,
|
| 1894 |
+
max_value: int | None = None,
|
| 1895 |
+
fast_acquire: bool = False,
|
| 1896 |
+
) -> Semaphore:
|
| 1897 |
+
return object.__new__(cls)
|
| 1898 |
+
|
| 1899 |
+
def __init__(
|
| 1900 |
+
self,
|
| 1901 |
+
initial_value: int,
|
| 1902 |
+
*,
|
| 1903 |
+
max_value: int | None = None,
|
| 1904 |
+
fast_acquire: bool = False,
|
| 1905 |
+
):
|
| 1906 |
+
super().__init__(initial_value, max_value=max_value)
|
| 1907 |
+
self._value = initial_value
|
| 1908 |
+
self._max_value = max_value
|
| 1909 |
+
self._fast_acquire = fast_acquire
|
| 1910 |
+
self._waiters: deque[asyncio.Future[None]] = deque()
|
| 1911 |
+
|
| 1912 |
+
async def acquire(self) -> None:
|
| 1913 |
+
if self._value > 0 and not self._waiters:
|
| 1914 |
+
await AsyncIOBackend.checkpoint_if_cancelled()
|
| 1915 |
+
self._value -= 1
|
| 1916 |
+
|
| 1917 |
+
# Unless on the "fast path", yield control of the event loop so that other
|
| 1918 |
+
# tasks can run too
|
| 1919 |
+
if not self._fast_acquire:
|
| 1920 |
+
try:
|
| 1921 |
+
await AsyncIOBackend.cancel_shielded_checkpoint()
|
| 1922 |
+
except CancelledError:
|
| 1923 |
+
self.release()
|
| 1924 |
+
raise
|
| 1925 |
+
|
| 1926 |
+
return
|
| 1927 |
+
|
| 1928 |
+
fut: asyncio.Future[None] = asyncio.Future()
|
| 1929 |
+
self._waiters.append(fut)
|
| 1930 |
+
try:
|
| 1931 |
+
await fut
|
| 1932 |
+
except CancelledError:
|
| 1933 |
+
try:
|
| 1934 |
+
self._waiters.remove(fut)
|
| 1935 |
+
except ValueError:
|
| 1936 |
+
self.release()
|
| 1937 |
+
|
| 1938 |
+
raise
|
| 1939 |
+
|
| 1940 |
+
def acquire_nowait(self) -> None:
|
| 1941 |
+
if self._value == 0:
|
| 1942 |
+
raise WouldBlock
|
| 1943 |
+
|
| 1944 |
+
self._value -= 1
|
| 1945 |
+
|
| 1946 |
+
def release(self) -> None:
|
| 1947 |
+
if self._max_value is not None and self._value == self._max_value:
|
| 1948 |
+
raise ValueError("semaphore released too many times")
|
| 1949 |
+
|
| 1950 |
+
for fut in self._waiters:
|
| 1951 |
+
if not fut.cancelled():
|
| 1952 |
+
fut.set_result(None)
|
| 1953 |
+
self._waiters.remove(fut)
|
| 1954 |
+
return
|
| 1955 |
+
|
| 1956 |
+
self._value += 1
|
| 1957 |
+
|
| 1958 |
+
@property
|
| 1959 |
+
def value(self) -> int:
|
| 1960 |
+
return self._value
|
| 1961 |
+
|
| 1962 |
+
@property
|
| 1963 |
+
def max_value(self) -> int | None:
|
| 1964 |
+
return self._max_value
|
| 1965 |
+
|
| 1966 |
+
def statistics(self) -> SemaphoreStatistics:
|
| 1967 |
+
return SemaphoreStatistics(len(self._waiters))
|
| 1968 |
+
|
| 1969 |
+
|
| 1970 |
+
class CapacityLimiter(BaseCapacityLimiter):
|
| 1971 |
+
_total_tokens: float = 0
|
| 1972 |
+
|
| 1973 |
+
def __new__(cls, total_tokens: float) -> CapacityLimiter:
|
| 1974 |
+
return object.__new__(cls)
|
| 1975 |
+
|
| 1976 |
+
def __init__(self, total_tokens: float):
|
| 1977 |
+
self._borrowers: set[Any] = set()
|
| 1978 |
+
self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict()
|
| 1979 |
+
self.total_tokens = total_tokens
|
| 1980 |
+
|
| 1981 |
+
async def __aenter__(self) -> None:
|
| 1982 |
+
await self.acquire()
|
| 1983 |
+
|
| 1984 |
+
async def __aexit__(
|
| 1985 |
+
self,
|
| 1986 |
+
exc_type: type[BaseException] | None,
|
| 1987 |
+
exc_val: BaseException | None,
|
| 1988 |
+
exc_tb: TracebackType | None,
|
| 1989 |
+
) -> None:
|
| 1990 |
+
self.release()
|
| 1991 |
+
|
| 1992 |
+
@property
|
| 1993 |
+
def total_tokens(self) -> float:
|
| 1994 |
+
return self._total_tokens
|
| 1995 |
+
|
| 1996 |
+
@total_tokens.setter
|
| 1997 |
+
def total_tokens(self, value: float) -> None:
|
| 1998 |
+
if not isinstance(value, int) and not math.isinf(value):
|
| 1999 |
+
raise TypeError("total_tokens must be an int or math.inf")
|
| 2000 |
+
if value < 1:
|
| 2001 |
+
raise ValueError("total_tokens must be >= 1")
|
| 2002 |
+
|
| 2003 |
+
waiters_to_notify = max(value - self._total_tokens, 0)
|
| 2004 |
+
self._total_tokens = value
|
| 2005 |
+
|
| 2006 |
+
# Notify waiting tasks that they have acquired the limiter
|
| 2007 |
+
while self._wait_queue and waiters_to_notify:
|
| 2008 |
+
event = self._wait_queue.popitem(last=False)[1]
|
| 2009 |
+
event.set()
|
| 2010 |
+
waiters_to_notify -= 1
|
| 2011 |
+
|
| 2012 |
+
@property
|
| 2013 |
+
def borrowed_tokens(self) -> int:
|
| 2014 |
+
return len(self._borrowers)
|
| 2015 |
+
|
| 2016 |
+
@property
|
| 2017 |
+
def available_tokens(self) -> float:
|
| 2018 |
+
return self._total_tokens - len(self._borrowers)
|
| 2019 |
+
|
| 2020 |
+
def acquire_nowait(self) -> None:
|
| 2021 |
+
self.acquire_on_behalf_of_nowait(current_task())
|
| 2022 |
+
|
| 2023 |
+
def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
|
| 2024 |
+
if borrower in self._borrowers:
|
| 2025 |
+
raise RuntimeError(
|
| 2026 |
+
"this borrower is already holding one of this CapacityLimiter's "
|
| 2027 |
+
"tokens"
|
| 2028 |
+
)
|
| 2029 |
+
|
| 2030 |
+
if self._wait_queue or len(self._borrowers) >= self._total_tokens:
|
| 2031 |
+
raise WouldBlock
|
| 2032 |
+
|
| 2033 |
+
self._borrowers.add(borrower)
|
| 2034 |
+
|
| 2035 |
+
async def acquire(self) -> None:
|
| 2036 |
+
return await self.acquire_on_behalf_of(current_task())
|
| 2037 |
+
|
| 2038 |
+
async def acquire_on_behalf_of(self, borrower: object) -> None:
|
| 2039 |
+
await AsyncIOBackend.checkpoint_if_cancelled()
|
| 2040 |
+
try:
|
| 2041 |
+
self.acquire_on_behalf_of_nowait(borrower)
|
| 2042 |
+
except WouldBlock:
|
| 2043 |
+
event = asyncio.Event()
|
| 2044 |
+
self._wait_queue[borrower] = event
|
| 2045 |
+
try:
|
| 2046 |
+
await event.wait()
|
| 2047 |
+
except BaseException:
|
| 2048 |
+
self._wait_queue.pop(borrower, None)
|
| 2049 |
+
raise
|
| 2050 |
+
|
| 2051 |
+
self._borrowers.add(borrower)
|
| 2052 |
+
else:
|
| 2053 |
+
try:
|
| 2054 |
+
await AsyncIOBackend.cancel_shielded_checkpoint()
|
| 2055 |
+
except BaseException:
|
| 2056 |
+
self.release()
|
| 2057 |
+
raise
|
| 2058 |
+
|
| 2059 |
+
def release(self) -> None:
|
| 2060 |
+
self.release_on_behalf_of(current_task())
|
| 2061 |
+
|
| 2062 |
+
def release_on_behalf_of(self, borrower: object) -> None:
|
| 2063 |
+
try:
|
| 2064 |
+
self._borrowers.remove(borrower)
|
| 2065 |
+
except KeyError:
|
| 2066 |
+
raise RuntimeError(
|
| 2067 |
+
"this borrower isn't holding any of this CapacityLimiter's tokens"
|
| 2068 |
+
) from None
|
| 2069 |
+
|
| 2070 |
+
# Notify the next task in line if this limiter has free capacity now
|
| 2071 |
+
if self._wait_queue and len(self._borrowers) < self._total_tokens:
|
| 2072 |
+
event = self._wait_queue.popitem(last=False)[1]
|
| 2073 |
+
event.set()
|
| 2074 |
+
|
| 2075 |
+
def statistics(self) -> CapacityLimiterStatistics:
|
| 2076 |
+
return CapacityLimiterStatistics(
|
| 2077 |
+
self.borrowed_tokens,
|
| 2078 |
+
self.total_tokens,
|
| 2079 |
+
tuple(self._borrowers),
|
| 2080 |
+
len(self._wait_queue),
|
| 2081 |
+
)
|
| 2082 |
+
|
| 2083 |
+
|
| 2084 |
+
_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter")
|
| 2085 |
+
|
| 2086 |
+
|
| 2087 |
+
#
|
| 2088 |
+
# Operating system signals
|
| 2089 |
+
#
|
| 2090 |
+
|
| 2091 |
+
|
| 2092 |
+
class _SignalReceiver:
|
| 2093 |
+
def __init__(self, signals: tuple[Signals, ...]):
|
| 2094 |
+
self._signals = signals
|
| 2095 |
+
self._loop = get_running_loop()
|
| 2096 |
+
self._signal_queue: deque[Signals] = deque()
|
| 2097 |
+
self._future: asyncio.Future = asyncio.Future()
|
| 2098 |
+
self._handled_signals: set[Signals] = set()
|
| 2099 |
+
|
| 2100 |
+
def _deliver(self, signum: Signals) -> None:
|
| 2101 |
+
self._signal_queue.append(signum)
|
| 2102 |
+
if not self._future.done():
|
| 2103 |
+
self._future.set_result(None)
|
| 2104 |
+
|
| 2105 |
+
def __enter__(self) -> _SignalReceiver:
|
| 2106 |
+
for sig in set(self._signals):
|
| 2107 |
+
self._loop.add_signal_handler(sig, self._deliver, sig)
|
| 2108 |
+
self._handled_signals.add(sig)
|
| 2109 |
+
|
| 2110 |
+
return self
|
| 2111 |
+
|
| 2112 |
+
def __exit__(
|
| 2113 |
+
self,
|
| 2114 |
+
exc_type: type[BaseException] | None,
|
| 2115 |
+
exc_val: BaseException | None,
|
| 2116 |
+
exc_tb: TracebackType | None,
|
| 2117 |
+
) -> bool | None:
|
| 2118 |
+
for sig in self._handled_signals:
|
| 2119 |
+
self._loop.remove_signal_handler(sig)
|
| 2120 |
+
return None
|
| 2121 |
+
|
| 2122 |
+
def __aiter__(self) -> _SignalReceiver:
|
| 2123 |
+
return self
|
| 2124 |
+
|
| 2125 |
+
async def __anext__(self) -> Signals:
|
| 2126 |
+
await AsyncIOBackend.checkpoint()
|
| 2127 |
+
if not self._signal_queue:
|
| 2128 |
+
self._future = asyncio.Future()
|
| 2129 |
+
await self._future
|
| 2130 |
+
|
| 2131 |
+
return self._signal_queue.popleft()
|
| 2132 |
+
|
| 2133 |
+
|
| 2134 |
+
#
|
| 2135 |
+
# Testing and debugging
|
| 2136 |
+
#
|
| 2137 |
+
|
| 2138 |
+
|
| 2139 |
+
class AsyncIOTaskInfo(TaskInfo):
|
| 2140 |
+
def __init__(self, task: asyncio.Task):
|
| 2141 |
+
task_state = _task_states.get(task)
|
| 2142 |
+
if task_state is None:
|
| 2143 |
+
parent_id = None
|
| 2144 |
+
else:
|
| 2145 |
+
parent_id = task_state.parent_id
|
| 2146 |
+
|
| 2147 |
+
coro = task.get_coro()
|
| 2148 |
+
assert coro is not None, "created TaskInfo from a completed Task"
|
| 2149 |
+
super().__init__(id(task), parent_id, task.get_name(), coro)
|
| 2150 |
+
self._task = weakref.ref(task)
|
| 2151 |
+
|
| 2152 |
+
def has_pending_cancellation(self) -> bool:
|
| 2153 |
+
if not (task := self._task()):
|
| 2154 |
+
# If the task isn't around anymore, it won't have a pending cancellation
|
| 2155 |
+
return False
|
| 2156 |
+
|
| 2157 |
+
if task._must_cancel: # type: ignore[attr-defined]
|
| 2158 |
+
return True
|
| 2159 |
+
elif (
|
| 2160 |
+
isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined]
|
| 2161 |
+
and task._fut_waiter.cancelled() # type: ignore[attr-defined]
|
| 2162 |
+
):
|
| 2163 |
+
return True
|
| 2164 |
+
|
| 2165 |
+
if task_state := _task_states.get(task):
|
| 2166 |
+
if cancel_scope := task_state.cancel_scope:
|
| 2167 |
+
return cancel_scope._effectively_cancelled
|
| 2168 |
+
|
| 2169 |
+
return False
|
| 2170 |
+
|
| 2171 |
+
|
| 2172 |
+
class TestRunner(abc.TestRunner):
|
| 2173 |
+
_send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]]
|
| 2174 |
+
|
| 2175 |
+
def __init__(
|
| 2176 |
+
self,
|
| 2177 |
+
*,
|
| 2178 |
+
debug: bool | None = None,
|
| 2179 |
+
use_uvloop: bool = False,
|
| 2180 |
+
loop_factory: Callable[[], AbstractEventLoop] | None = None,
|
| 2181 |
+
) -> None:
|
| 2182 |
+
if use_uvloop and loop_factory is None:
|
| 2183 |
+
import uvloop
|
| 2184 |
+
|
| 2185 |
+
loop_factory = uvloop.new_event_loop
|
| 2186 |
+
|
| 2187 |
+
self._runner = Runner(debug=debug, loop_factory=loop_factory)
|
| 2188 |
+
self._exceptions: list[BaseException] = []
|
| 2189 |
+
self._runner_task: asyncio.Task | None = None
|
| 2190 |
+
|
| 2191 |
+
def __enter__(self) -> TestRunner:
|
| 2192 |
+
self._runner.__enter__()
|
| 2193 |
+
self.get_loop().set_exception_handler(self._exception_handler)
|
| 2194 |
+
return self
|
| 2195 |
+
|
| 2196 |
+
def __exit__(
|
| 2197 |
+
self,
|
| 2198 |
+
exc_type: type[BaseException] | None,
|
| 2199 |
+
exc_val: BaseException | None,
|
| 2200 |
+
exc_tb: TracebackType | None,
|
| 2201 |
+
) -> None:
|
| 2202 |
+
self._runner.__exit__(exc_type, exc_val, exc_tb)
|
| 2203 |
+
|
| 2204 |
+
def get_loop(self) -> AbstractEventLoop:
|
| 2205 |
+
return self._runner.get_loop()
|
| 2206 |
+
|
| 2207 |
+
def _exception_handler(
|
| 2208 |
+
self, loop: asyncio.AbstractEventLoop, context: dict[str, Any]
|
| 2209 |
+
) -> None:
|
| 2210 |
+
if isinstance(context.get("exception"), Exception):
|
| 2211 |
+
self._exceptions.append(context["exception"])
|
| 2212 |
+
else:
|
| 2213 |
+
loop.default_exception_handler(context)
|
| 2214 |
+
|
| 2215 |
+
def _raise_async_exceptions(self) -> None:
|
| 2216 |
+
# Re-raise any exceptions raised in asynchronous callbacks
|
| 2217 |
+
if self._exceptions:
|
| 2218 |
+
exceptions, self._exceptions = self._exceptions, []
|
| 2219 |
+
if len(exceptions) == 1:
|
| 2220 |
+
raise exceptions[0]
|
| 2221 |
+
elif exceptions:
|
| 2222 |
+
raise BaseExceptionGroup(
|
| 2223 |
+
"Multiple exceptions occurred in asynchronous callbacks", exceptions
|
| 2224 |
+
)
|
| 2225 |
+
|
| 2226 |
+
async def _run_tests_and_fixtures(
|
| 2227 |
+
self,
|
| 2228 |
+
receive_stream: MemoryObjectReceiveStream[
|
| 2229 |
+
tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]]
|
| 2230 |
+
],
|
| 2231 |
+
) -> None:
|
| 2232 |
+
from _pytest.outcomes import OutcomeException
|
| 2233 |
+
|
| 2234 |
+
with receive_stream, self._send_stream:
|
| 2235 |
+
async for coro, future in receive_stream:
|
| 2236 |
+
try:
|
| 2237 |
+
retval = await coro
|
| 2238 |
+
except CancelledError as exc:
|
| 2239 |
+
if not future.cancelled():
|
| 2240 |
+
future.cancel(*exc.args)
|
| 2241 |
+
|
| 2242 |
+
raise
|
| 2243 |
+
except BaseException as exc:
|
| 2244 |
+
if not future.cancelled():
|
| 2245 |
+
future.set_exception(exc)
|
| 2246 |
+
|
| 2247 |
+
if not isinstance(exc, (Exception, OutcomeException)):
|
| 2248 |
+
raise
|
| 2249 |
+
else:
|
| 2250 |
+
if not future.cancelled():
|
| 2251 |
+
future.set_result(retval)
|
| 2252 |
+
|
| 2253 |
+
async def _call_in_runner_task(
|
| 2254 |
+
self,
|
| 2255 |
+
func: Callable[P, Awaitable[T_Retval]],
|
| 2256 |
+
*args: P.args,
|
| 2257 |
+
**kwargs: P.kwargs,
|
| 2258 |
+
) -> T_Retval:
|
| 2259 |
+
if not self._runner_task:
|
| 2260 |
+
self._send_stream, receive_stream = create_memory_object_stream[
|
| 2261 |
+
tuple[Awaitable[Any], asyncio.Future]
|
| 2262 |
+
](1)
|
| 2263 |
+
self._runner_task = self.get_loop().create_task(
|
| 2264 |
+
self._run_tests_and_fixtures(receive_stream)
|
| 2265 |
+
)
|
| 2266 |
+
|
| 2267 |
+
coro = func(*args, **kwargs)
|
| 2268 |
+
future: asyncio.Future[T_Retval] = self.get_loop().create_future()
|
| 2269 |
+
self._send_stream.send_nowait((coro, future))
|
| 2270 |
+
return await future
|
| 2271 |
+
|
| 2272 |
+
def run_asyncgen_fixture(
|
| 2273 |
+
self,
|
| 2274 |
+
fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]],
|
| 2275 |
+
kwargs: dict[str, Any],
|
| 2276 |
+
) -> Iterable[T_Retval]:
|
| 2277 |
+
asyncgen = fixture_func(**kwargs)
|
| 2278 |
+
fixturevalue: T_Retval = self.get_loop().run_until_complete(
|
| 2279 |
+
self._call_in_runner_task(asyncgen.asend, None)
|
| 2280 |
+
)
|
| 2281 |
+
self._raise_async_exceptions()
|
| 2282 |
+
|
| 2283 |
+
yield fixturevalue
|
| 2284 |
+
|
| 2285 |
+
try:
|
| 2286 |
+
self.get_loop().run_until_complete(
|
| 2287 |
+
self._call_in_runner_task(asyncgen.asend, None)
|
| 2288 |
+
)
|
| 2289 |
+
except StopAsyncIteration:
|
| 2290 |
+
self._raise_async_exceptions()
|
| 2291 |
+
else:
|
| 2292 |
+
self.get_loop().run_until_complete(asyncgen.aclose())
|
| 2293 |
+
raise RuntimeError("Async generator fixture did not stop")
|
| 2294 |
+
|
| 2295 |
+
def run_fixture(
|
| 2296 |
+
self,
|
| 2297 |
+
fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]],
|
| 2298 |
+
kwargs: dict[str, Any],
|
| 2299 |
+
) -> T_Retval:
|
| 2300 |
+
retval = self.get_loop().run_until_complete(
|
| 2301 |
+
self._call_in_runner_task(fixture_func, **kwargs)
|
| 2302 |
+
)
|
| 2303 |
+
self._raise_async_exceptions()
|
| 2304 |
+
return retval
|
| 2305 |
+
|
| 2306 |
+
def run_test(
|
| 2307 |
+
self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
|
| 2308 |
+
) -> None:
|
| 2309 |
+
try:
|
| 2310 |
+
self.get_loop().run_until_complete(
|
| 2311 |
+
self._call_in_runner_task(test_func, **kwargs)
|
| 2312 |
+
)
|
| 2313 |
+
except Exception as exc:
|
| 2314 |
+
self._exceptions.append(exc)
|
| 2315 |
+
|
| 2316 |
+
self._raise_async_exceptions()
|
| 2317 |
+
|
| 2318 |
+
|
| 2319 |
+
class AsyncIOBackend(AsyncBackend):
|
| 2320 |
+
@classmethod
|
| 2321 |
+
def run(
|
| 2322 |
+
cls,
|
| 2323 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 2324 |
+
args: tuple[Unpack[PosArgsT]],
|
| 2325 |
+
kwargs: dict[str, Any],
|
| 2326 |
+
options: dict[str, Any],
|
| 2327 |
+
) -> T_Retval:
|
| 2328 |
+
@wraps(func)
|
| 2329 |
+
async def wrapper() -> T_Retval:
|
| 2330 |
+
task = cast(asyncio.Task, current_task())
|
| 2331 |
+
task.set_name(get_callable_name(func))
|
| 2332 |
+
_task_states[task] = TaskState(None, None)
|
| 2333 |
+
|
| 2334 |
+
try:
|
| 2335 |
+
return await func(*args)
|
| 2336 |
+
finally:
|
| 2337 |
+
del _task_states[task]
|
| 2338 |
+
|
| 2339 |
+
debug = options.get("debug", None)
|
| 2340 |
+
loop_factory = options.get("loop_factory", None)
|
| 2341 |
+
if loop_factory is None and options.get("use_uvloop", False):
|
| 2342 |
+
import uvloop
|
| 2343 |
+
|
| 2344 |
+
loop_factory = uvloop.new_event_loop
|
| 2345 |
+
|
| 2346 |
+
with Runner(debug=debug, loop_factory=loop_factory) as runner:
|
| 2347 |
+
return runner.run(wrapper())
|
| 2348 |
+
|
| 2349 |
+
@classmethod
|
| 2350 |
+
def current_token(cls) -> object:
|
| 2351 |
+
return get_running_loop()
|
| 2352 |
+
|
| 2353 |
+
@classmethod
|
| 2354 |
+
def current_time(cls) -> float:
|
| 2355 |
+
return get_running_loop().time()
|
| 2356 |
+
|
| 2357 |
+
@classmethod
|
| 2358 |
+
def cancelled_exception_class(cls) -> type[BaseException]:
|
| 2359 |
+
return CancelledError
|
| 2360 |
+
|
| 2361 |
+
@classmethod
|
| 2362 |
+
async def checkpoint(cls) -> None:
|
| 2363 |
+
await sleep(0)
|
| 2364 |
+
|
| 2365 |
+
@classmethod
|
| 2366 |
+
async def checkpoint_if_cancelled(cls) -> None:
|
| 2367 |
+
task = current_task()
|
| 2368 |
+
if task is None:
|
| 2369 |
+
return
|
| 2370 |
+
|
| 2371 |
+
try:
|
| 2372 |
+
cancel_scope = _task_states[task].cancel_scope
|
| 2373 |
+
except KeyError:
|
| 2374 |
+
return
|
| 2375 |
+
|
| 2376 |
+
while cancel_scope:
|
| 2377 |
+
if cancel_scope.cancel_called:
|
| 2378 |
+
await sleep(0)
|
| 2379 |
+
elif cancel_scope.shield:
|
| 2380 |
+
break
|
| 2381 |
+
else:
|
| 2382 |
+
cancel_scope = cancel_scope._parent_scope
|
| 2383 |
+
|
| 2384 |
+
@classmethod
|
| 2385 |
+
async def cancel_shielded_checkpoint(cls) -> None:
|
| 2386 |
+
with CancelScope(shield=True):
|
| 2387 |
+
await sleep(0)
|
| 2388 |
+
|
| 2389 |
+
@classmethod
|
| 2390 |
+
async def sleep(cls, delay: float) -> None:
|
| 2391 |
+
await sleep(delay)
|
| 2392 |
+
|
| 2393 |
+
@classmethod
|
| 2394 |
+
def create_cancel_scope(
|
| 2395 |
+
cls, *, deadline: float = math.inf, shield: bool = False
|
| 2396 |
+
) -> CancelScope:
|
| 2397 |
+
return CancelScope(deadline=deadline, shield=shield)
|
| 2398 |
+
|
| 2399 |
+
@classmethod
|
| 2400 |
+
def current_effective_deadline(cls) -> float:
|
| 2401 |
+
if (task := current_task()) is None:
|
| 2402 |
+
return math.inf
|
| 2403 |
+
|
| 2404 |
+
try:
|
| 2405 |
+
cancel_scope = _task_states[task].cancel_scope
|
| 2406 |
+
except KeyError:
|
| 2407 |
+
return math.inf
|
| 2408 |
+
|
| 2409 |
+
deadline = math.inf
|
| 2410 |
+
while cancel_scope:
|
| 2411 |
+
deadline = min(deadline, cancel_scope.deadline)
|
| 2412 |
+
if cancel_scope._cancel_called:
|
| 2413 |
+
deadline = -math.inf
|
| 2414 |
+
break
|
| 2415 |
+
elif cancel_scope.shield:
|
| 2416 |
+
break
|
| 2417 |
+
else:
|
| 2418 |
+
cancel_scope = cancel_scope._parent_scope
|
| 2419 |
+
|
| 2420 |
+
return deadline
|
| 2421 |
+
|
| 2422 |
+
@classmethod
|
| 2423 |
+
def create_task_group(cls) -> abc.TaskGroup:
|
| 2424 |
+
return TaskGroup()
|
| 2425 |
+
|
| 2426 |
+
@classmethod
|
| 2427 |
+
def create_event(cls) -> abc.Event:
|
| 2428 |
+
return Event()
|
| 2429 |
+
|
| 2430 |
+
@classmethod
|
| 2431 |
+
def create_lock(cls, *, fast_acquire: bool) -> abc.Lock:
|
| 2432 |
+
return Lock(fast_acquire=fast_acquire)
|
| 2433 |
+
|
| 2434 |
+
@classmethod
|
| 2435 |
+
def create_semaphore(
|
| 2436 |
+
cls,
|
| 2437 |
+
initial_value: int,
|
| 2438 |
+
*,
|
| 2439 |
+
max_value: int | None = None,
|
| 2440 |
+
fast_acquire: bool = False,
|
| 2441 |
+
) -> abc.Semaphore:
|
| 2442 |
+
return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
|
| 2443 |
+
|
| 2444 |
+
@classmethod
|
| 2445 |
+
def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter:
|
| 2446 |
+
return CapacityLimiter(total_tokens)
|
| 2447 |
+
|
| 2448 |
+
@classmethod
|
| 2449 |
+
async def run_sync_in_worker_thread(
|
| 2450 |
+
cls,
|
| 2451 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 2452 |
+
args: tuple[Unpack[PosArgsT]],
|
| 2453 |
+
abandon_on_cancel: bool = False,
|
| 2454 |
+
limiter: abc.CapacityLimiter | None = None,
|
| 2455 |
+
) -> T_Retval:
|
| 2456 |
+
await cls.checkpoint()
|
| 2457 |
+
|
| 2458 |
+
# If this is the first run in this event loop thread, set up the necessary
|
| 2459 |
+
# variables
|
| 2460 |
+
try:
|
| 2461 |
+
idle_workers = _threadpool_idle_workers.get()
|
| 2462 |
+
workers = _threadpool_workers.get()
|
| 2463 |
+
except LookupError:
|
| 2464 |
+
idle_workers = deque()
|
| 2465 |
+
workers = set()
|
| 2466 |
+
_threadpool_idle_workers.set(idle_workers)
|
| 2467 |
+
_threadpool_workers.set(workers)
|
| 2468 |
+
|
| 2469 |
+
async with limiter or cls.current_default_thread_limiter():
|
| 2470 |
+
with CancelScope(shield=not abandon_on_cancel) as scope:
|
| 2471 |
+
future: asyncio.Future = asyncio.Future()
|
| 2472 |
+
root_task = find_root_task()
|
| 2473 |
+
if not idle_workers:
|
| 2474 |
+
worker = WorkerThread(root_task, workers, idle_workers)
|
| 2475 |
+
worker.start()
|
| 2476 |
+
workers.add(worker)
|
| 2477 |
+
root_task.add_done_callback(worker.stop)
|
| 2478 |
+
else:
|
| 2479 |
+
worker = idle_workers.pop()
|
| 2480 |
+
|
| 2481 |
+
# Prune any other workers that have been idle for MAX_IDLE_TIME
|
| 2482 |
+
# seconds or longer
|
| 2483 |
+
now = cls.current_time()
|
| 2484 |
+
while idle_workers:
|
| 2485 |
+
if (
|
| 2486 |
+
now - idle_workers[0].idle_since
|
| 2487 |
+
< WorkerThread.MAX_IDLE_TIME
|
| 2488 |
+
):
|
| 2489 |
+
break
|
| 2490 |
+
|
| 2491 |
+
expired_worker = idle_workers.popleft()
|
| 2492 |
+
expired_worker.root_task.remove_done_callback(
|
| 2493 |
+
expired_worker.stop
|
| 2494 |
+
)
|
| 2495 |
+
expired_worker.stop()
|
| 2496 |
+
|
| 2497 |
+
context = copy_context()
|
| 2498 |
+
context.run(sniffio.current_async_library_cvar.set, None)
|
| 2499 |
+
if abandon_on_cancel or scope._parent_scope is None:
|
| 2500 |
+
worker_scope = scope
|
| 2501 |
+
else:
|
| 2502 |
+
worker_scope = scope._parent_scope
|
| 2503 |
+
|
| 2504 |
+
worker.queue.put_nowait((context, func, args, future, worker_scope))
|
| 2505 |
+
return await future
|
| 2506 |
+
|
| 2507 |
+
@classmethod
|
| 2508 |
+
def check_cancelled(cls) -> None:
|
| 2509 |
+
scope: CancelScope | None = threadlocals.current_cancel_scope
|
| 2510 |
+
while scope is not None:
|
| 2511 |
+
if scope.cancel_called:
|
| 2512 |
+
raise CancelledError(f"Cancelled by cancel scope {id(scope):x}")
|
| 2513 |
+
|
| 2514 |
+
if scope.shield:
|
| 2515 |
+
return
|
| 2516 |
+
|
| 2517 |
+
scope = scope._parent_scope
|
| 2518 |
+
|
| 2519 |
+
@classmethod
|
| 2520 |
+
def run_async_from_thread(
|
| 2521 |
+
cls,
|
| 2522 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 2523 |
+
args: tuple[Unpack[PosArgsT]],
|
| 2524 |
+
token: object,
|
| 2525 |
+
) -> T_Retval:
|
| 2526 |
+
async def task_wrapper(scope: CancelScope) -> T_Retval:
|
| 2527 |
+
__tracebackhide__ = True
|
| 2528 |
+
task = cast(asyncio.Task, current_task())
|
| 2529 |
+
_task_states[task] = TaskState(None, scope)
|
| 2530 |
+
scope._tasks.add(task)
|
| 2531 |
+
try:
|
| 2532 |
+
return await func(*args)
|
| 2533 |
+
except CancelledError as exc:
|
| 2534 |
+
raise concurrent.futures.CancelledError(str(exc)) from None
|
| 2535 |
+
finally:
|
| 2536 |
+
scope._tasks.discard(task)
|
| 2537 |
+
|
| 2538 |
+
loop = cast(AbstractEventLoop, token)
|
| 2539 |
+
context = copy_context()
|
| 2540 |
+
context.run(sniffio.current_async_library_cvar.set, "asyncio")
|
| 2541 |
+
wrapper = task_wrapper(threadlocals.current_cancel_scope)
|
| 2542 |
+
f: concurrent.futures.Future[T_Retval] = context.run(
|
| 2543 |
+
asyncio.run_coroutine_threadsafe, wrapper, loop
|
| 2544 |
+
)
|
| 2545 |
+
return f.result()
|
| 2546 |
+
|
| 2547 |
+
@classmethod
|
| 2548 |
+
def run_sync_from_thread(
|
| 2549 |
+
cls,
|
| 2550 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 2551 |
+
args: tuple[Unpack[PosArgsT]],
|
| 2552 |
+
token: object,
|
| 2553 |
+
) -> T_Retval:
|
| 2554 |
+
@wraps(func)
|
| 2555 |
+
def wrapper() -> None:
|
| 2556 |
+
try:
|
| 2557 |
+
sniffio.current_async_library_cvar.set("asyncio")
|
| 2558 |
+
f.set_result(func(*args))
|
| 2559 |
+
except BaseException as exc:
|
| 2560 |
+
f.set_exception(exc)
|
| 2561 |
+
if not isinstance(exc, Exception):
|
| 2562 |
+
raise
|
| 2563 |
+
|
| 2564 |
+
f: concurrent.futures.Future[T_Retval] = Future()
|
| 2565 |
+
loop = cast(AbstractEventLoop, token)
|
| 2566 |
+
loop.call_soon_threadsafe(wrapper)
|
| 2567 |
+
return f.result()
|
| 2568 |
+
|
| 2569 |
+
@classmethod
|
| 2570 |
+
def create_blocking_portal(cls) -> abc.BlockingPortal:
|
| 2571 |
+
return BlockingPortal()
|
| 2572 |
+
|
| 2573 |
+
@classmethod
|
| 2574 |
+
async def open_process(
|
| 2575 |
+
cls,
|
| 2576 |
+
command: StrOrBytesPath | Sequence[StrOrBytesPath],
|
| 2577 |
+
*,
|
| 2578 |
+
stdin: int | IO[Any] | None,
|
| 2579 |
+
stdout: int | IO[Any] | None,
|
| 2580 |
+
stderr: int | IO[Any] | None,
|
| 2581 |
+
**kwargs: Any,
|
| 2582 |
+
) -> Process:
|
| 2583 |
+
await cls.checkpoint()
|
| 2584 |
+
if isinstance(command, PathLike):
|
| 2585 |
+
command = os.fspath(command)
|
| 2586 |
+
|
| 2587 |
+
if isinstance(command, (str, bytes)):
|
| 2588 |
+
process = await asyncio.create_subprocess_shell(
|
| 2589 |
+
command,
|
| 2590 |
+
stdin=stdin,
|
| 2591 |
+
stdout=stdout,
|
| 2592 |
+
stderr=stderr,
|
| 2593 |
+
**kwargs,
|
| 2594 |
+
)
|
| 2595 |
+
else:
|
| 2596 |
+
process = await asyncio.create_subprocess_exec(
|
| 2597 |
+
*command,
|
| 2598 |
+
stdin=stdin,
|
| 2599 |
+
stdout=stdout,
|
| 2600 |
+
stderr=stderr,
|
| 2601 |
+
**kwargs,
|
| 2602 |
+
)
|
| 2603 |
+
|
| 2604 |
+
stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None
|
| 2605 |
+
stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None
|
| 2606 |
+
stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None
|
| 2607 |
+
return Process(process, stdin_stream, stdout_stream, stderr_stream)
|
| 2608 |
+
|
| 2609 |
+
@classmethod
|
| 2610 |
+
def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None:
|
| 2611 |
+
create_task(
|
| 2612 |
+
_shutdown_process_pool_on_exit(workers),
|
| 2613 |
+
name="AnyIO process pool shutdown task",
|
| 2614 |
+
)
|
| 2615 |
+
find_root_task().add_done_callback(
|
| 2616 |
+
partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type]
|
| 2617 |
+
)
|
| 2618 |
+
|
| 2619 |
+
@classmethod
|
| 2620 |
+
async def connect_tcp(
|
| 2621 |
+
cls, host: str, port: int, local_address: IPSockAddrType | None = None
|
| 2622 |
+
) -> abc.SocketStream:
|
| 2623 |
+
transport, protocol = cast(
|
| 2624 |
+
tuple[asyncio.Transport, StreamProtocol],
|
| 2625 |
+
await get_running_loop().create_connection(
|
| 2626 |
+
StreamProtocol, host, port, local_addr=local_address
|
| 2627 |
+
),
|
| 2628 |
+
)
|
| 2629 |
+
transport.pause_reading()
|
| 2630 |
+
return SocketStream(transport, protocol)
|
| 2631 |
+
|
| 2632 |
+
@classmethod
|
| 2633 |
+
async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream:
|
| 2634 |
+
await cls.checkpoint()
|
| 2635 |
+
loop = get_running_loop()
|
| 2636 |
+
raw_socket = socket.socket(socket.AF_UNIX)
|
| 2637 |
+
raw_socket.setblocking(False)
|
| 2638 |
+
while True:
|
| 2639 |
+
try:
|
| 2640 |
+
raw_socket.connect(path)
|
| 2641 |
+
except BlockingIOError:
|
| 2642 |
+
f: asyncio.Future = asyncio.Future()
|
| 2643 |
+
loop.add_writer(raw_socket, f.set_result, None)
|
| 2644 |
+
f.add_done_callback(lambda _: loop.remove_writer(raw_socket))
|
| 2645 |
+
await f
|
| 2646 |
+
except BaseException:
|
| 2647 |
+
raw_socket.close()
|
| 2648 |
+
raise
|
| 2649 |
+
else:
|
| 2650 |
+
return UNIXSocketStream(raw_socket)
|
| 2651 |
+
|
| 2652 |
+
@classmethod
|
| 2653 |
+
def create_tcp_listener(cls, sock: socket.socket) -> SocketListener:
|
| 2654 |
+
return TCPSocketListener(sock)
|
| 2655 |
+
|
| 2656 |
+
@classmethod
|
| 2657 |
+
def create_unix_listener(cls, sock: socket.socket) -> SocketListener:
|
| 2658 |
+
return UNIXSocketListener(sock)
|
| 2659 |
+
|
| 2660 |
+
@classmethod
|
| 2661 |
+
async def create_udp_socket(
|
| 2662 |
+
cls,
|
| 2663 |
+
family: AddressFamily,
|
| 2664 |
+
local_address: IPSockAddrType | None,
|
| 2665 |
+
remote_address: IPSockAddrType | None,
|
| 2666 |
+
reuse_port: bool,
|
| 2667 |
+
) -> UDPSocket | ConnectedUDPSocket:
|
| 2668 |
+
transport, protocol = await get_running_loop().create_datagram_endpoint(
|
| 2669 |
+
DatagramProtocol,
|
| 2670 |
+
local_addr=local_address,
|
| 2671 |
+
remote_addr=remote_address,
|
| 2672 |
+
family=family,
|
| 2673 |
+
reuse_port=reuse_port,
|
| 2674 |
+
)
|
| 2675 |
+
if protocol.exception:
|
| 2676 |
+
transport.close()
|
| 2677 |
+
raise protocol.exception
|
| 2678 |
+
|
| 2679 |
+
if not remote_address:
|
| 2680 |
+
return UDPSocket(transport, protocol)
|
| 2681 |
+
else:
|
| 2682 |
+
return ConnectedUDPSocket(transport, protocol)
|
| 2683 |
+
|
| 2684 |
+
@classmethod
|
| 2685 |
+
async def create_unix_datagram_socket( # type: ignore[override]
|
| 2686 |
+
cls, raw_socket: socket.socket, remote_path: str | bytes | None
|
| 2687 |
+
) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket:
|
| 2688 |
+
await cls.checkpoint()
|
| 2689 |
+
loop = get_running_loop()
|
| 2690 |
+
|
| 2691 |
+
if remote_path:
|
| 2692 |
+
while True:
|
| 2693 |
+
try:
|
| 2694 |
+
raw_socket.connect(remote_path)
|
| 2695 |
+
except BlockingIOError:
|
| 2696 |
+
f: asyncio.Future = asyncio.Future()
|
| 2697 |
+
loop.add_writer(raw_socket, f.set_result, None)
|
| 2698 |
+
f.add_done_callback(lambda _: loop.remove_writer(raw_socket))
|
| 2699 |
+
await f
|
| 2700 |
+
except BaseException:
|
| 2701 |
+
raw_socket.close()
|
| 2702 |
+
raise
|
| 2703 |
+
else:
|
| 2704 |
+
return ConnectedUNIXDatagramSocket(raw_socket)
|
| 2705 |
+
else:
|
| 2706 |
+
return UNIXDatagramSocket(raw_socket)
|
| 2707 |
+
|
| 2708 |
+
@classmethod
|
| 2709 |
+
async def getaddrinfo(
|
| 2710 |
+
cls,
|
| 2711 |
+
host: bytes | str | None,
|
| 2712 |
+
port: str | int | None,
|
| 2713 |
+
*,
|
| 2714 |
+
family: int | AddressFamily = 0,
|
| 2715 |
+
type: int | SocketKind = 0,
|
| 2716 |
+
proto: int = 0,
|
| 2717 |
+
flags: int = 0,
|
| 2718 |
+
) -> list[
|
| 2719 |
+
tuple[
|
| 2720 |
+
AddressFamily,
|
| 2721 |
+
SocketKind,
|
| 2722 |
+
int,
|
| 2723 |
+
str,
|
| 2724 |
+
tuple[str, int] | tuple[str, int, int, int],
|
| 2725 |
+
]
|
| 2726 |
+
]:
|
| 2727 |
+
return await get_running_loop().getaddrinfo(
|
| 2728 |
+
host, port, family=family, type=type, proto=proto, flags=flags
|
| 2729 |
+
)
|
| 2730 |
+
|
| 2731 |
+
@classmethod
|
| 2732 |
+
async def getnameinfo(
|
| 2733 |
+
cls, sockaddr: IPSockAddrType, flags: int = 0
|
| 2734 |
+
) -> tuple[str, str]:
|
| 2735 |
+
return await get_running_loop().getnameinfo(sockaddr, flags)
|
| 2736 |
+
|
| 2737 |
+
@classmethod
|
| 2738 |
+
async def wait_readable(cls, obj: FileDescriptorLike) -> None:
|
| 2739 |
+
await cls.checkpoint()
|
| 2740 |
+
try:
|
| 2741 |
+
read_events = _read_events.get()
|
| 2742 |
+
except LookupError:
|
| 2743 |
+
read_events = {}
|
| 2744 |
+
_read_events.set(read_events)
|
| 2745 |
+
|
| 2746 |
+
if not isinstance(obj, int):
|
| 2747 |
+
obj = obj.fileno()
|
| 2748 |
+
|
| 2749 |
+
if read_events.get(obj):
|
| 2750 |
+
raise BusyResourceError("reading from")
|
| 2751 |
+
|
| 2752 |
+
loop = get_running_loop()
|
| 2753 |
+
event = asyncio.Event()
|
| 2754 |
+
try:
|
| 2755 |
+
loop.add_reader(obj, event.set)
|
| 2756 |
+
except NotImplementedError:
|
| 2757 |
+
from anyio._core._asyncio_selector_thread import get_selector
|
| 2758 |
+
|
| 2759 |
+
selector = get_selector()
|
| 2760 |
+
selector.add_reader(obj, event.set)
|
| 2761 |
+
remove_reader = selector.remove_reader
|
| 2762 |
+
else:
|
| 2763 |
+
remove_reader = loop.remove_reader
|
| 2764 |
+
|
| 2765 |
+
read_events[obj] = event
|
| 2766 |
+
try:
|
| 2767 |
+
await event.wait()
|
| 2768 |
+
finally:
|
| 2769 |
+
remove_reader(obj)
|
| 2770 |
+
del read_events[obj]
|
| 2771 |
+
|
| 2772 |
+
@classmethod
|
| 2773 |
+
async def wait_writable(cls, obj: FileDescriptorLike) -> None:
|
| 2774 |
+
await cls.checkpoint()
|
| 2775 |
+
try:
|
| 2776 |
+
write_events = _write_events.get()
|
| 2777 |
+
except LookupError:
|
| 2778 |
+
write_events = {}
|
| 2779 |
+
_write_events.set(write_events)
|
| 2780 |
+
|
| 2781 |
+
if not isinstance(obj, int):
|
| 2782 |
+
obj = obj.fileno()
|
| 2783 |
+
|
| 2784 |
+
if write_events.get(obj):
|
| 2785 |
+
raise BusyResourceError("writing to")
|
| 2786 |
+
|
| 2787 |
+
loop = get_running_loop()
|
| 2788 |
+
event = asyncio.Event()
|
| 2789 |
+
try:
|
| 2790 |
+
loop.add_writer(obj, event.set)
|
| 2791 |
+
except NotImplementedError:
|
| 2792 |
+
from anyio._core._asyncio_selector_thread import get_selector
|
| 2793 |
+
|
| 2794 |
+
selector = get_selector()
|
| 2795 |
+
selector.add_writer(obj, event.set)
|
| 2796 |
+
remove_writer = selector.remove_writer
|
| 2797 |
+
else:
|
| 2798 |
+
remove_writer = loop.remove_writer
|
| 2799 |
+
|
| 2800 |
+
write_events[obj] = event
|
| 2801 |
+
try:
|
| 2802 |
+
await event.wait()
|
| 2803 |
+
finally:
|
| 2804 |
+
del write_events[obj]
|
| 2805 |
+
remove_writer(obj)
|
| 2806 |
+
|
| 2807 |
+
@classmethod
|
| 2808 |
+
def current_default_thread_limiter(cls) -> CapacityLimiter:
|
| 2809 |
+
try:
|
| 2810 |
+
return _default_thread_limiter.get()
|
| 2811 |
+
except LookupError:
|
| 2812 |
+
limiter = CapacityLimiter(40)
|
| 2813 |
+
_default_thread_limiter.set(limiter)
|
| 2814 |
+
return limiter
|
| 2815 |
+
|
| 2816 |
+
@classmethod
|
| 2817 |
+
def open_signal_receiver(
|
| 2818 |
+
cls, *signals: Signals
|
| 2819 |
+
) -> AbstractContextManager[AsyncIterator[Signals]]:
|
| 2820 |
+
return _SignalReceiver(signals)
|
| 2821 |
+
|
| 2822 |
+
@classmethod
|
| 2823 |
+
def get_current_task(cls) -> TaskInfo:
|
| 2824 |
+
return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type]
|
| 2825 |
+
|
| 2826 |
+
@classmethod
|
| 2827 |
+
def get_running_tasks(cls) -> Sequence[TaskInfo]:
|
| 2828 |
+
return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()]
|
| 2829 |
+
|
| 2830 |
+
@classmethod
|
| 2831 |
+
async def wait_all_tasks_blocked(cls) -> None:
|
| 2832 |
+
await cls.checkpoint()
|
| 2833 |
+
this_task = current_task()
|
| 2834 |
+
while True:
|
| 2835 |
+
for task in all_tasks():
|
| 2836 |
+
if task is this_task:
|
| 2837 |
+
continue
|
| 2838 |
+
|
| 2839 |
+
waiter = task._fut_waiter # type: ignore[attr-defined]
|
| 2840 |
+
if waiter is None or waiter.done():
|
| 2841 |
+
await sleep(0.1)
|
| 2842 |
+
break
|
| 2843 |
+
else:
|
| 2844 |
+
return
|
| 2845 |
+
|
| 2846 |
+
@classmethod
|
| 2847 |
+
def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
|
| 2848 |
+
return TestRunner(**options)
|
| 2849 |
+
|
| 2850 |
+
|
| 2851 |
+
backend_class = AsyncIOBackend
|
minigpt2/lib/python3.10/site-packages/anyio/_backends/_trio.py
ADDED
|
@@ -0,0 +1,1334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import array
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import socket
|
| 7 |
+
import sys
|
| 8 |
+
import types
|
| 9 |
+
import weakref
|
| 10 |
+
from collections.abc import (
|
| 11 |
+
AsyncGenerator,
|
| 12 |
+
AsyncIterator,
|
| 13 |
+
Awaitable,
|
| 14 |
+
Callable,
|
| 15 |
+
Collection,
|
| 16 |
+
Coroutine,
|
| 17 |
+
Iterable,
|
| 18 |
+
Sequence,
|
| 19 |
+
)
|
| 20 |
+
from concurrent.futures import Future
|
| 21 |
+
from contextlib import AbstractContextManager
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from functools import partial
|
| 24 |
+
from io import IOBase
|
| 25 |
+
from os import PathLike
|
| 26 |
+
from signal import Signals
|
| 27 |
+
from socket import AddressFamily, SocketKind
|
| 28 |
+
from types import TracebackType
|
| 29 |
+
from typing import (
|
| 30 |
+
IO,
|
| 31 |
+
TYPE_CHECKING,
|
| 32 |
+
Any,
|
| 33 |
+
Generic,
|
| 34 |
+
NoReturn,
|
| 35 |
+
TypeVar,
|
| 36 |
+
cast,
|
| 37 |
+
overload,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
import trio.from_thread
|
| 41 |
+
import trio.lowlevel
|
| 42 |
+
from outcome import Error, Outcome, Value
|
| 43 |
+
from trio.lowlevel import (
|
| 44 |
+
current_root_task,
|
| 45 |
+
current_task,
|
| 46 |
+
wait_readable,
|
| 47 |
+
wait_writable,
|
| 48 |
+
)
|
| 49 |
+
from trio.socket import SocketType as TrioSocketType
|
| 50 |
+
from trio.to_thread import run_sync
|
| 51 |
+
|
| 52 |
+
from .. import (
|
| 53 |
+
CapacityLimiterStatistics,
|
| 54 |
+
EventStatistics,
|
| 55 |
+
LockStatistics,
|
| 56 |
+
TaskInfo,
|
| 57 |
+
WouldBlock,
|
| 58 |
+
abc,
|
| 59 |
+
)
|
| 60 |
+
from .._core._eventloop import claim_worker_thread
|
| 61 |
+
from .._core._exceptions import (
|
| 62 |
+
BrokenResourceError,
|
| 63 |
+
BusyResourceError,
|
| 64 |
+
ClosedResourceError,
|
| 65 |
+
EndOfStream,
|
| 66 |
+
)
|
| 67 |
+
from .._core._sockets import convert_ipv6_sockaddr
|
| 68 |
+
from .._core._streams import create_memory_object_stream
|
| 69 |
+
from .._core._synchronization import (
|
| 70 |
+
CapacityLimiter as BaseCapacityLimiter,
|
| 71 |
+
)
|
| 72 |
+
from .._core._synchronization import Event as BaseEvent
|
| 73 |
+
from .._core._synchronization import Lock as BaseLock
|
| 74 |
+
from .._core._synchronization import (
|
| 75 |
+
ResourceGuard,
|
| 76 |
+
SemaphoreStatistics,
|
| 77 |
+
)
|
| 78 |
+
from .._core._synchronization import Semaphore as BaseSemaphore
|
| 79 |
+
from .._core._tasks import CancelScope as BaseCancelScope
|
| 80 |
+
from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType
|
| 81 |
+
from ..abc._eventloop import AsyncBackend, StrOrBytesPath
|
| 82 |
+
from ..streams.memory import MemoryObjectSendStream
|
| 83 |
+
|
| 84 |
+
if TYPE_CHECKING:
|
| 85 |
+
from _typeshed import HasFileno
|
| 86 |
+
|
| 87 |
+
if sys.version_info >= (3, 10):
|
| 88 |
+
from typing import ParamSpec
|
| 89 |
+
else:
|
| 90 |
+
from typing_extensions import ParamSpec
|
| 91 |
+
|
| 92 |
+
if sys.version_info >= (3, 11):
|
| 93 |
+
from typing import TypeVarTuple, Unpack
|
| 94 |
+
else:
|
| 95 |
+
from exceptiongroup import BaseExceptionGroup
|
| 96 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 97 |
+
|
| 98 |
+
T = TypeVar("T")
|
| 99 |
+
T_Retval = TypeVar("T_Retval")
|
| 100 |
+
T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType)
|
| 101 |
+
PosArgsT = TypeVarTuple("PosArgsT")
|
| 102 |
+
P = ParamSpec("P")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
#
|
| 106 |
+
# Event loop
|
| 107 |
+
#
|
| 108 |
+
|
| 109 |
+
RunVar = trio.lowlevel.RunVar
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
#
|
| 113 |
+
# Timeouts and cancellation
|
| 114 |
+
#
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class CancelScope(BaseCancelScope):
|
| 118 |
+
def __new__(
|
| 119 |
+
cls, original: trio.CancelScope | None = None, **kwargs: object
|
| 120 |
+
) -> CancelScope:
|
| 121 |
+
return object.__new__(cls)
|
| 122 |
+
|
| 123 |
+
def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None:
|
| 124 |
+
self.__original = original or trio.CancelScope(**kwargs)
|
| 125 |
+
|
| 126 |
+
def __enter__(self) -> CancelScope:
|
| 127 |
+
self.__original.__enter__()
|
| 128 |
+
return self
|
| 129 |
+
|
| 130 |
+
def __exit__(
|
| 131 |
+
self,
|
| 132 |
+
exc_type: type[BaseException] | None,
|
| 133 |
+
exc_val: BaseException | None,
|
| 134 |
+
exc_tb: TracebackType | None,
|
| 135 |
+
) -> bool | None:
|
| 136 |
+
# https://github.com/python-trio/trio-typing/pull/79
|
| 137 |
+
return self.__original.__exit__(exc_type, exc_val, exc_tb)
|
| 138 |
+
|
| 139 |
+
def cancel(self) -> None:
|
| 140 |
+
self.__original.cancel()
|
| 141 |
+
|
| 142 |
+
@property
|
| 143 |
+
def deadline(self) -> float:
|
| 144 |
+
return self.__original.deadline
|
| 145 |
+
|
| 146 |
+
@deadline.setter
|
| 147 |
+
def deadline(self, value: float) -> None:
|
| 148 |
+
self.__original.deadline = value
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def cancel_called(self) -> bool:
|
| 152 |
+
return self.__original.cancel_called
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def cancelled_caught(self) -> bool:
|
| 156 |
+
return self.__original.cancelled_caught
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def shield(self) -> bool:
|
| 160 |
+
return self.__original.shield
|
| 161 |
+
|
| 162 |
+
@shield.setter
|
| 163 |
+
def shield(self, value: bool) -> None:
|
| 164 |
+
self.__original.shield = value
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
#
|
| 168 |
+
# Task groups
|
| 169 |
+
#
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class TaskGroup(abc.TaskGroup):
|
| 173 |
+
def __init__(self) -> None:
|
| 174 |
+
self._active = False
|
| 175 |
+
self._nursery_manager = trio.open_nursery(strict_exception_groups=True)
|
| 176 |
+
self.cancel_scope = None # type: ignore[assignment]
|
| 177 |
+
|
| 178 |
+
async def __aenter__(self) -> TaskGroup:
|
| 179 |
+
self._active = True
|
| 180 |
+
self._nursery = await self._nursery_manager.__aenter__()
|
| 181 |
+
self.cancel_scope = CancelScope(self._nursery.cancel_scope)
|
| 182 |
+
return self
|
| 183 |
+
|
| 184 |
+
async def __aexit__(
|
| 185 |
+
self,
|
| 186 |
+
exc_type: type[BaseException] | None,
|
| 187 |
+
exc_val: BaseException | None,
|
| 188 |
+
exc_tb: TracebackType | None,
|
| 189 |
+
) -> bool | None:
|
| 190 |
+
try:
|
| 191 |
+
return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb)
|
| 192 |
+
except BaseExceptionGroup as exc:
|
| 193 |
+
if not exc.split(trio.Cancelled)[1]:
|
| 194 |
+
raise trio.Cancelled._create() from exc
|
| 195 |
+
|
| 196 |
+
raise
|
| 197 |
+
finally:
|
| 198 |
+
del exc_val, exc_tb
|
| 199 |
+
self._active = False
|
| 200 |
+
|
| 201 |
+
def start_soon(
|
| 202 |
+
self,
|
| 203 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
|
| 204 |
+
*args: Unpack[PosArgsT],
|
| 205 |
+
name: object = None,
|
| 206 |
+
) -> None:
|
| 207 |
+
if not self._active:
|
| 208 |
+
raise RuntimeError(
|
| 209 |
+
"This task group is not active; no new tasks can be started."
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
self._nursery.start_soon(func, *args, name=name)
|
| 213 |
+
|
| 214 |
+
async def start(
|
| 215 |
+
self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None
|
| 216 |
+
) -> Any:
|
| 217 |
+
if not self._active:
|
| 218 |
+
raise RuntimeError(
|
| 219 |
+
"This task group is not active; no new tasks can be started."
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
return await self._nursery.start(func, *args, name=name)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
#
|
| 226 |
+
# Threads
|
| 227 |
+
#
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class BlockingPortal(abc.BlockingPortal):
|
| 231 |
+
def __new__(cls) -> BlockingPortal:
|
| 232 |
+
return object.__new__(cls)
|
| 233 |
+
|
| 234 |
+
def __init__(self) -> None:
|
| 235 |
+
super().__init__()
|
| 236 |
+
self._token = trio.lowlevel.current_trio_token()
|
| 237 |
+
|
| 238 |
+
def _spawn_task_from_thread(
|
| 239 |
+
self,
|
| 240 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
|
| 241 |
+
args: tuple[Unpack[PosArgsT]],
|
| 242 |
+
kwargs: dict[str, Any],
|
| 243 |
+
name: object,
|
| 244 |
+
future: Future[T_Retval],
|
| 245 |
+
) -> None:
|
| 246 |
+
trio.from_thread.run_sync(
|
| 247 |
+
partial(self._task_group.start_soon, name=name),
|
| 248 |
+
self._call_func,
|
| 249 |
+
func,
|
| 250 |
+
args,
|
| 251 |
+
kwargs,
|
| 252 |
+
future,
|
| 253 |
+
trio_token=self._token,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
#
|
| 258 |
+
# Subprocesses
|
| 259 |
+
#
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@dataclass(eq=False)
|
| 263 |
+
class ReceiveStreamWrapper(abc.ByteReceiveStream):
|
| 264 |
+
_stream: trio.abc.ReceiveStream
|
| 265 |
+
|
| 266 |
+
async def receive(self, max_bytes: int | None = None) -> bytes:
|
| 267 |
+
try:
|
| 268 |
+
data = await self._stream.receive_some(max_bytes)
|
| 269 |
+
except trio.ClosedResourceError as exc:
|
| 270 |
+
raise ClosedResourceError from exc.__cause__
|
| 271 |
+
except trio.BrokenResourceError as exc:
|
| 272 |
+
raise BrokenResourceError from exc.__cause__
|
| 273 |
+
|
| 274 |
+
if data:
|
| 275 |
+
return data
|
| 276 |
+
else:
|
| 277 |
+
raise EndOfStream
|
| 278 |
+
|
| 279 |
+
async def aclose(self) -> None:
|
| 280 |
+
await self._stream.aclose()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@dataclass(eq=False)
|
| 284 |
+
class SendStreamWrapper(abc.ByteSendStream):
|
| 285 |
+
_stream: trio.abc.SendStream
|
| 286 |
+
|
| 287 |
+
async def send(self, item: bytes) -> None:
|
| 288 |
+
try:
|
| 289 |
+
await self._stream.send_all(item)
|
| 290 |
+
except trio.ClosedResourceError as exc:
|
| 291 |
+
raise ClosedResourceError from exc.__cause__
|
| 292 |
+
except trio.BrokenResourceError as exc:
|
| 293 |
+
raise BrokenResourceError from exc.__cause__
|
| 294 |
+
|
| 295 |
+
async def aclose(self) -> None:
|
| 296 |
+
await self._stream.aclose()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@dataclass(eq=False)
|
| 300 |
+
class Process(abc.Process):
|
| 301 |
+
_process: trio.Process
|
| 302 |
+
_stdin: abc.ByteSendStream | None
|
| 303 |
+
_stdout: abc.ByteReceiveStream | None
|
| 304 |
+
_stderr: abc.ByteReceiveStream | None
|
| 305 |
+
|
| 306 |
+
async def aclose(self) -> None:
|
| 307 |
+
with CancelScope(shield=True):
|
| 308 |
+
if self._stdin:
|
| 309 |
+
await self._stdin.aclose()
|
| 310 |
+
if self._stdout:
|
| 311 |
+
await self._stdout.aclose()
|
| 312 |
+
if self._stderr:
|
| 313 |
+
await self._stderr.aclose()
|
| 314 |
+
|
| 315 |
+
try:
|
| 316 |
+
await self.wait()
|
| 317 |
+
except BaseException:
|
| 318 |
+
self.kill()
|
| 319 |
+
with CancelScope(shield=True):
|
| 320 |
+
await self.wait()
|
| 321 |
+
raise
|
| 322 |
+
|
| 323 |
+
async def wait(self) -> int:
|
| 324 |
+
return await self._process.wait()
|
| 325 |
+
|
| 326 |
+
def terminate(self) -> None:
|
| 327 |
+
self._process.terminate()
|
| 328 |
+
|
| 329 |
+
def kill(self) -> None:
|
| 330 |
+
self._process.kill()
|
| 331 |
+
|
| 332 |
+
def send_signal(self, signal: Signals) -> None:
|
| 333 |
+
self._process.send_signal(signal)
|
| 334 |
+
|
| 335 |
+
@property
|
| 336 |
+
def pid(self) -> int:
|
| 337 |
+
return self._process.pid
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def returncode(self) -> int | None:
|
| 341 |
+
return self._process.returncode
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def stdin(self) -> abc.ByteSendStream | None:
|
| 345 |
+
return self._stdin
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def stdout(self) -> abc.ByteReceiveStream | None:
|
| 349 |
+
return self._stdout
|
| 350 |
+
|
| 351 |
+
@property
|
| 352 |
+
def stderr(self) -> abc.ByteReceiveStream | None:
|
| 353 |
+
return self._stderr
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class _ProcessPoolShutdownInstrument(trio.abc.Instrument):
|
| 357 |
+
def after_run(self) -> None:
|
| 358 |
+
super().after_run()
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar(
|
| 362 |
+
"current_default_worker_process_limiter"
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
async def _shutdown_process_pool(workers: set[abc.Process]) -> None:
|
| 367 |
+
try:
|
| 368 |
+
await trio.sleep(math.inf)
|
| 369 |
+
except trio.Cancelled:
|
| 370 |
+
for process in workers:
|
| 371 |
+
if process.returncode is None:
|
| 372 |
+
process.kill()
|
| 373 |
+
|
| 374 |
+
with CancelScope(shield=True):
|
| 375 |
+
for process in workers:
|
| 376 |
+
await process.aclose()
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
#
|
| 380 |
+
# Sockets and networking
|
| 381 |
+
#
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class _TrioSocketMixin(Generic[T_SockAddr]):
|
| 385 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 386 |
+
self._trio_socket = trio_socket
|
| 387 |
+
self._closed = False
|
| 388 |
+
|
| 389 |
+
def _check_closed(self) -> None:
|
| 390 |
+
if self._closed:
|
| 391 |
+
raise ClosedResourceError
|
| 392 |
+
if self._trio_socket.fileno() < 0:
|
| 393 |
+
raise BrokenResourceError
|
| 394 |
+
|
| 395 |
+
@property
|
| 396 |
+
def _raw_socket(self) -> socket.socket:
|
| 397 |
+
return self._trio_socket._sock # type: ignore[attr-defined]
|
| 398 |
+
|
| 399 |
+
async def aclose(self) -> None:
|
| 400 |
+
if self._trio_socket.fileno() >= 0:
|
| 401 |
+
self._closed = True
|
| 402 |
+
self._trio_socket.close()
|
| 403 |
+
|
| 404 |
+
def _convert_socket_error(self, exc: BaseException) -> NoReturn:
|
| 405 |
+
if isinstance(exc, trio.ClosedResourceError):
|
| 406 |
+
raise ClosedResourceError from exc
|
| 407 |
+
elif self._trio_socket.fileno() < 0 and self._closed:
|
| 408 |
+
raise ClosedResourceError from None
|
| 409 |
+
elif isinstance(exc, OSError):
|
| 410 |
+
raise BrokenResourceError from exc
|
| 411 |
+
else:
|
| 412 |
+
raise exc
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class SocketStream(_TrioSocketMixin, abc.SocketStream):
|
| 416 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 417 |
+
super().__init__(trio_socket)
|
| 418 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 419 |
+
self._send_guard = ResourceGuard("writing to")
|
| 420 |
+
|
| 421 |
+
async def receive(self, max_bytes: int = 65536) -> bytes:
|
| 422 |
+
with self._receive_guard:
|
| 423 |
+
try:
|
| 424 |
+
data = await self._trio_socket.recv(max_bytes)
|
| 425 |
+
except BaseException as exc:
|
| 426 |
+
self._convert_socket_error(exc)
|
| 427 |
+
|
| 428 |
+
if data:
|
| 429 |
+
return data
|
| 430 |
+
else:
|
| 431 |
+
raise EndOfStream
|
| 432 |
+
|
| 433 |
+
async def send(self, item: bytes) -> None:
|
| 434 |
+
with self._send_guard:
|
| 435 |
+
view = memoryview(item)
|
| 436 |
+
while view:
|
| 437 |
+
try:
|
| 438 |
+
bytes_sent = await self._trio_socket.send(view)
|
| 439 |
+
except BaseException as exc:
|
| 440 |
+
self._convert_socket_error(exc)
|
| 441 |
+
|
| 442 |
+
view = view[bytes_sent:]
|
| 443 |
+
|
| 444 |
+
async def send_eof(self) -> None:
|
| 445 |
+
self._trio_socket.shutdown(socket.SHUT_WR)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class UNIXSocketStream(SocketStream, abc.UNIXSocketStream):
|
| 449 |
+
async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
|
| 450 |
+
if not isinstance(msglen, int) or msglen < 0:
|
| 451 |
+
raise ValueError("msglen must be a non-negative integer")
|
| 452 |
+
if not isinstance(maxfds, int) or maxfds < 1:
|
| 453 |
+
raise ValueError("maxfds must be a positive integer")
|
| 454 |
+
|
| 455 |
+
fds = array.array("i")
|
| 456 |
+
await trio.lowlevel.checkpoint()
|
| 457 |
+
with self._receive_guard:
|
| 458 |
+
while True:
|
| 459 |
+
try:
|
| 460 |
+
message, ancdata, flags, addr = await self._trio_socket.recvmsg(
|
| 461 |
+
msglen, socket.CMSG_LEN(maxfds * fds.itemsize)
|
| 462 |
+
)
|
| 463 |
+
except BaseException as exc:
|
| 464 |
+
self._convert_socket_error(exc)
|
| 465 |
+
else:
|
| 466 |
+
if not message and not ancdata:
|
| 467 |
+
raise EndOfStream
|
| 468 |
+
|
| 469 |
+
break
|
| 470 |
+
|
| 471 |
+
for cmsg_level, cmsg_type, cmsg_data in ancdata:
|
| 472 |
+
if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS:
|
| 473 |
+
raise RuntimeError(
|
| 474 |
+
f"Received unexpected ancillary data; message = {message!r}, "
|
| 475 |
+
f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}"
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
|
| 479 |
+
|
| 480 |
+
return message, list(fds)
|
| 481 |
+
|
| 482 |
+
async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
|
| 483 |
+
if not message:
|
| 484 |
+
raise ValueError("message must not be empty")
|
| 485 |
+
if not fds:
|
| 486 |
+
raise ValueError("fds must not be empty")
|
| 487 |
+
|
| 488 |
+
filenos: list[int] = []
|
| 489 |
+
for fd in fds:
|
| 490 |
+
if isinstance(fd, int):
|
| 491 |
+
filenos.append(fd)
|
| 492 |
+
elif isinstance(fd, IOBase):
|
| 493 |
+
filenos.append(fd.fileno())
|
| 494 |
+
|
| 495 |
+
fdarray = array.array("i", filenos)
|
| 496 |
+
await trio.lowlevel.checkpoint()
|
| 497 |
+
with self._send_guard:
|
| 498 |
+
while True:
|
| 499 |
+
try:
|
| 500 |
+
await self._trio_socket.sendmsg(
|
| 501 |
+
[message],
|
| 502 |
+
[
|
| 503 |
+
(
|
| 504 |
+
socket.SOL_SOCKET,
|
| 505 |
+
socket.SCM_RIGHTS,
|
| 506 |
+
fdarray,
|
| 507 |
+
)
|
| 508 |
+
],
|
| 509 |
+
)
|
| 510 |
+
break
|
| 511 |
+
except BaseException as exc:
|
| 512 |
+
self._convert_socket_error(exc)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class TCPSocketListener(_TrioSocketMixin, abc.SocketListener):
|
| 516 |
+
def __init__(self, raw_socket: socket.socket):
|
| 517 |
+
super().__init__(trio.socket.from_stdlib_socket(raw_socket))
|
| 518 |
+
self._accept_guard = ResourceGuard("accepting connections from")
|
| 519 |
+
|
| 520 |
+
async def accept(self) -> SocketStream:
|
| 521 |
+
with self._accept_guard:
|
| 522 |
+
try:
|
| 523 |
+
trio_socket, _addr = await self._trio_socket.accept()
|
| 524 |
+
except BaseException as exc:
|
| 525 |
+
self._convert_socket_error(exc)
|
| 526 |
+
|
| 527 |
+
trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 528 |
+
return SocketStream(trio_socket)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener):
|
| 532 |
+
def __init__(self, raw_socket: socket.socket):
|
| 533 |
+
super().__init__(trio.socket.from_stdlib_socket(raw_socket))
|
| 534 |
+
self._accept_guard = ResourceGuard("accepting connections from")
|
| 535 |
+
|
| 536 |
+
async def accept(self) -> UNIXSocketStream:
|
| 537 |
+
with self._accept_guard:
|
| 538 |
+
try:
|
| 539 |
+
trio_socket, _addr = await self._trio_socket.accept()
|
| 540 |
+
except BaseException as exc:
|
| 541 |
+
self._convert_socket_error(exc)
|
| 542 |
+
|
| 543 |
+
return UNIXSocketStream(trio_socket)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket):
|
| 547 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 548 |
+
super().__init__(trio_socket)
|
| 549 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 550 |
+
self._send_guard = ResourceGuard("writing to")
|
| 551 |
+
|
| 552 |
+
async def receive(self) -> tuple[bytes, IPSockAddrType]:
|
| 553 |
+
with self._receive_guard:
|
| 554 |
+
try:
|
| 555 |
+
data, addr = await self._trio_socket.recvfrom(65536)
|
| 556 |
+
return data, convert_ipv6_sockaddr(addr)
|
| 557 |
+
except BaseException as exc:
|
| 558 |
+
self._convert_socket_error(exc)
|
| 559 |
+
|
| 560 |
+
async def send(self, item: UDPPacketType) -> None:
|
| 561 |
+
with self._send_guard:
|
| 562 |
+
try:
|
| 563 |
+
await self._trio_socket.sendto(*item)
|
| 564 |
+
except BaseException as exc:
|
| 565 |
+
self._convert_socket_error(exc)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket):
|
| 569 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 570 |
+
super().__init__(trio_socket)
|
| 571 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 572 |
+
self._send_guard = ResourceGuard("writing to")
|
| 573 |
+
|
| 574 |
+
async def receive(self) -> bytes:
|
| 575 |
+
with self._receive_guard:
|
| 576 |
+
try:
|
| 577 |
+
return await self._trio_socket.recv(65536)
|
| 578 |
+
except BaseException as exc:
|
| 579 |
+
self._convert_socket_error(exc)
|
| 580 |
+
|
| 581 |
+
async def send(self, item: bytes) -> None:
|
| 582 |
+
with self._send_guard:
|
| 583 |
+
try:
|
| 584 |
+
await self._trio_socket.send(item)
|
| 585 |
+
except BaseException as exc:
|
| 586 |
+
self._convert_socket_error(exc)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket):
|
| 590 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 591 |
+
super().__init__(trio_socket)
|
| 592 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 593 |
+
self._send_guard = ResourceGuard("writing to")
|
| 594 |
+
|
| 595 |
+
async def receive(self) -> UNIXDatagramPacketType:
|
| 596 |
+
with self._receive_guard:
|
| 597 |
+
try:
|
| 598 |
+
data, addr = await self._trio_socket.recvfrom(65536)
|
| 599 |
+
return data, addr
|
| 600 |
+
except BaseException as exc:
|
| 601 |
+
self._convert_socket_error(exc)
|
| 602 |
+
|
| 603 |
+
async def send(self, item: UNIXDatagramPacketType) -> None:
|
| 604 |
+
with self._send_guard:
|
| 605 |
+
try:
|
| 606 |
+
await self._trio_socket.sendto(*item)
|
| 607 |
+
except BaseException as exc:
|
| 608 |
+
self._convert_socket_error(exc)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
class ConnectedUNIXDatagramSocket(
|
| 612 |
+
_TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket
|
| 613 |
+
):
|
| 614 |
+
def __init__(self, trio_socket: TrioSocketType) -> None:
|
| 615 |
+
super().__init__(trio_socket)
|
| 616 |
+
self._receive_guard = ResourceGuard("reading from")
|
| 617 |
+
self._send_guard = ResourceGuard("writing to")
|
| 618 |
+
|
| 619 |
+
async def receive(self) -> bytes:
|
| 620 |
+
with self._receive_guard:
|
| 621 |
+
try:
|
| 622 |
+
return await self._trio_socket.recv(65536)
|
| 623 |
+
except BaseException as exc:
|
| 624 |
+
self._convert_socket_error(exc)
|
| 625 |
+
|
| 626 |
+
async def send(self, item: bytes) -> None:
|
| 627 |
+
with self._send_guard:
|
| 628 |
+
try:
|
| 629 |
+
await self._trio_socket.send(item)
|
| 630 |
+
except BaseException as exc:
|
| 631 |
+
self._convert_socket_error(exc)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
#
|
| 635 |
+
# Synchronization
|
| 636 |
+
#
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
class Event(BaseEvent):
|
| 640 |
+
def __new__(cls) -> Event:
|
| 641 |
+
return object.__new__(cls)
|
| 642 |
+
|
| 643 |
+
def __init__(self) -> None:
|
| 644 |
+
self.__original = trio.Event()
|
| 645 |
+
|
| 646 |
+
def is_set(self) -> bool:
|
| 647 |
+
return self.__original.is_set()
|
| 648 |
+
|
| 649 |
+
async def wait(self) -> None:
|
| 650 |
+
return await self.__original.wait()
|
| 651 |
+
|
| 652 |
+
def statistics(self) -> EventStatistics:
|
| 653 |
+
orig_statistics = self.__original.statistics()
|
| 654 |
+
return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting)
|
| 655 |
+
|
| 656 |
+
def set(self) -> None:
|
| 657 |
+
self.__original.set()
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
class Lock(BaseLock):
|
| 661 |
+
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
|
| 662 |
+
return object.__new__(cls)
|
| 663 |
+
|
| 664 |
+
def __init__(self, *, fast_acquire: bool = False) -> None:
|
| 665 |
+
self._fast_acquire = fast_acquire
|
| 666 |
+
self.__original = trio.Lock()
|
| 667 |
+
|
| 668 |
+
@staticmethod
|
| 669 |
+
def _convert_runtime_error_msg(exc: RuntimeError) -> None:
|
| 670 |
+
if exc.args == ("attempt to re-acquire an already held Lock",):
|
| 671 |
+
exc.args = ("Attempted to acquire an already held Lock",)
|
| 672 |
+
|
| 673 |
+
async def acquire(self) -> None:
|
| 674 |
+
if not self._fast_acquire:
|
| 675 |
+
try:
|
| 676 |
+
await self.__original.acquire()
|
| 677 |
+
except RuntimeError as exc:
|
| 678 |
+
self._convert_runtime_error_msg(exc)
|
| 679 |
+
raise
|
| 680 |
+
|
| 681 |
+
return
|
| 682 |
+
|
| 683 |
+
# This is the "fast path" where we don't let other tasks run
|
| 684 |
+
await trio.lowlevel.checkpoint_if_cancelled()
|
| 685 |
+
try:
|
| 686 |
+
self.__original.acquire_nowait()
|
| 687 |
+
except trio.WouldBlock:
|
| 688 |
+
await self.__original._lot.park()
|
| 689 |
+
except RuntimeError as exc:
|
| 690 |
+
self._convert_runtime_error_msg(exc)
|
| 691 |
+
raise
|
| 692 |
+
|
| 693 |
+
def acquire_nowait(self) -> None:
|
| 694 |
+
try:
|
| 695 |
+
self.__original.acquire_nowait()
|
| 696 |
+
except trio.WouldBlock:
|
| 697 |
+
raise WouldBlock from None
|
| 698 |
+
except RuntimeError as exc:
|
| 699 |
+
self._convert_runtime_error_msg(exc)
|
| 700 |
+
raise
|
| 701 |
+
|
| 702 |
+
def locked(self) -> bool:
|
| 703 |
+
return self.__original.locked()
|
| 704 |
+
|
| 705 |
+
def release(self) -> None:
|
| 706 |
+
self.__original.release()
|
| 707 |
+
|
| 708 |
+
def statistics(self) -> LockStatistics:
|
| 709 |
+
orig_statistics = self.__original.statistics()
|
| 710 |
+
owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None
|
| 711 |
+
return LockStatistics(
|
| 712 |
+
orig_statistics.locked, owner, orig_statistics.tasks_waiting
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
class Semaphore(BaseSemaphore):
|
| 717 |
+
def __new__(
|
| 718 |
+
cls,
|
| 719 |
+
initial_value: int,
|
| 720 |
+
*,
|
| 721 |
+
max_value: int | None = None,
|
| 722 |
+
fast_acquire: bool = False,
|
| 723 |
+
) -> Semaphore:
|
| 724 |
+
return object.__new__(cls)
|
| 725 |
+
|
| 726 |
+
def __init__(
|
| 727 |
+
self,
|
| 728 |
+
initial_value: int,
|
| 729 |
+
*,
|
| 730 |
+
max_value: int | None = None,
|
| 731 |
+
fast_acquire: bool = False,
|
| 732 |
+
) -> None:
|
| 733 |
+
super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
|
| 734 |
+
self.__original = trio.Semaphore(initial_value, max_value=max_value)
|
| 735 |
+
|
| 736 |
+
async def acquire(self) -> None:
|
| 737 |
+
if not self._fast_acquire:
|
| 738 |
+
await self.__original.acquire()
|
| 739 |
+
return
|
| 740 |
+
|
| 741 |
+
# This is the "fast path" where we don't let other tasks run
|
| 742 |
+
await trio.lowlevel.checkpoint_if_cancelled()
|
| 743 |
+
try:
|
| 744 |
+
self.__original.acquire_nowait()
|
| 745 |
+
except trio.WouldBlock:
|
| 746 |
+
await self.__original._lot.park()
|
| 747 |
+
|
| 748 |
+
def acquire_nowait(self) -> None:
|
| 749 |
+
try:
|
| 750 |
+
self.__original.acquire_nowait()
|
| 751 |
+
except trio.WouldBlock:
|
| 752 |
+
raise WouldBlock from None
|
| 753 |
+
|
| 754 |
+
@property
|
| 755 |
+
def max_value(self) -> int | None:
|
| 756 |
+
return self.__original.max_value
|
| 757 |
+
|
| 758 |
+
@property
|
| 759 |
+
def value(self) -> int:
|
| 760 |
+
return self.__original.value
|
| 761 |
+
|
| 762 |
+
def release(self) -> None:
|
| 763 |
+
self.__original.release()
|
| 764 |
+
|
| 765 |
+
def statistics(self) -> SemaphoreStatistics:
|
| 766 |
+
orig_statistics = self.__original.statistics()
|
| 767 |
+
return SemaphoreStatistics(orig_statistics.tasks_waiting)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
class CapacityLimiter(BaseCapacityLimiter):
|
| 771 |
+
def __new__(
|
| 772 |
+
cls,
|
| 773 |
+
total_tokens: float | None = None,
|
| 774 |
+
*,
|
| 775 |
+
original: trio.CapacityLimiter | None = None,
|
| 776 |
+
) -> CapacityLimiter:
|
| 777 |
+
return object.__new__(cls)
|
| 778 |
+
|
| 779 |
+
def __init__(
|
| 780 |
+
self,
|
| 781 |
+
total_tokens: float | None = None,
|
| 782 |
+
*,
|
| 783 |
+
original: trio.CapacityLimiter | None = None,
|
| 784 |
+
) -> None:
|
| 785 |
+
if original is not None:
|
| 786 |
+
self.__original = original
|
| 787 |
+
else:
|
| 788 |
+
assert total_tokens is not None
|
| 789 |
+
self.__original = trio.CapacityLimiter(total_tokens)
|
| 790 |
+
|
| 791 |
+
async def __aenter__(self) -> None:
|
| 792 |
+
return await self.__original.__aenter__()
|
| 793 |
+
|
| 794 |
+
async def __aexit__(
|
| 795 |
+
self,
|
| 796 |
+
exc_type: type[BaseException] | None,
|
| 797 |
+
exc_val: BaseException | None,
|
| 798 |
+
exc_tb: TracebackType | None,
|
| 799 |
+
) -> None:
|
| 800 |
+
await self.__original.__aexit__(exc_type, exc_val, exc_tb)
|
| 801 |
+
|
| 802 |
+
@property
|
| 803 |
+
def total_tokens(self) -> float:
|
| 804 |
+
return self.__original.total_tokens
|
| 805 |
+
|
| 806 |
+
@total_tokens.setter
|
| 807 |
+
def total_tokens(self, value: float) -> None:
|
| 808 |
+
self.__original.total_tokens = value
|
| 809 |
+
|
| 810 |
+
@property
|
| 811 |
+
def borrowed_tokens(self) -> int:
|
| 812 |
+
return self.__original.borrowed_tokens
|
| 813 |
+
|
| 814 |
+
@property
|
| 815 |
+
def available_tokens(self) -> float:
|
| 816 |
+
return self.__original.available_tokens
|
| 817 |
+
|
| 818 |
+
def acquire_nowait(self) -> None:
|
| 819 |
+
self.__original.acquire_nowait()
|
| 820 |
+
|
| 821 |
+
def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
|
| 822 |
+
self.__original.acquire_on_behalf_of_nowait(borrower)
|
| 823 |
+
|
| 824 |
+
async def acquire(self) -> None:
|
| 825 |
+
await self.__original.acquire()
|
| 826 |
+
|
| 827 |
+
async def acquire_on_behalf_of(self, borrower: object) -> None:
|
| 828 |
+
await self.__original.acquire_on_behalf_of(borrower)
|
| 829 |
+
|
| 830 |
+
def release(self) -> None:
|
| 831 |
+
return self.__original.release()
|
| 832 |
+
|
| 833 |
+
def release_on_behalf_of(self, borrower: object) -> None:
|
| 834 |
+
return self.__original.release_on_behalf_of(borrower)
|
| 835 |
+
|
| 836 |
+
def statistics(self) -> CapacityLimiterStatistics:
|
| 837 |
+
orig = self.__original.statistics()
|
| 838 |
+
return CapacityLimiterStatistics(
|
| 839 |
+
borrowed_tokens=orig.borrowed_tokens,
|
| 840 |
+
total_tokens=orig.total_tokens,
|
| 841 |
+
borrowers=tuple(orig.borrowers),
|
| 842 |
+
tasks_waiting=orig.tasks_waiting,
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper")
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
#
|
| 850 |
+
# Signal handling
|
| 851 |
+
#
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
class _SignalReceiver:
|
| 855 |
+
_iterator: AsyncIterator[int]
|
| 856 |
+
|
| 857 |
+
def __init__(self, signals: tuple[Signals, ...]):
|
| 858 |
+
self._signals = signals
|
| 859 |
+
|
| 860 |
+
def __enter__(self) -> _SignalReceiver:
|
| 861 |
+
self._cm = trio.open_signal_receiver(*self._signals)
|
| 862 |
+
self._iterator = self._cm.__enter__()
|
| 863 |
+
return self
|
| 864 |
+
|
| 865 |
+
def __exit__(
|
| 866 |
+
self,
|
| 867 |
+
exc_type: type[BaseException] | None,
|
| 868 |
+
exc_val: BaseException | None,
|
| 869 |
+
exc_tb: TracebackType | None,
|
| 870 |
+
) -> bool | None:
|
| 871 |
+
return self._cm.__exit__(exc_type, exc_val, exc_tb)
|
| 872 |
+
|
| 873 |
+
def __aiter__(self) -> _SignalReceiver:
|
| 874 |
+
return self
|
| 875 |
+
|
| 876 |
+
async def __anext__(self) -> Signals:
|
| 877 |
+
signum = await self._iterator.__anext__()
|
| 878 |
+
return Signals(signum)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
#
|
| 882 |
+
# Testing and debugging
|
| 883 |
+
#
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
class TestRunner(abc.TestRunner):
|
| 887 |
+
def __init__(self, **options: Any) -> None:
|
| 888 |
+
from queue import Queue
|
| 889 |
+
|
| 890 |
+
self._call_queue: Queue[Callable[[], object]] = Queue()
|
| 891 |
+
self._send_stream: MemoryObjectSendStream | None = None
|
| 892 |
+
self._options = options
|
| 893 |
+
|
| 894 |
+
def __exit__(
|
| 895 |
+
self,
|
| 896 |
+
exc_type: type[BaseException] | None,
|
| 897 |
+
exc_val: BaseException | None,
|
| 898 |
+
exc_tb: types.TracebackType | None,
|
| 899 |
+
) -> None:
|
| 900 |
+
if self._send_stream:
|
| 901 |
+
self._send_stream.close()
|
| 902 |
+
while self._send_stream is not None:
|
| 903 |
+
self._call_queue.get()()
|
| 904 |
+
|
| 905 |
+
async def _run_tests_and_fixtures(self) -> None:
|
| 906 |
+
self._send_stream, receive_stream = create_memory_object_stream(1)
|
| 907 |
+
with receive_stream:
|
| 908 |
+
async for coro, outcome_holder in receive_stream:
|
| 909 |
+
try:
|
| 910 |
+
retval = await coro
|
| 911 |
+
except BaseException as exc:
|
| 912 |
+
outcome_holder.append(Error(exc))
|
| 913 |
+
else:
|
| 914 |
+
outcome_holder.append(Value(retval))
|
| 915 |
+
|
| 916 |
+
def _main_task_finished(self, outcome: object) -> None:
|
| 917 |
+
self._send_stream = None
|
| 918 |
+
|
| 919 |
+
def _call_in_runner_task(
|
| 920 |
+
self,
|
| 921 |
+
func: Callable[P, Awaitable[T_Retval]],
|
| 922 |
+
*args: P.args,
|
| 923 |
+
**kwargs: P.kwargs,
|
| 924 |
+
) -> T_Retval:
|
| 925 |
+
if self._send_stream is None:
|
| 926 |
+
trio.lowlevel.start_guest_run(
|
| 927 |
+
self._run_tests_and_fixtures,
|
| 928 |
+
run_sync_soon_threadsafe=self._call_queue.put,
|
| 929 |
+
done_callback=self._main_task_finished,
|
| 930 |
+
**self._options,
|
| 931 |
+
)
|
| 932 |
+
while self._send_stream is None:
|
| 933 |
+
self._call_queue.get()()
|
| 934 |
+
|
| 935 |
+
outcome_holder: list[Outcome] = []
|
| 936 |
+
self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder))
|
| 937 |
+
while not outcome_holder:
|
| 938 |
+
self._call_queue.get()()
|
| 939 |
+
|
| 940 |
+
return outcome_holder[0].unwrap()
|
| 941 |
+
|
| 942 |
+
def run_asyncgen_fixture(
|
| 943 |
+
self,
|
| 944 |
+
fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]],
|
| 945 |
+
kwargs: dict[str, Any],
|
| 946 |
+
) -> Iterable[T_Retval]:
|
| 947 |
+
asyncgen = fixture_func(**kwargs)
|
| 948 |
+
fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None)
|
| 949 |
+
|
| 950 |
+
yield fixturevalue
|
| 951 |
+
|
| 952 |
+
try:
|
| 953 |
+
self._call_in_runner_task(asyncgen.asend, None)
|
| 954 |
+
except StopAsyncIteration:
|
| 955 |
+
pass
|
| 956 |
+
else:
|
| 957 |
+
self._call_in_runner_task(asyncgen.aclose)
|
| 958 |
+
raise RuntimeError("Async generator fixture did not stop")
|
| 959 |
+
|
| 960 |
+
def run_fixture(
|
| 961 |
+
self,
|
| 962 |
+
fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]],
|
| 963 |
+
kwargs: dict[str, Any],
|
| 964 |
+
) -> T_Retval:
|
| 965 |
+
return self._call_in_runner_task(fixture_func, **kwargs)
|
| 966 |
+
|
| 967 |
+
def run_test(
|
| 968 |
+
self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
|
| 969 |
+
) -> None:
|
| 970 |
+
self._call_in_runner_task(test_func, **kwargs)
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
class TrioTaskInfo(TaskInfo):
|
| 974 |
+
def __init__(self, task: trio.lowlevel.Task):
|
| 975 |
+
parent_id = None
|
| 976 |
+
if task.parent_nursery and task.parent_nursery.parent_task:
|
| 977 |
+
parent_id = id(task.parent_nursery.parent_task)
|
| 978 |
+
|
| 979 |
+
super().__init__(id(task), parent_id, task.name, task.coro)
|
| 980 |
+
self._task = weakref.proxy(task)
|
| 981 |
+
|
| 982 |
+
def has_pending_cancellation(self) -> bool:
|
| 983 |
+
try:
|
| 984 |
+
return self._task._cancel_status.effectively_cancelled
|
| 985 |
+
except ReferenceError:
|
| 986 |
+
# If the task is no longer around, it surely doesn't have a cancellation
|
| 987 |
+
# pending
|
| 988 |
+
return False
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
class TrioBackend(AsyncBackend):
|
| 992 |
+
@classmethod
|
| 993 |
+
def run(
|
| 994 |
+
cls,
|
| 995 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 996 |
+
args: tuple[Unpack[PosArgsT]],
|
| 997 |
+
kwargs: dict[str, Any],
|
| 998 |
+
options: dict[str, Any],
|
| 999 |
+
) -> T_Retval:
|
| 1000 |
+
return trio.run(func, *args)
|
| 1001 |
+
|
| 1002 |
+
@classmethod
|
| 1003 |
+
def current_token(cls) -> object:
|
| 1004 |
+
return trio.lowlevel.current_trio_token()
|
| 1005 |
+
|
| 1006 |
+
@classmethod
|
| 1007 |
+
def current_time(cls) -> float:
|
| 1008 |
+
return trio.current_time()
|
| 1009 |
+
|
| 1010 |
+
@classmethod
|
| 1011 |
+
def cancelled_exception_class(cls) -> type[BaseException]:
|
| 1012 |
+
return trio.Cancelled
|
| 1013 |
+
|
| 1014 |
+
@classmethod
|
| 1015 |
+
async def checkpoint(cls) -> None:
|
| 1016 |
+
await trio.lowlevel.checkpoint()
|
| 1017 |
+
|
| 1018 |
+
@classmethod
|
| 1019 |
+
async def checkpoint_if_cancelled(cls) -> None:
|
| 1020 |
+
await trio.lowlevel.checkpoint_if_cancelled()
|
| 1021 |
+
|
| 1022 |
+
@classmethod
|
| 1023 |
+
async def cancel_shielded_checkpoint(cls) -> None:
|
| 1024 |
+
await trio.lowlevel.cancel_shielded_checkpoint()
|
| 1025 |
+
|
| 1026 |
+
@classmethod
|
| 1027 |
+
async def sleep(cls, delay: float) -> None:
|
| 1028 |
+
await trio.sleep(delay)
|
| 1029 |
+
|
| 1030 |
+
@classmethod
|
| 1031 |
+
def create_cancel_scope(
|
| 1032 |
+
cls, *, deadline: float = math.inf, shield: bool = False
|
| 1033 |
+
) -> abc.CancelScope:
|
| 1034 |
+
return CancelScope(deadline=deadline, shield=shield)
|
| 1035 |
+
|
| 1036 |
+
@classmethod
|
| 1037 |
+
def current_effective_deadline(cls) -> float:
|
| 1038 |
+
return trio.current_effective_deadline()
|
| 1039 |
+
|
| 1040 |
+
@classmethod
|
| 1041 |
+
def create_task_group(cls) -> abc.TaskGroup:
|
| 1042 |
+
return TaskGroup()
|
| 1043 |
+
|
| 1044 |
+
@classmethod
|
| 1045 |
+
def create_event(cls) -> abc.Event:
|
| 1046 |
+
return Event()
|
| 1047 |
+
|
| 1048 |
+
@classmethod
|
| 1049 |
+
def create_lock(cls, *, fast_acquire: bool) -> Lock:
|
| 1050 |
+
return Lock(fast_acquire=fast_acquire)
|
| 1051 |
+
|
| 1052 |
+
@classmethod
|
| 1053 |
+
def create_semaphore(
|
| 1054 |
+
cls,
|
| 1055 |
+
initial_value: int,
|
| 1056 |
+
*,
|
| 1057 |
+
max_value: int | None = None,
|
| 1058 |
+
fast_acquire: bool = False,
|
| 1059 |
+
) -> abc.Semaphore:
|
| 1060 |
+
return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
|
| 1061 |
+
|
| 1062 |
+
@classmethod
|
| 1063 |
+
def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter:
|
| 1064 |
+
return CapacityLimiter(total_tokens)
|
| 1065 |
+
|
| 1066 |
+
@classmethod
|
| 1067 |
+
async def run_sync_in_worker_thread(
|
| 1068 |
+
cls,
|
| 1069 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 1070 |
+
args: tuple[Unpack[PosArgsT]],
|
| 1071 |
+
abandon_on_cancel: bool = False,
|
| 1072 |
+
limiter: abc.CapacityLimiter | None = None,
|
| 1073 |
+
) -> T_Retval:
|
| 1074 |
+
def wrapper() -> T_Retval:
|
| 1075 |
+
with claim_worker_thread(TrioBackend, token):
|
| 1076 |
+
return func(*args)
|
| 1077 |
+
|
| 1078 |
+
token = TrioBackend.current_token()
|
| 1079 |
+
return await run_sync(
|
| 1080 |
+
wrapper,
|
| 1081 |
+
abandon_on_cancel=abandon_on_cancel,
|
| 1082 |
+
limiter=cast(trio.CapacityLimiter, limiter),
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
@classmethod
|
| 1086 |
+
def check_cancelled(cls) -> None:
|
| 1087 |
+
trio.from_thread.check_cancelled()
|
| 1088 |
+
|
| 1089 |
+
@classmethod
|
| 1090 |
+
def run_async_from_thread(
|
| 1091 |
+
cls,
|
| 1092 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 1093 |
+
args: tuple[Unpack[PosArgsT]],
|
| 1094 |
+
token: object,
|
| 1095 |
+
) -> T_Retval:
|
| 1096 |
+
return trio.from_thread.run(func, *args)
|
| 1097 |
+
|
| 1098 |
+
@classmethod
|
| 1099 |
+
def run_sync_from_thread(
|
| 1100 |
+
cls,
|
| 1101 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 1102 |
+
args: tuple[Unpack[PosArgsT]],
|
| 1103 |
+
token: object,
|
| 1104 |
+
) -> T_Retval:
|
| 1105 |
+
return trio.from_thread.run_sync(func, *args)
|
| 1106 |
+
|
| 1107 |
+
@classmethod
|
| 1108 |
+
def create_blocking_portal(cls) -> abc.BlockingPortal:
|
| 1109 |
+
return BlockingPortal()
|
| 1110 |
+
|
| 1111 |
+
@classmethod
|
| 1112 |
+
async def open_process(
|
| 1113 |
+
cls,
|
| 1114 |
+
command: StrOrBytesPath | Sequence[StrOrBytesPath],
|
| 1115 |
+
*,
|
| 1116 |
+
stdin: int | IO[Any] | None,
|
| 1117 |
+
stdout: int | IO[Any] | None,
|
| 1118 |
+
stderr: int | IO[Any] | None,
|
| 1119 |
+
**kwargs: Any,
|
| 1120 |
+
) -> Process:
|
| 1121 |
+
def convert_item(item: StrOrBytesPath) -> str:
|
| 1122 |
+
str_or_bytes = os.fspath(item)
|
| 1123 |
+
if isinstance(str_or_bytes, str):
|
| 1124 |
+
return str_or_bytes
|
| 1125 |
+
else:
|
| 1126 |
+
return os.fsdecode(str_or_bytes)
|
| 1127 |
+
|
| 1128 |
+
if isinstance(command, (str, bytes, PathLike)):
|
| 1129 |
+
process = await trio.lowlevel.open_process(
|
| 1130 |
+
convert_item(command),
|
| 1131 |
+
stdin=stdin,
|
| 1132 |
+
stdout=stdout,
|
| 1133 |
+
stderr=stderr,
|
| 1134 |
+
shell=True,
|
| 1135 |
+
**kwargs,
|
| 1136 |
+
)
|
| 1137 |
+
else:
|
| 1138 |
+
process = await trio.lowlevel.open_process(
|
| 1139 |
+
[convert_item(item) for item in command],
|
| 1140 |
+
stdin=stdin,
|
| 1141 |
+
stdout=stdout,
|
| 1142 |
+
stderr=stderr,
|
| 1143 |
+
shell=False,
|
| 1144 |
+
**kwargs,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None
|
| 1148 |
+
stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None
|
| 1149 |
+
stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None
|
| 1150 |
+
return Process(process, stdin_stream, stdout_stream, stderr_stream)
|
| 1151 |
+
|
| 1152 |
+
@classmethod
|
| 1153 |
+
def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None:
|
| 1154 |
+
trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers)
|
| 1155 |
+
|
| 1156 |
+
@classmethod
|
| 1157 |
+
async def connect_tcp(
|
| 1158 |
+
cls, host: str, port: int, local_address: IPSockAddrType | None = None
|
| 1159 |
+
) -> SocketStream:
|
| 1160 |
+
family = socket.AF_INET6 if ":" in host else socket.AF_INET
|
| 1161 |
+
trio_socket = trio.socket.socket(family)
|
| 1162 |
+
trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 1163 |
+
if local_address:
|
| 1164 |
+
await trio_socket.bind(local_address)
|
| 1165 |
+
|
| 1166 |
+
try:
|
| 1167 |
+
await trio_socket.connect((host, port))
|
| 1168 |
+
except BaseException:
|
| 1169 |
+
trio_socket.close()
|
| 1170 |
+
raise
|
| 1171 |
+
|
| 1172 |
+
return SocketStream(trio_socket)
|
| 1173 |
+
|
| 1174 |
+
@classmethod
|
| 1175 |
+
async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream:
|
| 1176 |
+
trio_socket = trio.socket.socket(socket.AF_UNIX)
|
| 1177 |
+
try:
|
| 1178 |
+
await trio_socket.connect(path)
|
| 1179 |
+
except BaseException:
|
| 1180 |
+
trio_socket.close()
|
| 1181 |
+
raise
|
| 1182 |
+
|
| 1183 |
+
return UNIXSocketStream(trio_socket)
|
| 1184 |
+
|
| 1185 |
+
@classmethod
|
| 1186 |
+
def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener:
|
| 1187 |
+
return TCPSocketListener(sock)
|
| 1188 |
+
|
| 1189 |
+
@classmethod
|
| 1190 |
+
def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener:
|
| 1191 |
+
return UNIXSocketListener(sock)
|
| 1192 |
+
|
| 1193 |
+
@classmethod
|
| 1194 |
+
async def create_udp_socket(
|
| 1195 |
+
cls,
|
| 1196 |
+
family: socket.AddressFamily,
|
| 1197 |
+
local_address: IPSockAddrType | None,
|
| 1198 |
+
remote_address: IPSockAddrType | None,
|
| 1199 |
+
reuse_port: bool,
|
| 1200 |
+
) -> UDPSocket | ConnectedUDPSocket:
|
| 1201 |
+
trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM)
|
| 1202 |
+
|
| 1203 |
+
if reuse_port:
|
| 1204 |
+
trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
| 1205 |
+
|
| 1206 |
+
if local_address:
|
| 1207 |
+
await trio_socket.bind(local_address)
|
| 1208 |
+
|
| 1209 |
+
if remote_address:
|
| 1210 |
+
await trio_socket.connect(remote_address)
|
| 1211 |
+
return ConnectedUDPSocket(trio_socket)
|
| 1212 |
+
else:
|
| 1213 |
+
return UDPSocket(trio_socket)
|
| 1214 |
+
|
| 1215 |
+
@classmethod
|
| 1216 |
+
@overload
|
| 1217 |
+
async def create_unix_datagram_socket(
|
| 1218 |
+
cls, raw_socket: socket.socket, remote_path: None
|
| 1219 |
+
) -> abc.UNIXDatagramSocket: ...
|
| 1220 |
+
|
| 1221 |
+
@classmethod
|
| 1222 |
+
@overload
|
| 1223 |
+
async def create_unix_datagram_socket(
|
| 1224 |
+
cls, raw_socket: socket.socket, remote_path: str | bytes
|
| 1225 |
+
) -> abc.ConnectedUNIXDatagramSocket: ...
|
| 1226 |
+
|
| 1227 |
+
@classmethod
|
| 1228 |
+
async def create_unix_datagram_socket(
|
| 1229 |
+
cls, raw_socket: socket.socket, remote_path: str | bytes | None
|
| 1230 |
+
) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket:
|
| 1231 |
+
trio_socket = trio.socket.from_stdlib_socket(raw_socket)
|
| 1232 |
+
|
| 1233 |
+
if remote_path:
|
| 1234 |
+
await trio_socket.connect(remote_path)
|
| 1235 |
+
return ConnectedUNIXDatagramSocket(trio_socket)
|
| 1236 |
+
else:
|
| 1237 |
+
return UNIXDatagramSocket(trio_socket)
|
| 1238 |
+
|
| 1239 |
+
@classmethod
|
| 1240 |
+
async def getaddrinfo(
|
| 1241 |
+
cls,
|
| 1242 |
+
host: bytes | str | None,
|
| 1243 |
+
port: str | int | None,
|
| 1244 |
+
*,
|
| 1245 |
+
family: int | AddressFamily = 0,
|
| 1246 |
+
type: int | SocketKind = 0,
|
| 1247 |
+
proto: int = 0,
|
| 1248 |
+
flags: int = 0,
|
| 1249 |
+
) -> list[
|
| 1250 |
+
tuple[
|
| 1251 |
+
AddressFamily,
|
| 1252 |
+
SocketKind,
|
| 1253 |
+
int,
|
| 1254 |
+
str,
|
| 1255 |
+
tuple[str, int] | tuple[str, int, int, int],
|
| 1256 |
+
]
|
| 1257 |
+
]:
|
| 1258 |
+
return await trio.socket.getaddrinfo(host, port, family, type, proto, flags)
|
| 1259 |
+
|
| 1260 |
+
@classmethod
|
| 1261 |
+
async def getnameinfo(
|
| 1262 |
+
cls, sockaddr: IPSockAddrType, flags: int = 0
|
| 1263 |
+
) -> tuple[str, str]:
|
| 1264 |
+
return await trio.socket.getnameinfo(sockaddr, flags)
|
| 1265 |
+
|
| 1266 |
+
@classmethod
|
| 1267 |
+
async def wait_readable(cls, obj: HasFileno | int) -> None:
|
| 1268 |
+
try:
|
| 1269 |
+
await wait_readable(obj)
|
| 1270 |
+
except trio.ClosedResourceError as exc:
|
| 1271 |
+
raise ClosedResourceError().with_traceback(exc.__traceback__) from None
|
| 1272 |
+
except trio.BusyResourceError:
|
| 1273 |
+
raise BusyResourceError("reading from") from None
|
| 1274 |
+
|
| 1275 |
+
@classmethod
|
| 1276 |
+
async def wait_writable(cls, obj: HasFileno | int) -> None:
|
| 1277 |
+
try:
|
| 1278 |
+
await wait_writable(obj)
|
| 1279 |
+
except trio.ClosedResourceError as exc:
|
| 1280 |
+
raise ClosedResourceError().with_traceback(exc.__traceback__) from None
|
| 1281 |
+
except trio.BusyResourceError:
|
| 1282 |
+
raise BusyResourceError("writing to") from None
|
| 1283 |
+
|
| 1284 |
+
@classmethod
|
| 1285 |
+
def current_default_thread_limiter(cls) -> CapacityLimiter:
|
| 1286 |
+
try:
|
| 1287 |
+
return _capacity_limiter_wrapper.get()
|
| 1288 |
+
except LookupError:
|
| 1289 |
+
limiter = CapacityLimiter(
|
| 1290 |
+
original=trio.to_thread.current_default_thread_limiter()
|
| 1291 |
+
)
|
| 1292 |
+
_capacity_limiter_wrapper.set(limiter)
|
| 1293 |
+
return limiter
|
| 1294 |
+
|
| 1295 |
+
@classmethod
|
| 1296 |
+
def open_signal_receiver(
|
| 1297 |
+
cls, *signals: Signals
|
| 1298 |
+
) -> AbstractContextManager[AsyncIterator[Signals]]:
|
| 1299 |
+
return _SignalReceiver(signals)
|
| 1300 |
+
|
| 1301 |
+
@classmethod
|
| 1302 |
+
def get_current_task(cls) -> TaskInfo:
|
| 1303 |
+
task = current_task()
|
| 1304 |
+
return TrioTaskInfo(task)
|
| 1305 |
+
|
| 1306 |
+
@classmethod
|
| 1307 |
+
def get_running_tasks(cls) -> Sequence[TaskInfo]:
|
| 1308 |
+
root_task = current_root_task()
|
| 1309 |
+
assert root_task
|
| 1310 |
+
task_infos = [TrioTaskInfo(root_task)]
|
| 1311 |
+
nurseries = root_task.child_nurseries
|
| 1312 |
+
while nurseries:
|
| 1313 |
+
new_nurseries: list[trio.Nursery] = []
|
| 1314 |
+
for nursery in nurseries:
|
| 1315 |
+
for task in nursery.child_tasks:
|
| 1316 |
+
task_infos.append(TrioTaskInfo(task))
|
| 1317 |
+
new_nurseries.extend(task.child_nurseries)
|
| 1318 |
+
|
| 1319 |
+
nurseries = new_nurseries
|
| 1320 |
+
|
| 1321 |
+
return task_infos
|
| 1322 |
+
|
| 1323 |
+
@classmethod
|
| 1324 |
+
async def wait_all_tasks_blocked(cls) -> None:
|
| 1325 |
+
from trio.testing import wait_all_tasks_blocked
|
| 1326 |
+
|
| 1327 |
+
await wait_all_tasks_blocked()
|
| 1328 |
+
|
| 1329 |
+
@classmethod
|
| 1330 |
+
def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
|
| 1331 |
+
return TestRunner(**options)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
backend_class = TrioBackend
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__init__.py
ADDED
|
File without changes
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (165 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc
ADDED
|
Binary file (3.91 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_eventloop.cpython-310.pyc
ADDED
|
Binary file (4.77 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_exceptions.cpython-310.pyc
ADDED
|
Binary file (3.81 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_fileio.cpython-310.pyc
ADDED
|
Binary file (25 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_resources.cpython-310.pyc
ADDED
|
Binary file (744 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_signals.cpython-310.pyc
ADDED
|
Binary file (1.18 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_sockets.cpython-310.pyc
ADDED
|
Binary file (22.4 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_streams.cpython-310.pyc
ADDED
|
Binary file (1.98 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-310.pyc
ADDED
|
Binary file (7.42 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_synchronization.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_tasks.cpython-310.pyc
ADDED
|
Binary file (5.83 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_testing.cpython-310.pyc
ADDED
|
Binary file (2.9 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/_core/__pycache__/_typedattr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annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import socket
|
| 5 |
+
import threading
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector
|
| 8 |
+
from typing import TYPE_CHECKING, Any
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from _typeshed import FileDescriptorLike
|
| 12 |
+
|
| 13 |
+
_selector_lock = threading.Lock()
|
| 14 |
+
_selector: Selector | None = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Selector:
|
| 18 |
+
def __init__(self) -> None:
|
| 19 |
+
self._thread = threading.Thread(target=self.run, name="AnyIO socket selector")
|
| 20 |
+
self._selector = DefaultSelector()
|
| 21 |
+
self._send, self._receive = socket.socketpair()
|
| 22 |
+
self._send.setblocking(False)
|
| 23 |
+
self._receive.setblocking(False)
|
| 24 |
+
self._selector.register(self._receive, EVENT_READ)
|
| 25 |
+
self._closed = False
|
| 26 |
+
|
| 27 |
+
def start(self) -> None:
|
| 28 |
+
self._thread.start()
|
| 29 |
+
threading._register_atexit(self._stop) # type: ignore[attr-defined]
|
| 30 |
+
|
| 31 |
+
def _stop(self) -> None:
|
| 32 |
+
global _selector
|
| 33 |
+
self._closed = True
|
| 34 |
+
self._notify_self()
|
| 35 |
+
self._send.close()
|
| 36 |
+
self._thread.join()
|
| 37 |
+
self._selector.unregister(self._receive)
|
| 38 |
+
self._receive.close()
|
| 39 |
+
self._selector.close()
|
| 40 |
+
_selector = None
|
| 41 |
+
assert (
|
| 42 |
+
not self._selector.get_map()
|
| 43 |
+
), "selector still has registered file descriptors after shutdown"
|
| 44 |
+
|
| 45 |
+
def _notify_self(self) -> None:
|
| 46 |
+
try:
|
| 47 |
+
self._send.send(b"\x00")
|
| 48 |
+
except BlockingIOError:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None:
|
| 52 |
+
loop = asyncio.get_running_loop()
|
| 53 |
+
try:
|
| 54 |
+
key = self._selector.get_key(fd)
|
| 55 |
+
except KeyError:
|
| 56 |
+
self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)})
|
| 57 |
+
else:
|
| 58 |
+
if EVENT_READ in key.data:
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"this file descriptor is already registered for reading"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
key.data[EVENT_READ] = loop, callback
|
| 64 |
+
self._selector.modify(fd, key.events | EVENT_READ, key.data)
|
| 65 |
+
|
| 66 |
+
self._notify_self()
|
| 67 |
+
|
| 68 |
+
def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None:
|
| 69 |
+
loop = asyncio.get_running_loop()
|
| 70 |
+
try:
|
| 71 |
+
key = self._selector.get_key(fd)
|
| 72 |
+
except KeyError:
|
| 73 |
+
self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)})
|
| 74 |
+
else:
|
| 75 |
+
if EVENT_WRITE in key.data:
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"this file descriptor is already registered for writing"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
key.data[EVENT_WRITE] = loop, callback
|
| 81 |
+
self._selector.modify(fd, key.events | EVENT_WRITE, key.data)
|
| 82 |
+
|
| 83 |
+
self._notify_self()
|
| 84 |
+
|
| 85 |
+
def remove_reader(self, fd: FileDescriptorLike) -> bool:
|
| 86 |
+
try:
|
| 87 |
+
key = self._selector.get_key(fd)
|
| 88 |
+
except KeyError:
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
if new_events := key.events ^ EVENT_READ:
|
| 92 |
+
del key.data[EVENT_READ]
|
| 93 |
+
self._selector.modify(fd, new_events, key.data)
|
| 94 |
+
else:
|
| 95 |
+
self._selector.unregister(fd)
|
| 96 |
+
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
def remove_writer(self, fd: FileDescriptorLike) -> bool:
|
| 100 |
+
try:
|
| 101 |
+
key = self._selector.get_key(fd)
|
| 102 |
+
except KeyError:
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
if new_events := key.events ^ EVENT_WRITE:
|
| 106 |
+
del key.data[EVENT_WRITE]
|
| 107 |
+
self._selector.modify(fd, new_events, key.data)
|
| 108 |
+
else:
|
| 109 |
+
self._selector.unregister(fd)
|
| 110 |
+
|
| 111 |
+
return True
|
| 112 |
+
|
| 113 |
+
def run(self) -> None:
|
| 114 |
+
while not self._closed:
|
| 115 |
+
for key, events in self._selector.select():
|
| 116 |
+
if key.fileobj is self._receive:
|
| 117 |
+
try:
|
| 118 |
+
while self._receive.recv(4096):
|
| 119 |
+
pass
|
| 120 |
+
except BlockingIOError:
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
if events & EVENT_READ:
|
| 126 |
+
loop, callback = key.data[EVENT_READ]
|
| 127 |
+
self.remove_reader(key.fd)
|
| 128 |
+
try:
|
| 129 |
+
loop.call_soon_threadsafe(callback)
|
| 130 |
+
except RuntimeError:
|
| 131 |
+
pass # the loop was already closed
|
| 132 |
+
|
| 133 |
+
if events & EVENT_WRITE:
|
| 134 |
+
loop, callback = key.data[EVENT_WRITE]
|
| 135 |
+
self.remove_writer(key.fd)
|
| 136 |
+
try:
|
| 137 |
+
loop.call_soon_threadsafe(callback)
|
| 138 |
+
except RuntimeError:
|
| 139 |
+
pass # the loop was already closed
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_selector() -> Selector:
|
| 143 |
+
global _selector
|
| 144 |
+
|
| 145 |
+
with _selector_lock:
|
| 146 |
+
if _selector is None:
|
| 147 |
+
_selector = Selector()
|
| 148 |
+
_selector.start()
|
| 149 |
+
|
| 150 |
+
return _selector
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_eventloop.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 5 |
+
import threading
|
| 6 |
+
from collections.abc import Awaitable, Callable, Generator
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
from importlib import import_module
|
| 9 |
+
from typing import TYPE_CHECKING, Any, TypeVar
|
| 10 |
+
|
| 11 |
+
import sniffio
|
| 12 |
+
|
| 13 |
+
if sys.version_info >= (3, 11):
|
| 14 |
+
from typing import TypeVarTuple, Unpack
|
| 15 |
+
else:
|
| 16 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from ..abc import AsyncBackend
|
| 20 |
+
|
| 21 |
+
# This must be updated when new backends are introduced
|
| 22 |
+
BACKENDS = "asyncio", "trio"
|
| 23 |
+
|
| 24 |
+
T_Retval = TypeVar("T_Retval")
|
| 25 |
+
PosArgsT = TypeVarTuple("PosArgsT")
|
| 26 |
+
|
| 27 |
+
threadlocals = threading.local()
|
| 28 |
+
loaded_backends: dict[str, type[AsyncBackend]] = {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def run(
|
| 32 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 33 |
+
*args: Unpack[PosArgsT],
|
| 34 |
+
backend: str = "asyncio",
|
| 35 |
+
backend_options: dict[str, Any] | None = None,
|
| 36 |
+
) -> T_Retval:
|
| 37 |
+
"""
|
| 38 |
+
Run the given coroutine function in an asynchronous event loop.
|
| 39 |
+
|
| 40 |
+
The current thread must not be already running an event loop.
|
| 41 |
+
|
| 42 |
+
:param func: a coroutine function
|
| 43 |
+
:param args: positional arguments to ``func``
|
| 44 |
+
:param backend: name of the asynchronous event loop implementation – currently
|
| 45 |
+
either ``asyncio`` or ``trio``
|
| 46 |
+
:param backend_options: keyword arguments to call the backend ``run()``
|
| 47 |
+
implementation with (documented :ref:`here <backend options>`)
|
| 48 |
+
:return: the return value of the coroutine function
|
| 49 |
+
:raises RuntimeError: if an asynchronous event loop is already running in this
|
| 50 |
+
thread
|
| 51 |
+
:raises LookupError: if the named backend is not found
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
try:
|
| 55 |
+
asynclib_name = sniffio.current_async_library()
|
| 56 |
+
except sniffio.AsyncLibraryNotFoundError:
|
| 57 |
+
pass
|
| 58 |
+
else:
|
| 59 |
+
raise RuntimeError(f"Already running {asynclib_name} in this thread")
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
async_backend = get_async_backend(backend)
|
| 63 |
+
except ImportError as exc:
|
| 64 |
+
raise LookupError(f"No such backend: {backend}") from exc
|
| 65 |
+
|
| 66 |
+
token = None
|
| 67 |
+
if sniffio.current_async_library_cvar.get(None) is None:
|
| 68 |
+
# Since we're in control of the event loop, we can cache the name of the async
|
| 69 |
+
# library
|
| 70 |
+
token = sniffio.current_async_library_cvar.set(backend)
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
backend_options = backend_options or {}
|
| 74 |
+
return async_backend.run(func, args, {}, backend_options)
|
| 75 |
+
finally:
|
| 76 |
+
if token:
|
| 77 |
+
sniffio.current_async_library_cvar.reset(token)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
async def sleep(delay: float) -> None:
|
| 81 |
+
"""
|
| 82 |
+
Pause the current task for the specified duration.
|
| 83 |
+
|
| 84 |
+
:param delay: the duration, in seconds
|
| 85 |
+
|
| 86 |
+
"""
|
| 87 |
+
return await get_async_backend().sleep(delay)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
async def sleep_forever() -> None:
|
| 91 |
+
"""
|
| 92 |
+
Pause the current task until it's cancelled.
|
| 93 |
+
|
| 94 |
+
This is a shortcut for ``sleep(math.inf)``.
|
| 95 |
+
|
| 96 |
+
.. versionadded:: 3.1
|
| 97 |
+
|
| 98 |
+
"""
|
| 99 |
+
await sleep(math.inf)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def sleep_until(deadline: float) -> None:
|
| 103 |
+
"""
|
| 104 |
+
Pause the current task until the given time.
|
| 105 |
+
|
| 106 |
+
:param deadline: the absolute time to wake up at (according to the internal
|
| 107 |
+
monotonic clock of the event loop)
|
| 108 |
+
|
| 109 |
+
.. versionadded:: 3.1
|
| 110 |
+
|
| 111 |
+
"""
|
| 112 |
+
now = current_time()
|
| 113 |
+
await sleep(max(deadline - now, 0))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def current_time() -> float:
|
| 117 |
+
"""
|
| 118 |
+
Return the current value of the event loop's internal clock.
|
| 119 |
+
|
| 120 |
+
:return: the clock value (seconds)
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
return get_async_backend().current_time()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_all_backends() -> tuple[str, ...]:
|
| 127 |
+
"""Return a tuple of the names of all built-in backends."""
|
| 128 |
+
return BACKENDS
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def get_cancelled_exc_class() -> type[BaseException]:
|
| 132 |
+
"""Return the current async library's cancellation exception class."""
|
| 133 |
+
return get_async_backend().cancelled_exception_class()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
#
|
| 137 |
+
# Private API
|
| 138 |
+
#
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@contextmanager
|
| 142 |
+
def claim_worker_thread(
|
| 143 |
+
backend_class: type[AsyncBackend], token: object
|
| 144 |
+
) -> Generator[Any, None, None]:
|
| 145 |
+
threadlocals.current_async_backend = backend_class
|
| 146 |
+
threadlocals.current_token = token
|
| 147 |
+
try:
|
| 148 |
+
yield
|
| 149 |
+
finally:
|
| 150 |
+
del threadlocals.current_async_backend
|
| 151 |
+
del threadlocals.current_token
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]:
|
| 155 |
+
if asynclib_name is None:
|
| 156 |
+
asynclib_name = sniffio.current_async_library()
|
| 157 |
+
|
| 158 |
+
# We use our own dict instead of sys.modules to get the already imported back-end
|
| 159 |
+
# class because the appropriate modules in sys.modules could potentially be only
|
| 160 |
+
# partially initialized
|
| 161 |
+
try:
|
| 162 |
+
return loaded_backends[asynclib_name]
|
| 163 |
+
except KeyError:
|
| 164 |
+
module = import_module(f"anyio._backends._{asynclib_name}")
|
| 165 |
+
loaded_backends[asynclib_name] = module.backend_class
|
| 166 |
+
return module.backend_class
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_exceptions.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Generator
|
| 5 |
+
|
| 6 |
+
if sys.version_info < (3, 11):
|
| 7 |
+
from exceptiongroup import BaseExceptionGroup
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BrokenResourceError(Exception):
|
| 11 |
+
"""
|
| 12 |
+
Raised when trying to use a resource that has been rendered unusable due to external
|
| 13 |
+
causes (e.g. a send stream whose peer has disconnected).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class BrokenWorkerProcess(Exception):
|
| 18 |
+
"""
|
| 19 |
+
Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or
|
| 20 |
+
otherwise misbehaves.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BusyResourceError(Exception):
|
| 25 |
+
"""
|
| 26 |
+
Raised when two tasks are trying to read from or write to the same resource
|
| 27 |
+
concurrently.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, action: str):
|
| 31 |
+
super().__init__(f"Another task is already {action} this resource")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ClosedResourceError(Exception):
|
| 35 |
+
"""Raised when trying to use a resource that has been closed."""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DelimiterNotFound(Exception):
|
| 39 |
+
"""
|
| 40 |
+
Raised during
|
| 41 |
+
:meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the
|
| 42 |
+
maximum number of bytes has been read without the delimiter being found.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, max_bytes: int) -> None:
|
| 46 |
+
super().__init__(
|
| 47 |
+
f"The delimiter was not found among the first {max_bytes} bytes"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class EndOfStream(Exception):
|
| 52 |
+
"""
|
| 53 |
+
Raised when trying to read from a stream that has been closed from the other end.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class IncompleteRead(Exception):
|
| 58 |
+
"""
|
| 59 |
+
Raised during
|
| 60 |
+
:meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or
|
| 61 |
+
:meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the
|
| 62 |
+
connection is closed before the requested amount of bytes has been read.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
super().__init__(
|
| 67 |
+
"The stream was closed before the read operation could be completed"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class TypedAttributeLookupError(LookupError):
|
| 72 |
+
"""
|
| 73 |
+
Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute
|
| 74 |
+
is not found and no default value has been given.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class WouldBlock(Exception):
|
| 79 |
+
"""Raised by ``X_nowait`` functions if ``X()`` would block."""
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def iterate_exceptions(
|
| 83 |
+
exception: BaseException,
|
| 84 |
+
) -> Generator[BaseException, None, None]:
|
| 85 |
+
if isinstance(exception, BaseExceptionGroup):
|
| 86 |
+
for exc in exception.exceptions:
|
| 87 |
+
yield from iterate_exceptions(exc)
|
| 88 |
+
else:
|
| 89 |
+
yield exception
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_fileio.py
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import pathlib
|
| 5 |
+
import sys
|
| 6 |
+
from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from functools import partial
|
| 9 |
+
from os import PathLike
|
| 10 |
+
from typing import (
|
| 11 |
+
IO,
|
| 12 |
+
TYPE_CHECKING,
|
| 13 |
+
Any,
|
| 14 |
+
AnyStr,
|
| 15 |
+
Final,
|
| 16 |
+
Generic,
|
| 17 |
+
overload,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from .. import to_thread
|
| 21 |
+
from ..abc import AsyncResource
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer
|
| 25 |
+
else:
|
| 26 |
+
ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AsyncFile(AsyncResource, Generic[AnyStr]):
|
| 30 |
+
"""
|
| 31 |
+
An asynchronous file object.
|
| 32 |
+
|
| 33 |
+
This class wraps a standard file object and provides async friendly versions of the
|
| 34 |
+
following blocking methods (where available on the original file object):
|
| 35 |
+
|
| 36 |
+
* read
|
| 37 |
+
* read1
|
| 38 |
+
* readline
|
| 39 |
+
* readlines
|
| 40 |
+
* readinto
|
| 41 |
+
* readinto1
|
| 42 |
+
* write
|
| 43 |
+
* writelines
|
| 44 |
+
* truncate
|
| 45 |
+
* seek
|
| 46 |
+
* tell
|
| 47 |
+
* flush
|
| 48 |
+
|
| 49 |
+
All other methods are directly passed through.
|
| 50 |
+
|
| 51 |
+
This class supports the asynchronous context manager protocol which closes the
|
| 52 |
+
underlying file at the end of the context block.
|
| 53 |
+
|
| 54 |
+
This class also supports asynchronous iteration::
|
| 55 |
+
|
| 56 |
+
async with await open_file(...) as f:
|
| 57 |
+
async for line in f:
|
| 58 |
+
print(line)
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(self, fp: IO[AnyStr]) -> None:
|
| 62 |
+
self._fp: Any = fp
|
| 63 |
+
|
| 64 |
+
def __getattr__(self, name: str) -> object:
|
| 65 |
+
return getattr(self._fp, name)
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def wrapped(self) -> IO[AnyStr]:
|
| 69 |
+
"""The wrapped file object."""
|
| 70 |
+
return self._fp
|
| 71 |
+
|
| 72 |
+
async def __aiter__(self) -> AsyncIterator[AnyStr]:
|
| 73 |
+
while True:
|
| 74 |
+
line = await self.readline()
|
| 75 |
+
if line:
|
| 76 |
+
yield line
|
| 77 |
+
else:
|
| 78 |
+
break
|
| 79 |
+
|
| 80 |
+
async def aclose(self) -> None:
|
| 81 |
+
return await to_thread.run_sync(self._fp.close)
|
| 82 |
+
|
| 83 |
+
async def read(self, size: int = -1) -> AnyStr:
|
| 84 |
+
return await to_thread.run_sync(self._fp.read, size)
|
| 85 |
+
|
| 86 |
+
async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes:
|
| 87 |
+
return await to_thread.run_sync(self._fp.read1, size)
|
| 88 |
+
|
| 89 |
+
async def readline(self) -> AnyStr:
|
| 90 |
+
return await to_thread.run_sync(self._fp.readline)
|
| 91 |
+
|
| 92 |
+
async def readlines(self) -> list[AnyStr]:
|
| 93 |
+
return await to_thread.run_sync(self._fp.readlines)
|
| 94 |
+
|
| 95 |
+
async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int:
|
| 96 |
+
return await to_thread.run_sync(self._fp.readinto, b)
|
| 97 |
+
|
| 98 |
+
async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int:
|
| 99 |
+
return await to_thread.run_sync(self._fp.readinto1, b)
|
| 100 |
+
|
| 101 |
+
@overload
|
| 102 |
+
async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ...
|
| 103 |
+
|
| 104 |
+
@overload
|
| 105 |
+
async def write(self: AsyncFile[str], b: str) -> int: ...
|
| 106 |
+
|
| 107 |
+
async def write(self, b: ReadableBuffer | str) -> int:
|
| 108 |
+
return await to_thread.run_sync(self._fp.write, b)
|
| 109 |
+
|
| 110 |
+
@overload
|
| 111 |
+
async def writelines(
|
| 112 |
+
self: AsyncFile[bytes], lines: Iterable[ReadableBuffer]
|
| 113 |
+
) -> None: ...
|
| 114 |
+
|
| 115 |
+
@overload
|
| 116 |
+
async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ...
|
| 117 |
+
|
| 118 |
+
async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None:
|
| 119 |
+
return await to_thread.run_sync(self._fp.writelines, lines)
|
| 120 |
+
|
| 121 |
+
async def truncate(self, size: int | None = None) -> int:
|
| 122 |
+
return await to_thread.run_sync(self._fp.truncate, size)
|
| 123 |
+
|
| 124 |
+
async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int:
|
| 125 |
+
return await to_thread.run_sync(self._fp.seek, offset, whence)
|
| 126 |
+
|
| 127 |
+
async def tell(self) -> int:
|
| 128 |
+
return await to_thread.run_sync(self._fp.tell)
|
| 129 |
+
|
| 130 |
+
async def flush(self) -> None:
|
| 131 |
+
return await to_thread.run_sync(self._fp.flush)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@overload
|
| 135 |
+
async def open_file(
|
| 136 |
+
file: str | PathLike[str] | int,
|
| 137 |
+
mode: OpenBinaryMode,
|
| 138 |
+
buffering: int = ...,
|
| 139 |
+
encoding: str | None = ...,
|
| 140 |
+
errors: str | None = ...,
|
| 141 |
+
newline: str | None = ...,
|
| 142 |
+
closefd: bool = ...,
|
| 143 |
+
opener: Callable[[str, int], int] | None = ...,
|
| 144 |
+
) -> AsyncFile[bytes]: ...
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@overload
|
| 148 |
+
async def open_file(
|
| 149 |
+
file: str | PathLike[str] | int,
|
| 150 |
+
mode: OpenTextMode = ...,
|
| 151 |
+
buffering: int = ...,
|
| 152 |
+
encoding: str | None = ...,
|
| 153 |
+
errors: str | None = ...,
|
| 154 |
+
newline: str | None = ...,
|
| 155 |
+
closefd: bool = ...,
|
| 156 |
+
opener: Callable[[str, int], int] | None = ...,
|
| 157 |
+
) -> AsyncFile[str]: ...
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
async def open_file(
|
| 161 |
+
file: str | PathLike[str] | int,
|
| 162 |
+
mode: str = "r",
|
| 163 |
+
buffering: int = -1,
|
| 164 |
+
encoding: str | None = None,
|
| 165 |
+
errors: str | None = None,
|
| 166 |
+
newline: str | None = None,
|
| 167 |
+
closefd: bool = True,
|
| 168 |
+
opener: Callable[[str, int], int] | None = None,
|
| 169 |
+
) -> AsyncFile[Any]:
|
| 170 |
+
"""
|
| 171 |
+
Open a file asynchronously.
|
| 172 |
+
|
| 173 |
+
The arguments are exactly the same as for the builtin :func:`open`.
|
| 174 |
+
|
| 175 |
+
:return: an asynchronous file object
|
| 176 |
+
|
| 177 |
+
"""
|
| 178 |
+
fp = await to_thread.run_sync(
|
| 179 |
+
open, file, mode, buffering, encoding, errors, newline, closefd, opener
|
| 180 |
+
)
|
| 181 |
+
return AsyncFile(fp)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]:
|
| 185 |
+
"""
|
| 186 |
+
Wrap an existing file as an asynchronous file.
|
| 187 |
+
|
| 188 |
+
:param file: an existing file-like object
|
| 189 |
+
:return: an asynchronous file object
|
| 190 |
+
|
| 191 |
+
"""
|
| 192 |
+
return AsyncFile(file)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@dataclass(eq=False)
|
| 196 |
+
class _PathIterator(AsyncIterator["Path"]):
|
| 197 |
+
iterator: Iterator[PathLike[str]]
|
| 198 |
+
|
| 199 |
+
async def __anext__(self) -> Path:
|
| 200 |
+
nextval = await to_thread.run_sync(
|
| 201 |
+
next, self.iterator, None, abandon_on_cancel=True
|
| 202 |
+
)
|
| 203 |
+
if nextval is None:
|
| 204 |
+
raise StopAsyncIteration from None
|
| 205 |
+
|
| 206 |
+
return Path(nextval)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class Path:
|
| 210 |
+
"""
|
| 211 |
+
An asynchronous version of :class:`pathlib.Path`.
|
| 212 |
+
|
| 213 |
+
This class cannot be substituted for :class:`pathlib.Path` or
|
| 214 |
+
:class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike`
|
| 215 |
+
interface.
|
| 216 |
+
|
| 217 |
+
It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for
|
| 218 |
+
the deprecated :meth:`~pathlib.Path.link_to` method.
|
| 219 |
+
|
| 220 |
+
Some methods may be unavailable or have limited functionality, based on the Python
|
| 221 |
+
version:
|
| 222 |
+
|
| 223 |
+
* :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later)
|
| 224 |
+
* :meth:`~pathlib.Path.full_match` (available on Python 3.13 or later)
|
| 225 |
+
* :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later)
|
| 226 |
+
* :meth:`~pathlib.Path.match` (the ``case_sensitive`` paramater is only available on
|
| 227 |
+
Python 3.13 or later)
|
| 228 |
+
* :meth:`~pathlib.Path.relative_to` (the ``walk_up`` parameter is only available on
|
| 229 |
+
Python 3.12 or later)
|
| 230 |
+
* :meth:`~pathlib.Path.walk` (available on Python 3.12 or later)
|
| 231 |
+
|
| 232 |
+
Any methods that do disk I/O need to be awaited on. These methods are:
|
| 233 |
+
|
| 234 |
+
* :meth:`~pathlib.Path.absolute`
|
| 235 |
+
* :meth:`~pathlib.Path.chmod`
|
| 236 |
+
* :meth:`~pathlib.Path.cwd`
|
| 237 |
+
* :meth:`~pathlib.Path.exists`
|
| 238 |
+
* :meth:`~pathlib.Path.expanduser`
|
| 239 |
+
* :meth:`~pathlib.Path.group`
|
| 240 |
+
* :meth:`~pathlib.Path.hardlink_to`
|
| 241 |
+
* :meth:`~pathlib.Path.home`
|
| 242 |
+
* :meth:`~pathlib.Path.is_block_device`
|
| 243 |
+
* :meth:`~pathlib.Path.is_char_device`
|
| 244 |
+
* :meth:`~pathlib.Path.is_dir`
|
| 245 |
+
* :meth:`~pathlib.Path.is_fifo`
|
| 246 |
+
* :meth:`~pathlib.Path.is_file`
|
| 247 |
+
* :meth:`~pathlib.Path.is_junction`
|
| 248 |
+
* :meth:`~pathlib.Path.is_mount`
|
| 249 |
+
* :meth:`~pathlib.Path.is_socket`
|
| 250 |
+
* :meth:`~pathlib.Path.is_symlink`
|
| 251 |
+
* :meth:`~pathlib.Path.lchmod`
|
| 252 |
+
* :meth:`~pathlib.Path.lstat`
|
| 253 |
+
* :meth:`~pathlib.Path.mkdir`
|
| 254 |
+
* :meth:`~pathlib.Path.open`
|
| 255 |
+
* :meth:`~pathlib.Path.owner`
|
| 256 |
+
* :meth:`~pathlib.Path.read_bytes`
|
| 257 |
+
* :meth:`~pathlib.Path.read_text`
|
| 258 |
+
* :meth:`~pathlib.Path.readlink`
|
| 259 |
+
* :meth:`~pathlib.Path.rename`
|
| 260 |
+
* :meth:`~pathlib.Path.replace`
|
| 261 |
+
* :meth:`~pathlib.Path.resolve`
|
| 262 |
+
* :meth:`~pathlib.Path.rmdir`
|
| 263 |
+
* :meth:`~pathlib.Path.samefile`
|
| 264 |
+
* :meth:`~pathlib.Path.stat`
|
| 265 |
+
* :meth:`~pathlib.Path.symlink_to`
|
| 266 |
+
* :meth:`~pathlib.Path.touch`
|
| 267 |
+
* :meth:`~pathlib.Path.unlink`
|
| 268 |
+
* :meth:`~pathlib.Path.walk`
|
| 269 |
+
* :meth:`~pathlib.Path.write_bytes`
|
| 270 |
+
* :meth:`~pathlib.Path.write_text`
|
| 271 |
+
|
| 272 |
+
Additionally, the following methods return an async iterator yielding
|
| 273 |
+
:class:`~.Path` objects:
|
| 274 |
+
|
| 275 |
+
* :meth:`~pathlib.Path.glob`
|
| 276 |
+
* :meth:`~pathlib.Path.iterdir`
|
| 277 |
+
* :meth:`~pathlib.Path.rglob`
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
__slots__ = "_path", "__weakref__"
|
| 281 |
+
|
| 282 |
+
__weakref__: Any
|
| 283 |
+
|
| 284 |
+
def __init__(self, *args: str | PathLike[str]) -> None:
|
| 285 |
+
self._path: Final[pathlib.Path] = pathlib.Path(*args)
|
| 286 |
+
|
| 287 |
+
def __fspath__(self) -> str:
|
| 288 |
+
return self._path.__fspath__()
|
| 289 |
+
|
| 290 |
+
def __str__(self) -> str:
|
| 291 |
+
return self._path.__str__()
|
| 292 |
+
|
| 293 |
+
def __repr__(self) -> str:
|
| 294 |
+
return f"{self.__class__.__name__}({self.as_posix()!r})"
|
| 295 |
+
|
| 296 |
+
def __bytes__(self) -> bytes:
|
| 297 |
+
return self._path.__bytes__()
|
| 298 |
+
|
| 299 |
+
def __hash__(self) -> int:
|
| 300 |
+
return self._path.__hash__()
|
| 301 |
+
|
| 302 |
+
def __eq__(self, other: object) -> bool:
|
| 303 |
+
target = other._path if isinstance(other, Path) else other
|
| 304 |
+
return self._path.__eq__(target)
|
| 305 |
+
|
| 306 |
+
def __lt__(self, other: pathlib.PurePath | Path) -> bool:
|
| 307 |
+
target = other._path if isinstance(other, Path) else other
|
| 308 |
+
return self._path.__lt__(target)
|
| 309 |
+
|
| 310 |
+
def __le__(self, other: pathlib.PurePath | Path) -> bool:
|
| 311 |
+
target = other._path if isinstance(other, Path) else other
|
| 312 |
+
return self._path.__le__(target)
|
| 313 |
+
|
| 314 |
+
def __gt__(self, other: pathlib.PurePath | Path) -> bool:
|
| 315 |
+
target = other._path if isinstance(other, Path) else other
|
| 316 |
+
return self._path.__gt__(target)
|
| 317 |
+
|
| 318 |
+
def __ge__(self, other: pathlib.PurePath | Path) -> bool:
|
| 319 |
+
target = other._path if isinstance(other, Path) else other
|
| 320 |
+
return self._path.__ge__(target)
|
| 321 |
+
|
| 322 |
+
def __truediv__(self, other: str | PathLike[str]) -> Path:
|
| 323 |
+
return Path(self._path / other)
|
| 324 |
+
|
| 325 |
+
def __rtruediv__(self, other: str | PathLike[str]) -> Path:
|
| 326 |
+
return Path(other) / self
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def parts(self) -> tuple[str, ...]:
|
| 330 |
+
return self._path.parts
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def drive(self) -> str:
|
| 334 |
+
return self._path.drive
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def root(self) -> str:
|
| 338 |
+
return self._path.root
|
| 339 |
+
|
| 340 |
+
@property
|
| 341 |
+
def anchor(self) -> str:
|
| 342 |
+
return self._path.anchor
|
| 343 |
+
|
| 344 |
+
@property
|
| 345 |
+
def parents(self) -> Sequence[Path]:
|
| 346 |
+
return tuple(Path(p) for p in self._path.parents)
|
| 347 |
+
|
| 348 |
+
@property
|
| 349 |
+
def parent(self) -> Path:
|
| 350 |
+
return Path(self._path.parent)
|
| 351 |
+
|
| 352 |
+
@property
|
| 353 |
+
def name(self) -> str:
|
| 354 |
+
return self._path.name
|
| 355 |
+
|
| 356 |
+
@property
|
| 357 |
+
def suffix(self) -> str:
|
| 358 |
+
return self._path.suffix
|
| 359 |
+
|
| 360 |
+
@property
|
| 361 |
+
def suffixes(self) -> list[str]:
|
| 362 |
+
return self._path.suffixes
|
| 363 |
+
|
| 364 |
+
@property
|
| 365 |
+
def stem(self) -> str:
|
| 366 |
+
return self._path.stem
|
| 367 |
+
|
| 368 |
+
async def absolute(self) -> Path:
|
| 369 |
+
path = await to_thread.run_sync(self._path.absolute)
|
| 370 |
+
return Path(path)
|
| 371 |
+
|
| 372 |
+
def as_posix(self) -> str:
|
| 373 |
+
return self._path.as_posix()
|
| 374 |
+
|
| 375 |
+
def as_uri(self) -> str:
|
| 376 |
+
return self._path.as_uri()
|
| 377 |
+
|
| 378 |
+
if sys.version_info >= (3, 13):
|
| 379 |
+
parser = pathlib.Path.parser
|
| 380 |
+
|
| 381 |
+
@classmethod
|
| 382 |
+
def from_uri(cls, uri: str) -> Path:
|
| 383 |
+
return Path(pathlib.Path.from_uri(uri))
|
| 384 |
+
|
| 385 |
+
def full_match(
|
| 386 |
+
self, path_pattern: str, *, case_sensitive: bool | None = None
|
| 387 |
+
) -> bool:
|
| 388 |
+
return self._path.full_match(path_pattern, case_sensitive=case_sensitive)
|
| 389 |
+
|
| 390 |
+
def match(
|
| 391 |
+
self, path_pattern: str, *, case_sensitive: bool | None = None
|
| 392 |
+
) -> bool:
|
| 393 |
+
return self._path.match(path_pattern, case_sensitive=case_sensitive)
|
| 394 |
+
else:
|
| 395 |
+
|
| 396 |
+
def match(self, path_pattern: str) -> bool:
|
| 397 |
+
return self._path.match(path_pattern)
|
| 398 |
+
|
| 399 |
+
def is_relative_to(self, other: str | PathLike[str]) -> bool:
|
| 400 |
+
try:
|
| 401 |
+
self.relative_to(other)
|
| 402 |
+
return True
|
| 403 |
+
except ValueError:
|
| 404 |
+
return False
|
| 405 |
+
|
| 406 |
+
async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None:
|
| 407 |
+
func = partial(os.chmod, follow_symlinks=follow_symlinks)
|
| 408 |
+
return await to_thread.run_sync(func, self._path, mode)
|
| 409 |
+
|
| 410 |
+
@classmethod
|
| 411 |
+
async def cwd(cls) -> Path:
|
| 412 |
+
path = await to_thread.run_sync(pathlib.Path.cwd)
|
| 413 |
+
return cls(path)
|
| 414 |
+
|
| 415 |
+
async def exists(self) -> bool:
|
| 416 |
+
return await to_thread.run_sync(self._path.exists, abandon_on_cancel=True)
|
| 417 |
+
|
| 418 |
+
async def expanduser(self) -> Path:
|
| 419 |
+
return Path(
|
| 420 |
+
await to_thread.run_sync(self._path.expanduser, abandon_on_cancel=True)
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
def glob(self, pattern: str) -> AsyncIterator[Path]:
|
| 424 |
+
gen = self._path.glob(pattern)
|
| 425 |
+
return _PathIterator(gen)
|
| 426 |
+
|
| 427 |
+
async def group(self) -> str:
|
| 428 |
+
return await to_thread.run_sync(self._path.group, abandon_on_cancel=True)
|
| 429 |
+
|
| 430 |
+
async def hardlink_to(
|
| 431 |
+
self, target: str | bytes | PathLike[str] | PathLike[bytes]
|
| 432 |
+
) -> None:
|
| 433 |
+
if isinstance(target, Path):
|
| 434 |
+
target = target._path
|
| 435 |
+
|
| 436 |
+
await to_thread.run_sync(os.link, target, self)
|
| 437 |
+
|
| 438 |
+
@classmethod
|
| 439 |
+
async def home(cls) -> Path:
|
| 440 |
+
home_path = await to_thread.run_sync(pathlib.Path.home)
|
| 441 |
+
return cls(home_path)
|
| 442 |
+
|
| 443 |
+
def is_absolute(self) -> bool:
|
| 444 |
+
return self._path.is_absolute()
|
| 445 |
+
|
| 446 |
+
async def is_block_device(self) -> bool:
|
| 447 |
+
return await to_thread.run_sync(
|
| 448 |
+
self._path.is_block_device, abandon_on_cancel=True
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
async def is_char_device(self) -> bool:
|
| 452 |
+
return await to_thread.run_sync(
|
| 453 |
+
self._path.is_char_device, abandon_on_cancel=True
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
async def is_dir(self) -> bool:
|
| 457 |
+
return await to_thread.run_sync(self._path.is_dir, abandon_on_cancel=True)
|
| 458 |
+
|
| 459 |
+
async def is_fifo(self) -> bool:
|
| 460 |
+
return await to_thread.run_sync(self._path.is_fifo, abandon_on_cancel=True)
|
| 461 |
+
|
| 462 |
+
async def is_file(self) -> bool:
|
| 463 |
+
return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True)
|
| 464 |
+
|
| 465 |
+
if sys.version_info >= (3, 12):
|
| 466 |
+
|
| 467 |
+
async def is_junction(self) -> bool:
|
| 468 |
+
return await to_thread.run_sync(self._path.is_junction)
|
| 469 |
+
|
| 470 |
+
async def is_mount(self) -> bool:
|
| 471 |
+
return await to_thread.run_sync(
|
| 472 |
+
os.path.ismount, self._path, abandon_on_cancel=True
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
def is_reserved(self) -> bool:
|
| 476 |
+
return self._path.is_reserved()
|
| 477 |
+
|
| 478 |
+
async def is_socket(self) -> bool:
|
| 479 |
+
return await to_thread.run_sync(self._path.is_socket, abandon_on_cancel=True)
|
| 480 |
+
|
| 481 |
+
async def is_symlink(self) -> bool:
|
| 482 |
+
return await to_thread.run_sync(self._path.is_symlink, abandon_on_cancel=True)
|
| 483 |
+
|
| 484 |
+
def iterdir(self) -> AsyncIterator[Path]:
|
| 485 |
+
gen = self._path.iterdir()
|
| 486 |
+
return _PathIterator(gen)
|
| 487 |
+
|
| 488 |
+
def joinpath(self, *args: str | PathLike[str]) -> Path:
|
| 489 |
+
return Path(self._path.joinpath(*args))
|
| 490 |
+
|
| 491 |
+
async def lchmod(self, mode: int) -> None:
|
| 492 |
+
await to_thread.run_sync(self._path.lchmod, mode)
|
| 493 |
+
|
| 494 |
+
async def lstat(self) -> os.stat_result:
|
| 495 |
+
return await to_thread.run_sync(self._path.lstat, abandon_on_cancel=True)
|
| 496 |
+
|
| 497 |
+
async def mkdir(
|
| 498 |
+
self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False
|
| 499 |
+
) -> None:
|
| 500 |
+
await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok)
|
| 501 |
+
|
| 502 |
+
@overload
|
| 503 |
+
async def open(
|
| 504 |
+
self,
|
| 505 |
+
mode: OpenBinaryMode,
|
| 506 |
+
buffering: int = ...,
|
| 507 |
+
encoding: str | None = ...,
|
| 508 |
+
errors: str | None = ...,
|
| 509 |
+
newline: str | None = ...,
|
| 510 |
+
) -> AsyncFile[bytes]: ...
|
| 511 |
+
|
| 512 |
+
@overload
|
| 513 |
+
async def open(
|
| 514 |
+
self,
|
| 515 |
+
mode: OpenTextMode = ...,
|
| 516 |
+
buffering: int = ...,
|
| 517 |
+
encoding: str | None = ...,
|
| 518 |
+
errors: str | None = ...,
|
| 519 |
+
newline: str | None = ...,
|
| 520 |
+
) -> AsyncFile[str]: ...
|
| 521 |
+
|
| 522 |
+
async def open(
|
| 523 |
+
self,
|
| 524 |
+
mode: str = "r",
|
| 525 |
+
buffering: int = -1,
|
| 526 |
+
encoding: str | None = None,
|
| 527 |
+
errors: str | None = None,
|
| 528 |
+
newline: str | None = None,
|
| 529 |
+
) -> AsyncFile[Any]:
|
| 530 |
+
fp = await to_thread.run_sync(
|
| 531 |
+
self._path.open, mode, buffering, encoding, errors, newline
|
| 532 |
+
)
|
| 533 |
+
return AsyncFile(fp)
|
| 534 |
+
|
| 535 |
+
async def owner(self) -> str:
|
| 536 |
+
return await to_thread.run_sync(self._path.owner, abandon_on_cancel=True)
|
| 537 |
+
|
| 538 |
+
async def read_bytes(self) -> bytes:
|
| 539 |
+
return await to_thread.run_sync(self._path.read_bytes)
|
| 540 |
+
|
| 541 |
+
async def read_text(
|
| 542 |
+
self, encoding: str | None = None, errors: str | None = None
|
| 543 |
+
) -> str:
|
| 544 |
+
return await to_thread.run_sync(self._path.read_text, encoding, errors)
|
| 545 |
+
|
| 546 |
+
if sys.version_info >= (3, 12):
|
| 547 |
+
|
| 548 |
+
def relative_to(
|
| 549 |
+
self, *other: str | PathLike[str], walk_up: bool = False
|
| 550 |
+
) -> Path:
|
| 551 |
+
return Path(self._path.relative_to(*other, walk_up=walk_up))
|
| 552 |
+
|
| 553 |
+
else:
|
| 554 |
+
|
| 555 |
+
def relative_to(self, *other: str | PathLike[str]) -> Path:
|
| 556 |
+
return Path(self._path.relative_to(*other))
|
| 557 |
+
|
| 558 |
+
async def readlink(self) -> Path:
|
| 559 |
+
target = await to_thread.run_sync(os.readlink, self._path)
|
| 560 |
+
return Path(target)
|
| 561 |
+
|
| 562 |
+
async def rename(self, target: str | pathlib.PurePath | Path) -> Path:
|
| 563 |
+
if isinstance(target, Path):
|
| 564 |
+
target = target._path
|
| 565 |
+
|
| 566 |
+
await to_thread.run_sync(self._path.rename, target)
|
| 567 |
+
return Path(target)
|
| 568 |
+
|
| 569 |
+
async def replace(self, target: str | pathlib.PurePath | Path) -> Path:
|
| 570 |
+
if isinstance(target, Path):
|
| 571 |
+
target = target._path
|
| 572 |
+
|
| 573 |
+
await to_thread.run_sync(self._path.replace, target)
|
| 574 |
+
return Path(target)
|
| 575 |
+
|
| 576 |
+
async def resolve(self, strict: bool = False) -> Path:
|
| 577 |
+
func = partial(self._path.resolve, strict=strict)
|
| 578 |
+
return Path(await to_thread.run_sync(func, abandon_on_cancel=True))
|
| 579 |
+
|
| 580 |
+
def rglob(self, pattern: str) -> AsyncIterator[Path]:
|
| 581 |
+
gen = self._path.rglob(pattern)
|
| 582 |
+
return _PathIterator(gen)
|
| 583 |
+
|
| 584 |
+
async def rmdir(self) -> None:
|
| 585 |
+
await to_thread.run_sync(self._path.rmdir)
|
| 586 |
+
|
| 587 |
+
async def samefile(self, other_path: str | PathLike[str]) -> bool:
|
| 588 |
+
if isinstance(other_path, Path):
|
| 589 |
+
other_path = other_path._path
|
| 590 |
+
|
| 591 |
+
return await to_thread.run_sync(
|
| 592 |
+
self._path.samefile, other_path, abandon_on_cancel=True
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result:
|
| 596 |
+
func = partial(os.stat, follow_symlinks=follow_symlinks)
|
| 597 |
+
return await to_thread.run_sync(func, self._path, abandon_on_cancel=True)
|
| 598 |
+
|
| 599 |
+
async def symlink_to(
|
| 600 |
+
self,
|
| 601 |
+
target: str | bytes | PathLike[str] | PathLike[bytes],
|
| 602 |
+
target_is_directory: bool = False,
|
| 603 |
+
) -> None:
|
| 604 |
+
if isinstance(target, Path):
|
| 605 |
+
target = target._path
|
| 606 |
+
|
| 607 |
+
await to_thread.run_sync(self._path.symlink_to, target, target_is_directory)
|
| 608 |
+
|
| 609 |
+
async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
|
| 610 |
+
await to_thread.run_sync(self._path.touch, mode, exist_ok)
|
| 611 |
+
|
| 612 |
+
async def unlink(self, missing_ok: bool = False) -> None:
|
| 613 |
+
try:
|
| 614 |
+
await to_thread.run_sync(self._path.unlink)
|
| 615 |
+
except FileNotFoundError:
|
| 616 |
+
if not missing_ok:
|
| 617 |
+
raise
|
| 618 |
+
|
| 619 |
+
if sys.version_info >= (3, 12):
|
| 620 |
+
|
| 621 |
+
async def walk(
|
| 622 |
+
self,
|
| 623 |
+
top_down: bool = True,
|
| 624 |
+
on_error: Callable[[OSError], object] | None = None,
|
| 625 |
+
follow_symlinks: bool = False,
|
| 626 |
+
) -> AsyncIterator[tuple[Path, list[str], list[str]]]:
|
| 627 |
+
def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None:
|
| 628 |
+
try:
|
| 629 |
+
return next(gen)
|
| 630 |
+
except StopIteration:
|
| 631 |
+
return None
|
| 632 |
+
|
| 633 |
+
gen = self._path.walk(top_down, on_error, follow_symlinks)
|
| 634 |
+
while True:
|
| 635 |
+
value = await to_thread.run_sync(get_next_value)
|
| 636 |
+
if value is None:
|
| 637 |
+
return
|
| 638 |
+
|
| 639 |
+
root, dirs, paths = value
|
| 640 |
+
yield Path(root), dirs, paths
|
| 641 |
+
|
| 642 |
+
def with_name(self, name: str) -> Path:
|
| 643 |
+
return Path(self._path.with_name(name))
|
| 644 |
+
|
| 645 |
+
def with_stem(self, stem: str) -> Path:
|
| 646 |
+
return Path(self._path.with_name(stem + self._path.suffix))
|
| 647 |
+
|
| 648 |
+
def with_suffix(self, suffix: str) -> Path:
|
| 649 |
+
return Path(self._path.with_suffix(suffix))
|
| 650 |
+
|
| 651 |
+
def with_segments(self, *pathsegments: str | PathLike[str]) -> Path:
|
| 652 |
+
return Path(*pathsegments)
|
| 653 |
+
|
| 654 |
+
async def write_bytes(self, data: bytes) -> int:
|
| 655 |
+
return await to_thread.run_sync(self._path.write_bytes, data)
|
| 656 |
+
|
| 657 |
+
async def write_text(
|
| 658 |
+
self,
|
| 659 |
+
data: str,
|
| 660 |
+
encoding: str | None = None,
|
| 661 |
+
errors: str | None = None,
|
| 662 |
+
newline: str | None = None,
|
| 663 |
+
) -> int:
|
| 664 |
+
# Path.write_text() does not support the "newline" parameter before Python 3.10
|
| 665 |
+
def sync_write_text() -> int:
|
| 666 |
+
with self._path.open(
|
| 667 |
+
"w", encoding=encoding, errors=errors, newline=newline
|
| 668 |
+
) as fp:
|
| 669 |
+
return fp.write(data)
|
| 670 |
+
|
| 671 |
+
return await to_thread.run_sync(sync_write_text)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
PathLike.register(Path)
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_resources.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from ..abc import AsyncResource
|
| 4 |
+
from ._tasks import CancelScope
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
async def aclose_forcefully(resource: AsyncResource) -> None:
|
| 8 |
+
"""
|
| 9 |
+
Close an asynchronous resource in a cancelled scope.
|
| 10 |
+
|
| 11 |
+
Doing this closes the resource without waiting on anything.
|
| 12 |
+
|
| 13 |
+
:param resource: the resource to close
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
with CancelScope() as scope:
|
| 17 |
+
scope.cancel()
|
| 18 |
+
await resource.aclose()
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_signals.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import AsyncIterator
|
| 4 |
+
from contextlib import AbstractContextManager
|
| 5 |
+
from signal import Signals
|
| 6 |
+
|
| 7 |
+
from ._eventloop import get_async_backend
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def open_signal_receiver(
|
| 11 |
+
*signals: Signals,
|
| 12 |
+
) -> AbstractContextManager[AsyncIterator[Signals]]:
|
| 13 |
+
"""
|
| 14 |
+
Start receiving operating system signals.
|
| 15 |
+
|
| 16 |
+
:param signals: signals to receive (e.g. ``signal.SIGINT``)
|
| 17 |
+
:return: an asynchronous context manager for an asynchronous iterator which yields
|
| 18 |
+
signal numbers
|
| 19 |
+
|
| 20 |
+
.. warning:: Windows does not support signals natively so it is best to avoid
|
| 21 |
+
relying on this in cross-platform applications.
|
| 22 |
+
|
| 23 |
+
.. warning:: On asyncio, this permanently replaces any previous signal handler for
|
| 24 |
+
the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
return get_async_backend().open_signal_receiver(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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import errno
|
| 4 |
+
import os
|
| 5 |
+
import socket
|
| 6 |
+
import ssl
|
| 7 |
+
import stat
|
| 8 |
+
import sys
|
| 9 |
+
from collections.abc import Awaitable
|
| 10 |
+
from ipaddress import IPv6Address, ip_address
|
| 11 |
+
from os import PathLike, chmod
|
| 12 |
+
from socket import AddressFamily, SocketKind
|
| 13 |
+
from typing import TYPE_CHECKING, Any, Literal, cast, overload
|
| 14 |
+
|
| 15 |
+
from .. import to_thread
|
| 16 |
+
from ..abc import (
|
| 17 |
+
ConnectedUDPSocket,
|
| 18 |
+
ConnectedUNIXDatagramSocket,
|
| 19 |
+
IPAddressType,
|
| 20 |
+
IPSockAddrType,
|
| 21 |
+
SocketListener,
|
| 22 |
+
SocketStream,
|
| 23 |
+
UDPSocket,
|
| 24 |
+
UNIXDatagramSocket,
|
| 25 |
+
UNIXSocketStream,
|
| 26 |
+
)
|
| 27 |
+
from ..streams.stapled import MultiListener
|
| 28 |
+
from ..streams.tls import TLSStream
|
| 29 |
+
from ._eventloop import get_async_backend
|
| 30 |
+
from ._resources import aclose_forcefully
|
| 31 |
+
from ._synchronization import Event
|
| 32 |
+
from ._tasks import create_task_group, move_on_after
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from _typeshed import FileDescriptorLike
|
| 36 |
+
else:
|
| 37 |
+
FileDescriptorLike = object
|
| 38 |
+
|
| 39 |
+
if sys.version_info < (3, 11):
|
| 40 |
+
from exceptiongroup import ExceptionGroup
|
| 41 |
+
|
| 42 |
+
if sys.version_info < (3, 13):
|
| 43 |
+
from typing_extensions import deprecated
|
| 44 |
+
else:
|
| 45 |
+
from warnings import deprecated
|
| 46 |
+
|
| 47 |
+
IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515
|
| 48 |
+
|
| 49 |
+
AnyIPAddressFamily = Literal[
|
| 50 |
+
AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6
|
| 51 |
+
]
|
| 52 |
+
IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# tls_hostname given
|
| 56 |
+
@overload
|
| 57 |
+
async def connect_tcp(
|
| 58 |
+
remote_host: IPAddressType,
|
| 59 |
+
remote_port: int,
|
| 60 |
+
*,
|
| 61 |
+
local_host: IPAddressType | None = ...,
|
| 62 |
+
ssl_context: ssl.SSLContext | None = ...,
|
| 63 |
+
tls_standard_compatible: bool = ...,
|
| 64 |
+
tls_hostname: str,
|
| 65 |
+
happy_eyeballs_delay: float = ...,
|
| 66 |
+
) -> TLSStream: ...
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ssl_context given
|
| 70 |
+
@overload
|
| 71 |
+
async def connect_tcp(
|
| 72 |
+
remote_host: IPAddressType,
|
| 73 |
+
remote_port: int,
|
| 74 |
+
*,
|
| 75 |
+
local_host: IPAddressType | None = ...,
|
| 76 |
+
ssl_context: ssl.SSLContext,
|
| 77 |
+
tls_standard_compatible: bool = ...,
|
| 78 |
+
tls_hostname: str | None = ...,
|
| 79 |
+
happy_eyeballs_delay: float = ...,
|
| 80 |
+
) -> TLSStream: ...
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# tls=True
|
| 84 |
+
@overload
|
| 85 |
+
async def connect_tcp(
|
| 86 |
+
remote_host: IPAddressType,
|
| 87 |
+
remote_port: int,
|
| 88 |
+
*,
|
| 89 |
+
local_host: IPAddressType | None = ...,
|
| 90 |
+
tls: Literal[True],
|
| 91 |
+
ssl_context: ssl.SSLContext | None = ...,
|
| 92 |
+
tls_standard_compatible: bool = ...,
|
| 93 |
+
tls_hostname: str | None = ...,
|
| 94 |
+
happy_eyeballs_delay: float = ...,
|
| 95 |
+
) -> TLSStream: ...
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# tls=False
|
| 99 |
+
@overload
|
| 100 |
+
async def connect_tcp(
|
| 101 |
+
remote_host: IPAddressType,
|
| 102 |
+
remote_port: int,
|
| 103 |
+
*,
|
| 104 |
+
local_host: IPAddressType | None = ...,
|
| 105 |
+
tls: Literal[False],
|
| 106 |
+
ssl_context: ssl.SSLContext | None = ...,
|
| 107 |
+
tls_standard_compatible: bool = ...,
|
| 108 |
+
tls_hostname: str | None = ...,
|
| 109 |
+
happy_eyeballs_delay: float = ...,
|
| 110 |
+
) -> SocketStream: ...
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# No TLS arguments
|
| 114 |
+
@overload
|
| 115 |
+
async def connect_tcp(
|
| 116 |
+
remote_host: IPAddressType,
|
| 117 |
+
remote_port: int,
|
| 118 |
+
*,
|
| 119 |
+
local_host: IPAddressType | None = ...,
|
| 120 |
+
happy_eyeballs_delay: float = ...,
|
| 121 |
+
) -> SocketStream: ...
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
async def connect_tcp(
|
| 125 |
+
remote_host: IPAddressType,
|
| 126 |
+
remote_port: int,
|
| 127 |
+
*,
|
| 128 |
+
local_host: IPAddressType | None = None,
|
| 129 |
+
tls: bool = False,
|
| 130 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 131 |
+
tls_standard_compatible: bool = True,
|
| 132 |
+
tls_hostname: str | None = None,
|
| 133 |
+
happy_eyeballs_delay: float = 0.25,
|
| 134 |
+
) -> SocketStream | TLSStream:
|
| 135 |
+
"""
|
| 136 |
+
Connect to a host using the TCP protocol.
|
| 137 |
+
|
| 138 |
+
This function implements the stateless version of the Happy Eyeballs algorithm (RFC
|
| 139 |
+
6555). If ``remote_host`` is a host name that resolves to multiple IP addresses,
|
| 140 |
+
each one is tried until one connection attempt succeeds. If the first attempt does
|
| 141 |
+
not connected within 250 milliseconds, a second attempt is started using the next
|
| 142 |
+
address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if
|
| 143 |
+
available) is tried first.
|
| 144 |
+
|
| 145 |
+
When the connection has been established, a TLS handshake will be done if either
|
| 146 |
+
``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``.
|
| 147 |
+
|
| 148 |
+
:param remote_host: the IP address or host name to connect to
|
| 149 |
+
:param remote_port: port on the target host to connect to
|
| 150 |
+
:param local_host: the interface address or name to bind the socket to before
|
| 151 |
+
connecting
|
| 152 |
+
:param tls: ``True`` to do a TLS handshake with the connected stream and return a
|
| 153 |
+
:class:`~anyio.streams.tls.TLSStream` instead
|
| 154 |
+
:param ssl_context: the SSL context object to use (if omitted, a default context is
|
| 155 |
+
created)
|
| 156 |
+
:param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake
|
| 157 |
+
before closing the stream and requires that the server does this as well.
|
| 158 |
+
Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream.
|
| 159 |
+
Some protocols, such as HTTP, require this option to be ``False``.
|
| 160 |
+
See :meth:`~ssl.SSLContext.wrap_socket` for details.
|
| 161 |
+
:param tls_hostname: host name to check the server certificate against (defaults to
|
| 162 |
+
the value of ``remote_host``)
|
| 163 |
+
:param happy_eyeballs_delay: delay (in seconds) before starting the next connection
|
| 164 |
+
attempt
|
| 165 |
+
:return: a socket stream object if no TLS handshake was done, otherwise a TLS stream
|
| 166 |
+
:raises OSError: if the connection attempt fails
|
| 167 |
+
|
| 168 |
+
"""
|
| 169 |
+
# Placed here due to https://github.com/python/mypy/issues/7057
|
| 170 |
+
connected_stream: SocketStream | None = None
|
| 171 |
+
|
| 172 |
+
async def try_connect(remote_host: str, event: Event) -> None:
|
| 173 |
+
nonlocal connected_stream
|
| 174 |
+
try:
|
| 175 |
+
stream = await asynclib.connect_tcp(remote_host, remote_port, local_address)
|
| 176 |
+
except OSError as exc:
|
| 177 |
+
oserrors.append(exc)
|
| 178 |
+
return
|
| 179 |
+
else:
|
| 180 |
+
if connected_stream is None:
|
| 181 |
+
connected_stream = stream
|
| 182 |
+
tg.cancel_scope.cancel()
|
| 183 |
+
else:
|
| 184 |
+
await stream.aclose()
|
| 185 |
+
finally:
|
| 186 |
+
event.set()
|
| 187 |
+
|
| 188 |
+
asynclib = get_async_backend()
|
| 189 |
+
local_address: IPSockAddrType | None = None
|
| 190 |
+
family = socket.AF_UNSPEC
|
| 191 |
+
if local_host:
|
| 192 |
+
gai_res = await getaddrinfo(str(local_host), None)
|
| 193 |
+
family, *_, local_address = gai_res[0]
|
| 194 |
+
|
| 195 |
+
target_host = str(remote_host)
|
| 196 |
+
try:
|
| 197 |
+
addr_obj = ip_address(remote_host)
|
| 198 |
+
except ValueError:
|
| 199 |
+
addr_obj = None
|
| 200 |
+
|
| 201 |
+
if addr_obj is not None:
|
| 202 |
+
if isinstance(addr_obj, IPv6Address):
|
| 203 |
+
target_addrs = [(socket.AF_INET6, addr_obj.compressed)]
|
| 204 |
+
else:
|
| 205 |
+
target_addrs = [(socket.AF_INET, addr_obj.compressed)]
|
| 206 |
+
else:
|
| 207 |
+
# getaddrinfo() will raise an exception if name resolution fails
|
| 208 |
+
gai_res = await getaddrinfo(
|
| 209 |
+
target_host, remote_port, family=family, type=socket.SOCK_STREAM
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# Organize the list so that the first address is an IPv6 address (if available)
|
| 213 |
+
# and the second one is an IPv4 addresses. The rest can be in whatever order.
|
| 214 |
+
v6_found = v4_found = False
|
| 215 |
+
target_addrs = []
|
| 216 |
+
for af, *rest, sa in gai_res:
|
| 217 |
+
if af == socket.AF_INET6 and not v6_found:
|
| 218 |
+
v6_found = True
|
| 219 |
+
target_addrs.insert(0, (af, sa[0]))
|
| 220 |
+
elif af == socket.AF_INET and not v4_found and v6_found:
|
| 221 |
+
v4_found = True
|
| 222 |
+
target_addrs.insert(1, (af, sa[0]))
|
| 223 |
+
else:
|
| 224 |
+
target_addrs.append((af, sa[0]))
|
| 225 |
+
|
| 226 |
+
oserrors: list[OSError] = []
|
| 227 |
+
async with create_task_group() as tg:
|
| 228 |
+
for i, (af, addr) in enumerate(target_addrs):
|
| 229 |
+
event = Event()
|
| 230 |
+
tg.start_soon(try_connect, addr, event)
|
| 231 |
+
with move_on_after(happy_eyeballs_delay):
|
| 232 |
+
await event.wait()
|
| 233 |
+
|
| 234 |
+
if connected_stream is None:
|
| 235 |
+
cause = (
|
| 236 |
+
oserrors[0]
|
| 237 |
+
if len(oserrors) == 1
|
| 238 |
+
else ExceptionGroup("multiple connection attempts failed", oserrors)
|
| 239 |
+
)
|
| 240 |
+
raise OSError("All connection attempts failed") from cause
|
| 241 |
+
|
| 242 |
+
if tls or tls_hostname or ssl_context:
|
| 243 |
+
try:
|
| 244 |
+
return await TLSStream.wrap(
|
| 245 |
+
connected_stream,
|
| 246 |
+
server_side=False,
|
| 247 |
+
hostname=tls_hostname or str(remote_host),
|
| 248 |
+
ssl_context=ssl_context,
|
| 249 |
+
standard_compatible=tls_standard_compatible,
|
| 250 |
+
)
|
| 251 |
+
except BaseException:
|
| 252 |
+
await aclose_forcefully(connected_stream)
|
| 253 |
+
raise
|
| 254 |
+
|
| 255 |
+
return connected_stream
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream:
|
| 259 |
+
"""
|
| 260 |
+
Connect to the given UNIX socket.
|
| 261 |
+
|
| 262 |
+
Not available on Windows.
|
| 263 |
+
|
| 264 |
+
:param path: path to the socket
|
| 265 |
+
:return: a socket stream object
|
| 266 |
+
|
| 267 |
+
"""
|
| 268 |
+
path = os.fspath(path)
|
| 269 |
+
return await get_async_backend().connect_unix(path)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
async def create_tcp_listener(
|
| 273 |
+
*,
|
| 274 |
+
local_host: IPAddressType | None = None,
|
| 275 |
+
local_port: int = 0,
|
| 276 |
+
family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC,
|
| 277 |
+
backlog: int = 65536,
|
| 278 |
+
reuse_port: bool = False,
|
| 279 |
+
) -> MultiListener[SocketStream]:
|
| 280 |
+
"""
|
| 281 |
+
Create a TCP socket listener.
|
| 282 |
+
|
| 283 |
+
:param local_port: port number to listen on
|
| 284 |
+
:param local_host: IP address of the interface to listen on. If omitted, listen on
|
| 285 |
+
all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address
|
| 286 |
+
family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6.
|
| 287 |
+
:param family: address family (used if ``local_host`` was omitted)
|
| 288 |
+
:param backlog: maximum number of queued incoming connections (up to a maximum of
|
| 289 |
+
2**16, or 65536)
|
| 290 |
+
:param reuse_port: ``True`` to allow multiple sockets to bind to the same
|
| 291 |
+
address/port (not supported on Windows)
|
| 292 |
+
:return: a list of listener objects
|
| 293 |
+
|
| 294 |
+
"""
|
| 295 |
+
asynclib = get_async_backend()
|
| 296 |
+
backlog = min(backlog, 65536)
|
| 297 |
+
local_host = str(local_host) if local_host is not None else None
|
| 298 |
+
gai_res = await getaddrinfo(
|
| 299 |
+
local_host,
|
| 300 |
+
local_port,
|
| 301 |
+
family=family,
|
| 302 |
+
type=socket.SocketKind.SOCK_STREAM if sys.platform == "win32" else 0,
|
| 303 |
+
flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
|
| 304 |
+
)
|
| 305 |
+
listeners: list[SocketListener] = []
|
| 306 |
+
try:
|
| 307 |
+
# The set() is here to work around a glibc bug:
|
| 308 |
+
# https://sourceware.org/bugzilla/show_bug.cgi?id=14969
|
| 309 |
+
sockaddr: tuple[str, int] | tuple[str, int, int, int]
|
| 310 |
+
for fam, kind, *_, sockaddr in sorted(set(gai_res)):
|
| 311 |
+
# Workaround for an uvloop bug where we don't get the correct scope ID for
|
| 312 |
+
# IPv6 link-local addresses when passing type=socket.SOCK_STREAM to
|
| 313 |
+
# getaddrinfo(): https://github.com/MagicStack/uvloop/issues/539
|
| 314 |
+
if sys.platform != "win32" and kind is not SocketKind.SOCK_STREAM:
|
| 315 |
+
continue
|
| 316 |
+
|
| 317 |
+
raw_socket = socket.socket(fam)
|
| 318 |
+
raw_socket.setblocking(False)
|
| 319 |
+
|
| 320 |
+
# For Windows, enable exclusive address use. For others, enable address
|
| 321 |
+
# reuse.
|
| 322 |
+
if sys.platform == "win32":
|
| 323 |
+
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
| 324 |
+
else:
|
| 325 |
+
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 326 |
+
|
| 327 |
+
if reuse_port:
|
| 328 |
+
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
| 329 |
+
|
| 330 |
+
# If only IPv6 was requested, disable dual stack operation
|
| 331 |
+
if fam == socket.AF_INET6:
|
| 332 |
+
raw_socket.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
| 333 |
+
|
| 334 |
+
# Workaround for #554
|
| 335 |
+
if "%" in sockaddr[0]:
|
| 336 |
+
addr, scope_id = sockaddr[0].split("%", 1)
|
| 337 |
+
sockaddr = (addr, sockaddr[1], 0, int(scope_id))
|
| 338 |
+
|
| 339 |
+
raw_socket.bind(sockaddr)
|
| 340 |
+
raw_socket.listen(backlog)
|
| 341 |
+
listener = asynclib.create_tcp_listener(raw_socket)
|
| 342 |
+
listeners.append(listener)
|
| 343 |
+
except BaseException:
|
| 344 |
+
for listener in listeners:
|
| 345 |
+
await listener.aclose()
|
| 346 |
+
|
| 347 |
+
raise
|
| 348 |
+
|
| 349 |
+
return MultiListener(listeners)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
async def create_unix_listener(
|
| 353 |
+
path: str | bytes | PathLike[Any],
|
| 354 |
+
*,
|
| 355 |
+
mode: int | None = None,
|
| 356 |
+
backlog: int = 65536,
|
| 357 |
+
) -> SocketListener:
|
| 358 |
+
"""
|
| 359 |
+
Create a UNIX socket listener.
|
| 360 |
+
|
| 361 |
+
Not available on Windows.
|
| 362 |
+
|
| 363 |
+
:param path: path of the socket
|
| 364 |
+
:param mode: permissions to set on the socket
|
| 365 |
+
:param backlog: maximum number of queued incoming connections (up to a maximum of
|
| 366 |
+
2**16, or 65536)
|
| 367 |
+
:return: a listener object
|
| 368 |
+
|
| 369 |
+
.. versionchanged:: 3.0
|
| 370 |
+
If a socket already exists on the file system in the given path, it will be
|
| 371 |
+
removed first.
|
| 372 |
+
|
| 373 |
+
"""
|
| 374 |
+
backlog = min(backlog, 65536)
|
| 375 |
+
raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM)
|
| 376 |
+
try:
|
| 377 |
+
raw_socket.listen(backlog)
|
| 378 |
+
return get_async_backend().create_unix_listener(raw_socket)
|
| 379 |
+
except BaseException:
|
| 380 |
+
raw_socket.close()
|
| 381 |
+
raise
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
async def create_udp_socket(
|
| 385 |
+
family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC,
|
| 386 |
+
*,
|
| 387 |
+
local_host: IPAddressType | None = None,
|
| 388 |
+
local_port: int = 0,
|
| 389 |
+
reuse_port: bool = False,
|
| 390 |
+
) -> UDPSocket:
|
| 391 |
+
"""
|
| 392 |
+
Create a UDP socket.
|
| 393 |
+
|
| 394 |
+
If ``port`` has been given, the socket will be bound to this port on the local
|
| 395 |
+
machine, making this socket suitable for providing UDP based services.
|
| 396 |
+
|
| 397 |
+
:param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
|
| 398 |
+
determined from ``local_host`` if omitted
|
| 399 |
+
:param local_host: IP address or host name of the local interface to bind to
|
| 400 |
+
:param local_port: local port to bind to
|
| 401 |
+
:param reuse_port: ``True`` to allow multiple sockets to bind to the same
|
| 402 |
+
address/port (not supported on Windows)
|
| 403 |
+
:return: a UDP socket
|
| 404 |
+
|
| 405 |
+
"""
|
| 406 |
+
if family is AddressFamily.AF_UNSPEC and not local_host:
|
| 407 |
+
raise ValueError('Either "family" or "local_host" must be given')
|
| 408 |
+
|
| 409 |
+
if local_host:
|
| 410 |
+
gai_res = await getaddrinfo(
|
| 411 |
+
str(local_host),
|
| 412 |
+
local_port,
|
| 413 |
+
family=family,
|
| 414 |
+
type=socket.SOCK_DGRAM,
|
| 415 |
+
flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
|
| 416 |
+
)
|
| 417 |
+
family = cast(AnyIPAddressFamily, gai_res[0][0])
|
| 418 |
+
local_address = gai_res[0][-1]
|
| 419 |
+
elif family is AddressFamily.AF_INET6:
|
| 420 |
+
local_address = ("::", 0)
|
| 421 |
+
else:
|
| 422 |
+
local_address = ("0.0.0.0", 0)
|
| 423 |
+
|
| 424 |
+
sock = await get_async_backend().create_udp_socket(
|
| 425 |
+
family, local_address, None, reuse_port
|
| 426 |
+
)
|
| 427 |
+
return cast(UDPSocket, sock)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
async def create_connected_udp_socket(
|
| 431 |
+
remote_host: IPAddressType,
|
| 432 |
+
remote_port: int,
|
| 433 |
+
*,
|
| 434 |
+
family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC,
|
| 435 |
+
local_host: IPAddressType | None = None,
|
| 436 |
+
local_port: int = 0,
|
| 437 |
+
reuse_port: bool = False,
|
| 438 |
+
) -> ConnectedUDPSocket:
|
| 439 |
+
"""
|
| 440 |
+
Create a connected UDP socket.
|
| 441 |
+
|
| 442 |
+
Connected UDP sockets can only communicate with the specified remote host/port, an
|
| 443 |
+
any packets sent from other sources are dropped.
|
| 444 |
+
|
| 445 |
+
:param remote_host: remote host to set as the default target
|
| 446 |
+
:param remote_port: port on the remote host to set as the default target
|
| 447 |
+
:param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
|
| 448 |
+
determined from ``local_host`` or ``remote_host`` if omitted
|
| 449 |
+
:param local_host: IP address or host name of the local interface to bind to
|
| 450 |
+
:param local_port: local port to bind to
|
| 451 |
+
:param reuse_port: ``True`` to allow multiple sockets to bind to the same
|
| 452 |
+
address/port (not supported on Windows)
|
| 453 |
+
:return: a connected UDP socket
|
| 454 |
+
|
| 455 |
+
"""
|
| 456 |
+
local_address = None
|
| 457 |
+
if local_host:
|
| 458 |
+
gai_res = await getaddrinfo(
|
| 459 |
+
str(local_host),
|
| 460 |
+
local_port,
|
| 461 |
+
family=family,
|
| 462 |
+
type=socket.SOCK_DGRAM,
|
| 463 |
+
flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
|
| 464 |
+
)
|
| 465 |
+
family = cast(AnyIPAddressFamily, gai_res[0][0])
|
| 466 |
+
local_address = gai_res[0][-1]
|
| 467 |
+
|
| 468 |
+
gai_res = await getaddrinfo(
|
| 469 |
+
str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM
|
| 470 |
+
)
|
| 471 |
+
family = cast(AnyIPAddressFamily, gai_res[0][0])
|
| 472 |
+
remote_address = gai_res[0][-1]
|
| 473 |
+
|
| 474 |
+
sock = await get_async_backend().create_udp_socket(
|
| 475 |
+
family, local_address, remote_address, reuse_port
|
| 476 |
+
)
|
| 477 |
+
return cast(ConnectedUDPSocket, sock)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
async def create_unix_datagram_socket(
|
| 481 |
+
*,
|
| 482 |
+
local_path: None | str | bytes | PathLike[Any] = None,
|
| 483 |
+
local_mode: int | None = None,
|
| 484 |
+
) -> UNIXDatagramSocket:
|
| 485 |
+
"""
|
| 486 |
+
Create a UNIX datagram socket.
|
| 487 |
+
|
| 488 |
+
Not available on Windows.
|
| 489 |
+
|
| 490 |
+
If ``local_path`` has been given, the socket will be bound to this path, making this
|
| 491 |
+
socket suitable for receiving datagrams from other processes. Other processes can
|
| 492 |
+
send datagrams to this socket only if ``local_path`` is set.
|
| 493 |
+
|
| 494 |
+
If a socket already exists on the file system in the ``local_path``, it will be
|
| 495 |
+
removed first.
|
| 496 |
+
|
| 497 |
+
:param local_path: the path on which to bind to
|
| 498 |
+
:param local_mode: permissions to set on the local socket
|
| 499 |
+
:return: a UNIX datagram socket
|
| 500 |
+
|
| 501 |
+
"""
|
| 502 |
+
raw_socket = await setup_unix_local_socket(
|
| 503 |
+
local_path, local_mode, socket.SOCK_DGRAM
|
| 504 |
+
)
|
| 505 |
+
return await get_async_backend().create_unix_datagram_socket(raw_socket, None)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
async def create_connected_unix_datagram_socket(
|
| 509 |
+
remote_path: str | bytes | PathLike[Any],
|
| 510 |
+
*,
|
| 511 |
+
local_path: None | str | bytes | PathLike[Any] = None,
|
| 512 |
+
local_mode: int | None = None,
|
| 513 |
+
) -> ConnectedUNIXDatagramSocket:
|
| 514 |
+
"""
|
| 515 |
+
Create a connected UNIX datagram socket.
|
| 516 |
+
|
| 517 |
+
Connected datagram sockets can only communicate with the specified remote path.
|
| 518 |
+
|
| 519 |
+
If ``local_path`` has been given, the socket will be bound to this path, making
|
| 520 |
+
this socket suitable for receiving datagrams from other processes. Other processes
|
| 521 |
+
can send datagrams to this socket only if ``local_path`` is set.
|
| 522 |
+
|
| 523 |
+
If a socket already exists on the file system in the ``local_path``, it will be
|
| 524 |
+
removed first.
|
| 525 |
+
|
| 526 |
+
:param remote_path: the path to set as the default target
|
| 527 |
+
:param local_path: the path on which to bind to
|
| 528 |
+
:param local_mode: permissions to set on the local socket
|
| 529 |
+
:return: a connected UNIX datagram socket
|
| 530 |
+
|
| 531 |
+
"""
|
| 532 |
+
remote_path = os.fspath(remote_path)
|
| 533 |
+
raw_socket = await setup_unix_local_socket(
|
| 534 |
+
local_path, local_mode, socket.SOCK_DGRAM
|
| 535 |
+
)
|
| 536 |
+
return await get_async_backend().create_unix_datagram_socket(
|
| 537 |
+
raw_socket, remote_path
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
async def getaddrinfo(
|
| 542 |
+
host: bytes | str | None,
|
| 543 |
+
port: str | int | None,
|
| 544 |
+
*,
|
| 545 |
+
family: int | AddressFamily = 0,
|
| 546 |
+
type: int | SocketKind = 0,
|
| 547 |
+
proto: int = 0,
|
| 548 |
+
flags: int = 0,
|
| 549 |
+
) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]:
|
| 550 |
+
"""
|
| 551 |
+
Look up a numeric IP address given a host name.
|
| 552 |
+
|
| 553 |
+
Internationalized domain names are translated according to the (non-transitional)
|
| 554 |
+
IDNA 2008 standard.
|
| 555 |
+
|
| 556 |
+
.. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of
|
| 557 |
+
(host, port), unlike what :func:`socket.getaddrinfo` does.
|
| 558 |
+
|
| 559 |
+
:param host: host name
|
| 560 |
+
:param port: port number
|
| 561 |
+
:param family: socket family (`'AF_INET``, ...)
|
| 562 |
+
:param type: socket type (``SOCK_STREAM``, ...)
|
| 563 |
+
:param proto: protocol number
|
| 564 |
+
:param flags: flags to pass to upstream ``getaddrinfo()``
|
| 565 |
+
:return: list of tuples containing (family, type, proto, canonname, sockaddr)
|
| 566 |
+
|
| 567 |
+
.. seealso:: :func:`socket.getaddrinfo`
|
| 568 |
+
|
| 569 |
+
"""
|
| 570 |
+
# Handle unicode hostnames
|
| 571 |
+
if isinstance(host, str):
|
| 572 |
+
try:
|
| 573 |
+
encoded_host: bytes | None = host.encode("ascii")
|
| 574 |
+
except UnicodeEncodeError:
|
| 575 |
+
import idna
|
| 576 |
+
|
| 577 |
+
encoded_host = idna.encode(host, uts46=True)
|
| 578 |
+
else:
|
| 579 |
+
encoded_host = host
|
| 580 |
+
|
| 581 |
+
gai_res = await get_async_backend().getaddrinfo(
|
| 582 |
+
encoded_host, port, family=family, type=type, proto=proto, flags=flags
|
| 583 |
+
)
|
| 584 |
+
return [
|
| 585 |
+
(family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr))
|
| 586 |
+
for family, type, proto, canonname, sockaddr in gai_res
|
| 587 |
+
]
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]:
|
| 591 |
+
"""
|
| 592 |
+
Look up the host name of an IP address.
|
| 593 |
+
|
| 594 |
+
:param sockaddr: socket address (e.g. (ipaddress, port) for IPv4)
|
| 595 |
+
:param flags: flags to pass to upstream ``getnameinfo()``
|
| 596 |
+
:return: a tuple of (host name, service name)
|
| 597 |
+
|
| 598 |
+
.. seealso:: :func:`socket.getnameinfo`
|
| 599 |
+
|
| 600 |
+
"""
|
| 601 |
+
return get_async_backend().getnameinfo(sockaddr, flags)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
@deprecated("This function is deprecated; use `wait_readable` instead")
|
| 605 |
+
def wait_socket_readable(sock: socket.socket) -> Awaitable[None]:
|
| 606 |
+
"""
|
| 607 |
+
.. deprecated:: 4.7.0
|
| 608 |
+
Use :func:`wait_readable` instead.
|
| 609 |
+
|
| 610 |
+
Wait until the given socket has data to be read.
|
| 611 |
+
|
| 612 |
+
.. warning:: Only use this on raw sockets that have not been wrapped by any higher
|
| 613 |
+
level constructs like socket streams!
|
| 614 |
+
|
| 615 |
+
:param sock: a socket object
|
| 616 |
+
:raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
|
| 617 |
+
socket to become readable
|
| 618 |
+
:raises ~anyio.BusyResourceError: if another task is already waiting for the socket
|
| 619 |
+
to become readable
|
| 620 |
+
|
| 621 |
+
"""
|
| 622 |
+
return get_async_backend().wait_readable(sock.fileno())
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
@deprecated("This function is deprecated; use `wait_writable` instead")
|
| 626 |
+
def wait_socket_writable(sock: socket.socket) -> Awaitable[None]:
|
| 627 |
+
"""
|
| 628 |
+
.. deprecated:: 4.7.0
|
| 629 |
+
Use :func:`wait_writable` instead.
|
| 630 |
+
|
| 631 |
+
Wait until the given socket can be written to.
|
| 632 |
+
|
| 633 |
+
This does **NOT** work on Windows when using the asyncio backend with a proactor
|
| 634 |
+
event loop (default on py3.8+).
|
| 635 |
+
|
| 636 |
+
.. warning:: Only use this on raw sockets that have not been wrapped by any higher
|
| 637 |
+
level constructs like socket streams!
|
| 638 |
+
|
| 639 |
+
:param sock: a socket object
|
| 640 |
+
:raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
|
| 641 |
+
socket to become writable
|
| 642 |
+
:raises ~anyio.BusyResourceError: if another task is already waiting for the socket
|
| 643 |
+
to become writable
|
| 644 |
+
|
| 645 |
+
"""
|
| 646 |
+
return get_async_backend().wait_writable(sock.fileno())
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]:
|
| 650 |
+
"""
|
| 651 |
+
Wait until the given object has data to be read.
|
| 652 |
+
|
| 653 |
+
On Unix systems, ``obj`` must either be an integer file descriptor, or else an
|
| 654 |
+
object with a ``.fileno()`` method which returns an integer file descriptor. Any
|
| 655 |
+
kind of file descriptor can be passed, though the exact semantics will depend on
|
| 656 |
+
your kernel. For example, this probably won't do anything useful for on-disk files.
|
| 657 |
+
|
| 658 |
+
On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an
|
| 659 |
+
object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File
|
| 660 |
+
descriptors aren't supported, and neither are handles that refer to anything besides
|
| 661 |
+
a ``SOCKET``.
|
| 662 |
+
|
| 663 |
+
On backends where this functionality is not natively provided (asyncio
|
| 664 |
+
``ProactorEventLoop`` on Windows), it is provided using a separate selector thread
|
| 665 |
+
which is set to shut down when the interpreter shuts down.
|
| 666 |
+
|
| 667 |
+
.. warning:: Don't use this on raw sockets that have been wrapped by any higher
|
| 668 |
+
level constructs like socket streams!
|
| 669 |
+
|
| 670 |
+
:param obj: an object with a ``.fileno()`` method or an integer handle
|
| 671 |
+
:raises ~anyio.ClosedResourceError: if the object was closed while waiting for the
|
| 672 |
+
object to become readable
|
| 673 |
+
:raises ~anyio.BusyResourceError: if another task is already waiting for the object
|
| 674 |
+
to become readable
|
| 675 |
+
|
| 676 |
+
"""
|
| 677 |
+
return get_async_backend().wait_readable(obj)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]:
|
| 681 |
+
"""
|
| 682 |
+
Wait until the given object can be written to.
|
| 683 |
+
|
| 684 |
+
:param obj: an object with a ``.fileno()`` method or an integer handle
|
| 685 |
+
:raises ~anyio.ClosedResourceError: if the object was closed while waiting for the
|
| 686 |
+
object to become writable
|
| 687 |
+
:raises ~anyio.BusyResourceError: if another task is already waiting for the object
|
| 688 |
+
to become writable
|
| 689 |
+
|
| 690 |
+
.. seealso:: See the documentation of :func:`wait_readable` for the definition of
|
| 691 |
+
``obj`` and notes on backend compatibility.
|
| 692 |
+
|
| 693 |
+
.. warning:: Don't use this on raw sockets that have been wrapped by any higher
|
| 694 |
+
level constructs like socket streams!
|
| 695 |
+
|
| 696 |
+
"""
|
| 697 |
+
return get_async_backend().wait_writable(obj)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
#
|
| 701 |
+
# Private API
|
| 702 |
+
#
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def convert_ipv6_sockaddr(
|
| 706 |
+
sockaddr: tuple[str, int, int, int] | tuple[str, int],
|
| 707 |
+
) -> tuple[str, int]:
|
| 708 |
+
"""
|
| 709 |
+
Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format.
|
| 710 |
+
|
| 711 |
+
If the scope ID is nonzero, it is added to the address, separated with ``%``.
|
| 712 |
+
Otherwise the flow id and scope id are simply cut off from the tuple.
|
| 713 |
+
Any other kinds of socket addresses are returned as-is.
|
| 714 |
+
|
| 715 |
+
:param sockaddr: the result of :meth:`~socket.socket.getsockname`
|
| 716 |
+
:return: the converted socket address
|
| 717 |
+
|
| 718 |
+
"""
|
| 719 |
+
# This is more complicated than it should be because of MyPy
|
| 720 |
+
if isinstance(sockaddr, tuple) and len(sockaddr) == 4:
|
| 721 |
+
host, port, flowinfo, scope_id = sockaddr
|
| 722 |
+
if scope_id:
|
| 723 |
+
# PyPy (as of v7.3.11) leaves the interface name in the result, so
|
| 724 |
+
# we discard it and only get the scope ID from the end
|
| 725 |
+
# (https://foss.heptapod.net/pypy/pypy/-/issues/3938)
|
| 726 |
+
host = host.split("%")[0]
|
| 727 |
+
|
| 728 |
+
# Add scope_id to the address
|
| 729 |
+
return f"{host}%{scope_id}", port
|
| 730 |
+
else:
|
| 731 |
+
return host, port
|
| 732 |
+
else:
|
| 733 |
+
return sockaddr
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
async def setup_unix_local_socket(
|
| 737 |
+
path: None | str | bytes | PathLike[Any],
|
| 738 |
+
mode: int | None,
|
| 739 |
+
socktype: int,
|
| 740 |
+
) -> socket.socket:
|
| 741 |
+
"""
|
| 742 |
+
Create a UNIX local socket object, deleting the socket at the given path if it
|
| 743 |
+
exists.
|
| 744 |
+
|
| 745 |
+
Not available on Windows.
|
| 746 |
+
|
| 747 |
+
:param path: path of the socket
|
| 748 |
+
:param mode: permissions to set on the socket
|
| 749 |
+
:param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM
|
| 750 |
+
|
| 751 |
+
"""
|
| 752 |
+
path_str: str | None
|
| 753 |
+
if path is not None:
|
| 754 |
+
path_str = os.fsdecode(path)
|
| 755 |
+
|
| 756 |
+
# Linux abstract namespace sockets aren't backed by a concrete file so skip stat call
|
| 757 |
+
if not path_str.startswith("\0"):
|
| 758 |
+
# Copied from pathlib...
|
| 759 |
+
try:
|
| 760 |
+
stat_result = os.stat(path)
|
| 761 |
+
except OSError as e:
|
| 762 |
+
if e.errno not in (
|
| 763 |
+
errno.ENOENT,
|
| 764 |
+
errno.ENOTDIR,
|
| 765 |
+
errno.EBADF,
|
| 766 |
+
errno.ELOOP,
|
| 767 |
+
):
|
| 768 |
+
raise
|
| 769 |
+
else:
|
| 770 |
+
if stat.S_ISSOCK(stat_result.st_mode):
|
| 771 |
+
os.unlink(path)
|
| 772 |
+
else:
|
| 773 |
+
path_str = None
|
| 774 |
+
|
| 775 |
+
raw_socket = socket.socket(socket.AF_UNIX, socktype)
|
| 776 |
+
raw_socket.setblocking(False)
|
| 777 |
+
|
| 778 |
+
if path_str is not None:
|
| 779 |
+
try:
|
| 780 |
+
await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True)
|
| 781 |
+
if mode is not None:
|
| 782 |
+
await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True)
|
| 783 |
+
except BaseException:
|
| 784 |
+
raw_socket.close()
|
| 785 |
+
raise
|
| 786 |
+
|
| 787 |
+
return raw_socket
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_streams.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import TypeVar
|
| 5 |
+
from warnings import warn
|
| 6 |
+
|
| 7 |
+
from ..streams.memory import (
|
| 8 |
+
MemoryObjectReceiveStream,
|
| 9 |
+
MemoryObjectSendStream,
|
| 10 |
+
MemoryObjectStreamState,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
T_Item = TypeVar("T_Item")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class create_memory_object_stream(
|
| 17 |
+
tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]],
|
| 18 |
+
):
|
| 19 |
+
"""
|
| 20 |
+
Create a memory object stream.
|
| 21 |
+
|
| 22 |
+
The stream's item type can be annotated like
|
| 23 |
+
:func:`create_memory_object_stream[T_Item]`.
|
| 24 |
+
|
| 25 |
+
:param max_buffer_size: number of items held in the buffer until ``send()`` starts
|
| 26 |
+
blocking
|
| 27 |
+
:param item_type: old way of marking the streams with the right generic type for
|
| 28 |
+
static typing (does nothing on AnyIO 4)
|
| 29 |
+
|
| 30 |
+
.. deprecated:: 4.0
|
| 31 |
+
Use ``create_memory_object_stream[YourItemType](...)`` instead.
|
| 32 |
+
:return: a tuple of (send stream, receive stream)
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __new__( # type: ignore[misc]
|
| 37 |
+
cls, max_buffer_size: float = 0, item_type: object = None
|
| 38 |
+
) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]:
|
| 39 |
+
if max_buffer_size != math.inf and not isinstance(max_buffer_size, int):
|
| 40 |
+
raise ValueError("max_buffer_size must be either an integer or math.inf")
|
| 41 |
+
if max_buffer_size < 0:
|
| 42 |
+
raise ValueError("max_buffer_size cannot be negative")
|
| 43 |
+
if item_type is not None:
|
| 44 |
+
warn(
|
| 45 |
+
"The item_type argument has been deprecated in AnyIO 4.0. "
|
| 46 |
+
"Use create_memory_object_stream[YourItemType](...) instead.",
|
| 47 |
+
DeprecationWarning,
|
| 48 |
+
stacklevel=2,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
state = MemoryObjectStreamState[T_Item](max_buffer_size)
|
| 52 |
+
return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state))
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_subprocesses.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from os import PathLike
|
| 7 |
+
from subprocess import DEVNULL, PIPE, CalledProcessError, CompletedProcess
|
| 8 |
+
from typing import IO, Any, Union, cast
|
| 9 |
+
|
| 10 |
+
from ..abc import Process
|
| 11 |
+
from ._eventloop import get_async_backend
|
| 12 |
+
from ._tasks import create_task_group
|
| 13 |
+
|
| 14 |
+
if sys.version_info >= (3, 10):
|
| 15 |
+
from typing import TypeAlias
|
| 16 |
+
else:
|
| 17 |
+
from typing_extensions import TypeAlias
|
| 18 |
+
|
| 19 |
+
StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
async def run_process(
|
| 23 |
+
command: StrOrBytesPath | Sequence[StrOrBytesPath],
|
| 24 |
+
*,
|
| 25 |
+
input: bytes | None = None,
|
| 26 |
+
stdout: int | IO[Any] | None = PIPE,
|
| 27 |
+
stderr: int | IO[Any] | None = PIPE,
|
| 28 |
+
check: bool = True,
|
| 29 |
+
cwd: StrOrBytesPath | None = None,
|
| 30 |
+
env: Mapping[str, str] | None = None,
|
| 31 |
+
startupinfo: Any = None,
|
| 32 |
+
creationflags: int = 0,
|
| 33 |
+
start_new_session: bool = False,
|
| 34 |
+
pass_fds: Sequence[int] = (),
|
| 35 |
+
user: str | int | None = None,
|
| 36 |
+
group: str | int | None = None,
|
| 37 |
+
extra_groups: Iterable[str | int] | None = None,
|
| 38 |
+
umask: int = -1,
|
| 39 |
+
) -> CompletedProcess[bytes]:
|
| 40 |
+
"""
|
| 41 |
+
Run an external command in a subprocess and wait until it completes.
|
| 42 |
+
|
| 43 |
+
.. seealso:: :func:`subprocess.run`
|
| 44 |
+
|
| 45 |
+
:param command: either a string to pass to the shell, or an iterable of strings
|
| 46 |
+
containing the executable name or path and its arguments
|
| 47 |
+
:param input: bytes passed to the standard input of the subprocess
|
| 48 |
+
:param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
|
| 49 |
+
a file-like object, or `None`
|
| 50 |
+
:param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
|
| 51 |
+
:data:`subprocess.STDOUT`, a file-like object, or `None`
|
| 52 |
+
:param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the
|
| 53 |
+
process terminates with a return code other than 0
|
| 54 |
+
:param cwd: If not ``None``, change the working directory to this before running the
|
| 55 |
+
command
|
| 56 |
+
:param env: if not ``None``, this mapping replaces the inherited environment
|
| 57 |
+
variables from the parent process
|
| 58 |
+
:param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
|
| 59 |
+
to specify process startup parameters (Windows only)
|
| 60 |
+
:param creationflags: flags that can be used to control the creation of the
|
| 61 |
+
subprocess (see :class:`subprocess.Popen` for the specifics)
|
| 62 |
+
:param start_new_session: if ``true`` the setsid() system call will be made in the
|
| 63 |
+
child process prior to the execution of the subprocess. (POSIX only)
|
| 64 |
+
:param pass_fds: sequence of file descriptors to keep open between the parent and
|
| 65 |
+
child processes. (POSIX only)
|
| 66 |
+
:param user: effective user to run the process as (Python >= 3.9, POSIX only)
|
| 67 |
+
:param group: effective group to run the process as (Python >= 3.9, POSIX only)
|
| 68 |
+
:param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9,
|
| 69 |
+
POSIX only)
|
| 70 |
+
:param umask: if not negative, this umask is applied in the child process before
|
| 71 |
+
running the given command (Python >= 3.9, POSIX only)
|
| 72 |
+
:return: an object representing the completed process
|
| 73 |
+
:raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process
|
| 74 |
+
exits with a nonzero return code
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None:
|
| 79 |
+
buffer = BytesIO()
|
| 80 |
+
async for chunk in stream:
|
| 81 |
+
buffer.write(chunk)
|
| 82 |
+
|
| 83 |
+
stream_contents[index] = buffer.getvalue()
|
| 84 |
+
|
| 85 |
+
async with await open_process(
|
| 86 |
+
command,
|
| 87 |
+
stdin=PIPE if input else DEVNULL,
|
| 88 |
+
stdout=stdout,
|
| 89 |
+
stderr=stderr,
|
| 90 |
+
cwd=cwd,
|
| 91 |
+
env=env,
|
| 92 |
+
startupinfo=startupinfo,
|
| 93 |
+
creationflags=creationflags,
|
| 94 |
+
start_new_session=start_new_session,
|
| 95 |
+
pass_fds=pass_fds,
|
| 96 |
+
user=user,
|
| 97 |
+
group=group,
|
| 98 |
+
extra_groups=extra_groups,
|
| 99 |
+
umask=umask,
|
| 100 |
+
) as process:
|
| 101 |
+
stream_contents: list[bytes | None] = [None, None]
|
| 102 |
+
async with create_task_group() as tg:
|
| 103 |
+
if process.stdout:
|
| 104 |
+
tg.start_soon(drain_stream, process.stdout, 0)
|
| 105 |
+
|
| 106 |
+
if process.stderr:
|
| 107 |
+
tg.start_soon(drain_stream, process.stderr, 1)
|
| 108 |
+
|
| 109 |
+
if process.stdin and input:
|
| 110 |
+
await process.stdin.send(input)
|
| 111 |
+
await process.stdin.aclose()
|
| 112 |
+
|
| 113 |
+
await process.wait()
|
| 114 |
+
|
| 115 |
+
output, errors = stream_contents
|
| 116 |
+
if check and process.returncode != 0:
|
| 117 |
+
raise CalledProcessError(cast(int, process.returncode), command, output, errors)
|
| 118 |
+
|
| 119 |
+
return CompletedProcess(command, cast(int, process.returncode), output, errors)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
async def open_process(
|
| 123 |
+
command: StrOrBytesPath | Sequence[StrOrBytesPath],
|
| 124 |
+
*,
|
| 125 |
+
stdin: int | IO[Any] | None = PIPE,
|
| 126 |
+
stdout: int | IO[Any] | None = PIPE,
|
| 127 |
+
stderr: int | IO[Any] | None = PIPE,
|
| 128 |
+
cwd: StrOrBytesPath | None = None,
|
| 129 |
+
env: Mapping[str, str] | None = None,
|
| 130 |
+
startupinfo: Any = None,
|
| 131 |
+
creationflags: int = 0,
|
| 132 |
+
start_new_session: bool = False,
|
| 133 |
+
pass_fds: Sequence[int] = (),
|
| 134 |
+
user: str | int | None = None,
|
| 135 |
+
group: str | int | None = None,
|
| 136 |
+
extra_groups: Iterable[str | int] | None = None,
|
| 137 |
+
umask: int = -1,
|
| 138 |
+
) -> Process:
|
| 139 |
+
"""
|
| 140 |
+
Start an external command in a subprocess.
|
| 141 |
+
|
| 142 |
+
.. seealso:: :class:`subprocess.Popen`
|
| 143 |
+
|
| 144 |
+
:param command: either a string to pass to the shell, or an iterable of strings
|
| 145 |
+
containing the executable name or path and its arguments
|
| 146 |
+
:param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a
|
| 147 |
+
file-like object, or ``None``
|
| 148 |
+
:param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
|
| 149 |
+
a file-like object, or ``None``
|
| 150 |
+
:param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
|
| 151 |
+
:data:`subprocess.STDOUT`, a file-like object, or ``None``
|
| 152 |
+
:param cwd: If not ``None``, the working directory is changed before executing
|
| 153 |
+
:param env: If env is not ``None``, it must be a mapping that defines the
|
| 154 |
+
environment variables for the new process
|
| 155 |
+
:param creationflags: flags that can be used to control the creation of the
|
| 156 |
+
subprocess (see :class:`subprocess.Popen` for the specifics)
|
| 157 |
+
:param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
|
| 158 |
+
to specify process startup parameters (Windows only)
|
| 159 |
+
:param start_new_session: if ``true`` the setsid() system call will be made in the
|
| 160 |
+
child process prior to the execution of the subprocess. (POSIX only)
|
| 161 |
+
:param pass_fds: sequence of file descriptors to keep open between the parent and
|
| 162 |
+
child processes. (POSIX only)
|
| 163 |
+
:param user: effective user to run the process as (POSIX only)
|
| 164 |
+
:param group: effective group to run the process as (POSIX only)
|
| 165 |
+
:param extra_groups: supplementary groups to set in the subprocess (POSIX only)
|
| 166 |
+
:param umask: if not negative, this umask is applied in the child process before
|
| 167 |
+
running the given command (POSIX only)
|
| 168 |
+
:return: an asynchronous process object
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
kwargs: dict[str, Any] = {}
|
| 172 |
+
if user is not None:
|
| 173 |
+
kwargs["user"] = user
|
| 174 |
+
|
| 175 |
+
if group is not None:
|
| 176 |
+
kwargs["group"] = group
|
| 177 |
+
|
| 178 |
+
if extra_groups is not None:
|
| 179 |
+
kwargs["extra_groups"] = group
|
| 180 |
+
|
| 181 |
+
if umask >= 0:
|
| 182 |
+
kwargs["umask"] = umask
|
| 183 |
+
|
| 184 |
+
return await get_async_backend().open_process(
|
| 185 |
+
command,
|
| 186 |
+
stdin=stdin,
|
| 187 |
+
stdout=stdout,
|
| 188 |
+
stderr=stderr,
|
| 189 |
+
cwd=cwd,
|
| 190 |
+
env=env,
|
| 191 |
+
startupinfo=startupinfo,
|
| 192 |
+
creationflags=creationflags,
|
| 193 |
+
start_new_session=start_new_session,
|
| 194 |
+
pass_fds=pass_fds,
|
| 195 |
+
**kwargs,
|
| 196 |
+
)
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_synchronization.py
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from collections import deque
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
|
| 8 |
+
from sniffio import AsyncLibraryNotFoundError
|
| 9 |
+
|
| 10 |
+
from ..lowlevel import checkpoint
|
| 11 |
+
from ._eventloop import get_async_backend
|
| 12 |
+
from ._exceptions import BusyResourceError
|
| 13 |
+
from ._tasks import CancelScope
|
| 14 |
+
from ._testing import TaskInfo, get_current_task
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class EventStatistics:
|
| 19 |
+
"""
|
| 20 |
+
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait`
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
tasks_waiting: int
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class CapacityLimiterStatistics:
|
| 28 |
+
"""
|
| 29 |
+
:ivar int borrowed_tokens: number of tokens currently borrowed by tasks
|
| 30 |
+
:ivar float total_tokens: total number of available tokens
|
| 31 |
+
:ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from
|
| 32 |
+
this limiter
|
| 33 |
+
:ivar int tasks_waiting: number of tasks waiting on
|
| 34 |
+
:meth:`~.CapacityLimiter.acquire` or
|
| 35 |
+
:meth:`~.CapacityLimiter.acquire_on_behalf_of`
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
borrowed_tokens: int
|
| 39 |
+
total_tokens: float
|
| 40 |
+
borrowers: tuple[object, ...]
|
| 41 |
+
tasks_waiting: int
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass(frozen=True)
|
| 45 |
+
class LockStatistics:
|
| 46 |
+
"""
|
| 47 |
+
:ivar bool locked: flag indicating if this lock is locked or not
|
| 48 |
+
:ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the
|
| 49 |
+
lock is not held by any task)
|
| 50 |
+
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire`
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
locked: bool
|
| 54 |
+
owner: TaskInfo | None
|
| 55 |
+
tasks_waiting: int
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=True)
|
| 59 |
+
class ConditionStatistics:
|
| 60 |
+
"""
|
| 61 |
+
:ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait`
|
| 62 |
+
:ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying
|
| 63 |
+
:class:`~.Lock`
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
tasks_waiting: int
|
| 67 |
+
lock_statistics: LockStatistics
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(frozen=True)
|
| 71 |
+
class SemaphoreStatistics:
|
| 72 |
+
"""
|
| 73 |
+
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire`
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
tasks_waiting: int
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class Event:
|
| 81 |
+
def __new__(cls) -> Event:
|
| 82 |
+
try:
|
| 83 |
+
return get_async_backend().create_event()
|
| 84 |
+
except AsyncLibraryNotFoundError:
|
| 85 |
+
return EventAdapter()
|
| 86 |
+
|
| 87 |
+
def set(self) -> None:
|
| 88 |
+
"""Set the flag, notifying all listeners."""
|
| 89 |
+
raise NotImplementedError
|
| 90 |
+
|
| 91 |
+
def is_set(self) -> bool:
|
| 92 |
+
"""Return ``True`` if the flag is set, ``False`` if not."""
|
| 93 |
+
raise NotImplementedError
|
| 94 |
+
|
| 95 |
+
async def wait(self) -> None:
|
| 96 |
+
"""
|
| 97 |
+
Wait until the flag has been set.
|
| 98 |
+
|
| 99 |
+
If the flag has already been set when this method is called, it returns
|
| 100 |
+
immediately.
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
raise NotImplementedError
|
| 104 |
+
|
| 105 |
+
def statistics(self) -> EventStatistics:
|
| 106 |
+
"""Return statistics about the current state of this event."""
|
| 107 |
+
raise NotImplementedError
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class EventAdapter(Event):
|
| 111 |
+
_internal_event: Event | None = None
|
| 112 |
+
_is_set: bool = False
|
| 113 |
+
|
| 114 |
+
def __new__(cls) -> EventAdapter:
|
| 115 |
+
return object.__new__(cls)
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def _event(self) -> Event:
|
| 119 |
+
if self._internal_event is None:
|
| 120 |
+
self._internal_event = get_async_backend().create_event()
|
| 121 |
+
if self._is_set:
|
| 122 |
+
self._internal_event.set()
|
| 123 |
+
|
| 124 |
+
return self._internal_event
|
| 125 |
+
|
| 126 |
+
def set(self) -> None:
|
| 127 |
+
if self._internal_event is None:
|
| 128 |
+
self._is_set = True
|
| 129 |
+
else:
|
| 130 |
+
self._event.set()
|
| 131 |
+
|
| 132 |
+
def is_set(self) -> bool:
|
| 133 |
+
if self._internal_event is None:
|
| 134 |
+
return self._is_set
|
| 135 |
+
|
| 136 |
+
return self._internal_event.is_set()
|
| 137 |
+
|
| 138 |
+
async def wait(self) -> None:
|
| 139 |
+
await self._event.wait()
|
| 140 |
+
|
| 141 |
+
def statistics(self) -> EventStatistics:
|
| 142 |
+
if self._internal_event is None:
|
| 143 |
+
return EventStatistics(tasks_waiting=0)
|
| 144 |
+
|
| 145 |
+
return self._internal_event.statistics()
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class Lock:
|
| 149 |
+
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
|
| 150 |
+
try:
|
| 151 |
+
return get_async_backend().create_lock(fast_acquire=fast_acquire)
|
| 152 |
+
except AsyncLibraryNotFoundError:
|
| 153 |
+
return LockAdapter(fast_acquire=fast_acquire)
|
| 154 |
+
|
| 155 |
+
async def __aenter__(self) -> None:
|
| 156 |
+
await self.acquire()
|
| 157 |
+
|
| 158 |
+
async def __aexit__(
|
| 159 |
+
self,
|
| 160 |
+
exc_type: type[BaseException] | None,
|
| 161 |
+
exc_val: BaseException | None,
|
| 162 |
+
exc_tb: TracebackType | None,
|
| 163 |
+
) -> None:
|
| 164 |
+
self.release()
|
| 165 |
+
|
| 166 |
+
async def acquire(self) -> None:
|
| 167 |
+
"""Acquire the lock."""
|
| 168 |
+
raise NotImplementedError
|
| 169 |
+
|
| 170 |
+
def acquire_nowait(self) -> None:
|
| 171 |
+
"""
|
| 172 |
+
Acquire the lock, without blocking.
|
| 173 |
+
|
| 174 |
+
:raises ~anyio.WouldBlock: if the operation would block
|
| 175 |
+
|
| 176 |
+
"""
|
| 177 |
+
raise NotImplementedError
|
| 178 |
+
|
| 179 |
+
def release(self) -> None:
|
| 180 |
+
"""Release the lock."""
|
| 181 |
+
raise NotImplementedError
|
| 182 |
+
|
| 183 |
+
def locked(self) -> bool:
|
| 184 |
+
"""Return True if the lock is currently held."""
|
| 185 |
+
raise NotImplementedError
|
| 186 |
+
|
| 187 |
+
def statistics(self) -> LockStatistics:
|
| 188 |
+
"""
|
| 189 |
+
Return statistics about the current state of this lock.
|
| 190 |
+
|
| 191 |
+
.. versionadded:: 3.0
|
| 192 |
+
"""
|
| 193 |
+
raise NotImplementedError
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class LockAdapter(Lock):
|
| 197 |
+
_internal_lock: Lock | None = None
|
| 198 |
+
|
| 199 |
+
def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter:
|
| 200 |
+
return object.__new__(cls)
|
| 201 |
+
|
| 202 |
+
def __init__(self, *, fast_acquire: bool = False):
|
| 203 |
+
self._fast_acquire = fast_acquire
|
| 204 |
+
|
| 205 |
+
@property
|
| 206 |
+
def _lock(self) -> Lock:
|
| 207 |
+
if self._internal_lock is None:
|
| 208 |
+
self._internal_lock = get_async_backend().create_lock(
|
| 209 |
+
fast_acquire=self._fast_acquire
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
return self._internal_lock
|
| 213 |
+
|
| 214 |
+
async def __aenter__(self) -> None:
|
| 215 |
+
await self._lock.acquire()
|
| 216 |
+
|
| 217 |
+
async def __aexit__(
|
| 218 |
+
self,
|
| 219 |
+
exc_type: type[BaseException] | None,
|
| 220 |
+
exc_val: BaseException | None,
|
| 221 |
+
exc_tb: TracebackType | None,
|
| 222 |
+
) -> None:
|
| 223 |
+
if self._internal_lock is not None:
|
| 224 |
+
self._internal_lock.release()
|
| 225 |
+
|
| 226 |
+
async def acquire(self) -> None:
|
| 227 |
+
"""Acquire the lock."""
|
| 228 |
+
await self._lock.acquire()
|
| 229 |
+
|
| 230 |
+
def acquire_nowait(self) -> None:
|
| 231 |
+
"""
|
| 232 |
+
Acquire the lock, without blocking.
|
| 233 |
+
|
| 234 |
+
:raises ~anyio.WouldBlock: if the operation would block
|
| 235 |
+
|
| 236 |
+
"""
|
| 237 |
+
self._lock.acquire_nowait()
|
| 238 |
+
|
| 239 |
+
def release(self) -> None:
|
| 240 |
+
"""Release the lock."""
|
| 241 |
+
self._lock.release()
|
| 242 |
+
|
| 243 |
+
def locked(self) -> bool:
|
| 244 |
+
"""Return True if the lock is currently held."""
|
| 245 |
+
return self._lock.locked()
|
| 246 |
+
|
| 247 |
+
def statistics(self) -> LockStatistics:
|
| 248 |
+
"""
|
| 249 |
+
Return statistics about the current state of this lock.
|
| 250 |
+
|
| 251 |
+
.. versionadded:: 3.0
|
| 252 |
+
|
| 253 |
+
"""
|
| 254 |
+
if self._internal_lock is None:
|
| 255 |
+
return LockStatistics(False, None, 0)
|
| 256 |
+
|
| 257 |
+
return self._internal_lock.statistics()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class Condition:
|
| 261 |
+
_owner_task: TaskInfo | None = None
|
| 262 |
+
|
| 263 |
+
def __init__(self, lock: Lock | None = None):
|
| 264 |
+
self._lock = lock or Lock()
|
| 265 |
+
self._waiters: deque[Event] = deque()
|
| 266 |
+
|
| 267 |
+
async def __aenter__(self) -> None:
|
| 268 |
+
await self.acquire()
|
| 269 |
+
|
| 270 |
+
async def __aexit__(
|
| 271 |
+
self,
|
| 272 |
+
exc_type: type[BaseException] | None,
|
| 273 |
+
exc_val: BaseException | None,
|
| 274 |
+
exc_tb: TracebackType | None,
|
| 275 |
+
) -> None:
|
| 276 |
+
self.release()
|
| 277 |
+
|
| 278 |
+
def _check_acquired(self) -> None:
|
| 279 |
+
if self._owner_task != get_current_task():
|
| 280 |
+
raise RuntimeError("The current task is not holding the underlying lock")
|
| 281 |
+
|
| 282 |
+
async def acquire(self) -> None:
|
| 283 |
+
"""Acquire the underlying lock."""
|
| 284 |
+
await self._lock.acquire()
|
| 285 |
+
self._owner_task = get_current_task()
|
| 286 |
+
|
| 287 |
+
def acquire_nowait(self) -> None:
|
| 288 |
+
"""
|
| 289 |
+
Acquire the underlying lock, without blocking.
|
| 290 |
+
|
| 291 |
+
:raises ~anyio.WouldBlock: if the operation would block
|
| 292 |
+
|
| 293 |
+
"""
|
| 294 |
+
self._lock.acquire_nowait()
|
| 295 |
+
self._owner_task = get_current_task()
|
| 296 |
+
|
| 297 |
+
def release(self) -> None:
|
| 298 |
+
"""Release the underlying lock."""
|
| 299 |
+
self._lock.release()
|
| 300 |
+
|
| 301 |
+
def locked(self) -> bool:
|
| 302 |
+
"""Return True if the lock is set."""
|
| 303 |
+
return self._lock.locked()
|
| 304 |
+
|
| 305 |
+
def notify(self, n: int = 1) -> None:
|
| 306 |
+
"""Notify exactly n listeners."""
|
| 307 |
+
self._check_acquired()
|
| 308 |
+
for _ in range(n):
|
| 309 |
+
try:
|
| 310 |
+
event = self._waiters.popleft()
|
| 311 |
+
except IndexError:
|
| 312 |
+
break
|
| 313 |
+
|
| 314 |
+
event.set()
|
| 315 |
+
|
| 316 |
+
def notify_all(self) -> None:
|
| 317 |
+
"""Notify all the listeners."""
|
| 318 |
+
self._check_acquired()
|
| 319 |
+
for event in self._waiters:
|
| 320 |
+
event.set()
|
| 321 |
+
|
| 322 |
+
self._waiters.clear()
|
| 323 |
+
|
| 324 |
+
async def wait(self) -> None:
|
| 325 |
+
"""Wait for a notification."""
|
| 326 |
+
await checkpoint()
|
| 327 |
+
event = Event()
|
| 328 |
+
self._waiters.append(event)
|
| 329 |
+
self.release()
|
| 330 |
+
try:
|
| 331 |
+
await event.wait()
|
| 332 |
+
except BaseException:
|
| 333 |
+
if not event.is_set():
|
| 334 |
+
self._waiters.remove(event)
|
| 335 |
+
|
| 336 |
+
raise
|
| 337 |
+
finally:
|
| 338 |
+
with CancelScope(shield=True):
|
| 339 |
+
await self.acquire()
|
| 340 |
+
|
| 341 |
+
def statistics(self) -> ConditionStatistics:
|
| 342 |
+
"""
|
| 343 |
+
Return statistics about the current state of this condition.
|
| 344 |
+
|
| 345 |
+
.. versionadded:: 3.0
|
| 346 |
+
"""
|
| 347 |
+
return ConditionStatistics(len(self._waiters), self._lock.statistics())
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class Semaphore:
|
| 351 |
+
def __new__(
|
| 352 |
+
cls,
|
| 353 |
+
initial_value: int,
|
| 354 |
+
*,
|
| 355 |
+
max_value: int | None = None,
|
| 356 |
+
fast_acquire: bool = False,
|
| 357 |
+
) -> Semaphore:
|
| 358 |
+
try:
|
| 359 |
+
return get_async_backend().create_semaphore(
|
| 360 |
+
initial_value, max_value=max_value, fast_acquire=fast_acquire
|
| 361 |
+
)
|
| 362 |
+
except AsyncLibraryNotFoundError:
|
| 363 |
+
return SemaphoreAdapter(initial_value, max_value=max_value)
|
| 364 |
+
|
| 365 |
+
def __init__(
|
| 366 |
+
self,
|
| 367 |
+
initial_value: int,
|
| 368 |
+
*,
|
| 369 |
+
max_value: int | None = None,
|
| 370 |
+
fast_acquire: bool = False,
|
| 371 |
+
):
|
| 372 |
+
if not isinstance(initial_value, int):
|
| 373 |
+
raise TypeError("initial_value must be an integer")
|
| 374 |
+
if initial_value < 0:
|
| 375 |
+
raise ValueError("initial_value must be >= 0")
|
| 376 |
+
if max_value is not None:
|
| 377 |
+
if not isinstance(max_value, int):
|
| 378 |
+
raise TypeError("max_value must be an integer or None")
|
| 379 |
+
if max_value < initial_value:
|
| 380 |
+
raise ValueError(
|
| 381 |
+
"max_value must be equal to or higher than initial_value"
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
self._fast_acquire = fast_acquire
|
| 385 |
+
|
| 386 |
+
async def __aenter__(self) -> Semaphore:
|
| 387 |
+
await self.acquire()
|
| 388 |
+
return self
|
| 389 |
+
|
| 390 |
+
async def __aexit__(
|
| 391 |
+
self,
|
| 392 |
+
exc_type: type[BaseException] | None,
|
| 393 |
+
exc_val: BaseException | None,
|
| 394 |
+
exc_tb: TracebackType | None,
|
| 395 |
+
) -> None:
|
| 396 |
+
self.release()
|
| 397 |
+
|
| 398 |
+
async def acquire(self) -> None:
|
| 399 |
+
"""Decrement the semaphore value, blocking if necessary."""
|
| 400 |
+
raise NotImplementedError
|
| 401 |
+
|
| 402 |
+
def acquire_nowait(self) -> None:
|
| 403 |
+
"""
|
| 404 |
+
Acquire the underlying lock, without blocking.
|
| 405 |
+
|
| 406 |
+
:raises ~anyio.WouldBlock: if the operation would block
|
| 407 |
+
|
| 408 |
+
"""
|
| 409 |
+
raise NotImplementedError
|
| 410 |
+
|
| 411 |
+
def release(self) -> None:
|
| 412 |
+
"""Increment the semaphore value."""
|
| 413 |
+
raise NotImplementedError
|
| 414 |
+
|
| 415 |
+
@property
|
| 416 |
+
def value(self) -> int:
|
| 417 |
+
"""The current value of the semaphore."""
|
| 418 |
+
raise NotImplementedError
|
| 419 |
+
|
| 420 |
+
@property
|
| 421 |
+
def max_value(self) -> int | None:
|
| 422 |
+
"""The maximum value of the semaphore."""
|
| 423 |
+
raise NotImplementedError
|
| 424 |
+
|
| 425 |
+
def statistics(self) -> SemaphoreStatistics:
|
| 426 |
+
"""
|
| 427 |
+
Return statistics about the current state of this semaphore.
|
| 428 |
+
|
| 429 |
+
.. versionadded:: 3.0
|
| 430 |
+
"""
|
| 431 |
+
raise NotImplementedError
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class SemaphoreAdapter(Semaphore):
|
| 435 |
+
_internal_semaphore: Semaphore | None = None
|
| 436 |
+
|
| 437 |
+
def __new__(
|
| 438 |
+
cls,
|
| 439 |
+
initial_value: int,
|
| 440 |
+
*,
|
| 441 |
+
max_value: int | None = None,
|
| 442 |
+
fast_acquire: bool = False,
|
| 443 |
+
) -> SemaphoreAdapter:
|
| 444 |
+
return object.__new__(cls)
|
| 445 |
+
|
| 446 |
+
def __init__(
|
| 447 |
+
self,
|
| 448 |
+
initial_value: int,
|
| 449 |
+
*,
|
| 450 |
+
max_value: int | None = None,
|
| 451 |
+
fast_acquire: bool = False,
|
| 452 |
+
) -> None:
|
| 453 |
+
super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
|
| 454 |
+
self._initial_value = initial_value
|
| 455 |
+
self._max_value = max_value
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def _semaphore(self) -> Semaphore:
|
| 459 |
+
if self._internal_semaphore is None:
|
| 460 |
+
self._internal_semaphore = get_async_backend().create_semaphore(
|
| 461 |
+
self._initial_value, max_value=self._max_value
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
return self._internal_semaphore
|
| 465 |
+
|
| 466 |
+
async def acquire(self) -> None:
|
| 467 |
+
await self._semaphore.acquire()
|
| 468 |
+
|
| 469 |
+
def acquire_nowait(self) -> None:
|
| 470 |
+
self._semaphore.acquire_nowait()
|
| 471 |
+
|
| 472 |
+
def release(self) -> None:
|
| 473 |
+
self._semaphore.release()
|
| 474 |
+
|
| 475 |
+
@property
|
| 476 |
+
def value(self) -> int:
|
| 477 |
+
if self._internal_semaphore is None:
|
| 478 |
+
return self._initial_value
|
| 479 |
+
|
| 480 |
+
return self._semaphore.value
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def max_value(self) -> int | None:
|
| 484 |
+
return self._max_value
|
| 485 |
+
|
| 486 |
+
def statistics(self) -> SemaphoreStatistics:
|
| 487 |
+
if self._internal_semaphore is None:
|
| 488 |
+
return SemaphoreStatistics(tasks_waiting=0)
|
| 489 |
+
|
| 490 |
+
return self._semaphore.statistics()
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
class CapacityLimiter:
|
| 494 |
+
def __new__(cls, total_tokens: float) -> CapacityLimiter:
|
| 495 |
+
try:
|
| 496 |
+
return get_async_backend().create_capacity_limiter(total_tokens)
|
| 497 |
+
except AsyncLibraryNotFoundError:
|
| 498 |
+
return CapacityLimiterAdapter(total_tokens)
|
| 499 |
+
|
| 500 |
+
async def __aenter__(self) -> None:
|
| 501 |
+
raise NotImplementedError
|
| 502 |
+
|
| 503 |
+
async def __aexit__(
|
| 504 |
+
self,
|
| 505 |
+
exc_type: type[BaseException] | None,
|
| 506 |
+
exc_val: BaseException | None,
|
| 507 |
+
exc_tb: TracebackType | None,
|
| 508 |
+
) -> bool | None:
|
| 509 |
+
raise NotImplementedError
|
| 510 |
+
|
| 511 |
+
@property
|
| 512 |
+
def total_tokens(self) -> float:
|
| 513 |
+
"""
|
| 514 |
+
The total number of tokens available for borrowing.
|
| 515 |
+
|
| 516 |
+
This is a read-write property. If the total number of tokens is increased, the
|
| 517 |
+
proportionate number of tasks waiting on this limiter will be granted their
|
| 518 |
+
tokens.
|
| 519 |
+
|
| 520 |
+
.. versionchanged:: 3.0
|
| 521 |
+
The property is now writable.
|
| 522 |
+
|
| 523 |
+
"""
|
| 524 |
+
raise NotImplementedError
|
| 525 |
+
|
| 526 |
+
@total_tokens.setter
|
| 527 |
+
def total_tokens(self, value: float) -> None:
|
| 528 |
+
raise NotImplementedError
|
| 529 |
+
|
| 530 |
+
@property
|
| 531 |
+
def borrowed_tokens(self) -> int:
|
| 532 |
+
"""The number of tokens that have currently been borrowed."""
|
| 533 |
+
raise NotImplementedError
|
| 534 |
+
|
| 535 |
+
@property
|
| 536 |
+
def available_tokens(self) -> float:
|
| 537 |
+
"""The number of tokens currently available to be borrowed"""
|
| 538 |
+
raise NotImplementedError
|
| 539 |
+
|
| 540 |
+
def acquire_nowait(self) -> None:
|
| 541 |
+
"""
|
| 542 |
+
Acquire a token for the current task without waiting for one to become
|
| 543 |
+
available.
|
| 544 |
+
|
| 545 |
+
:raises ~anyio.WouldBlock: if there are no tokens available for borrowing
|
| 546 |
+
|
| 547 |
+
"""
|
| 548 |
+
raise NotImplementedError
|
| 549 |
+
|
| 550 |
+
def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
|
| 551 |
+
"""
|
| 552 |
+
Acquire a token without waiting for one to become available.
|
| 553 |
+
|
| 554 |
+
:param borrower: the entity borrowing a token
|
| 555 |
+
:raises ~anyio.WouldBlock: if there are no tokens available for borrowing
|
| 556 |
+
|
| 557 |
+
"""
|
| 558 |
+
raise NotImplementedError
|
| 559 |
+
|
| 560 |
+
async def acquire(self) -> None:
|
| 561 |
+
"""
|
| 562 |
+
Acquire a token for the current task, waiting if necessary for one to become
|
| 563 |
+
available.
|
| 564 |
+
|
| 565 |
+
"""
|
| 566 |
+
raise NotImplementedError
|
| 567 |
+
|
| 568 |
+
async def acquire_on_behalf_of(self, borrower: object) -> None:
|
| 569 |
+
"""
|
| 570 |
+
Acquire a token, waiting if necessary for one to become available.
|
| 571 |
+
|
| 572 |
+
:param borrower: the entity borrowing a token
|
| 573 |
+
|
| 574 |
+
"""
|
| 575 |
+
raise NotImplementedError
|
| 576 |
+
|
| 577 |
+
def release(self) -> None:
|
| 578 |
+
"""
|
| 579 |
+
Release the token held by the current task.
|
| 580 |
+
|
| 581 |
+
:raises RuntimeError: if the current task has not borrowed a token from this
|
| 582 |
+
limiter.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
raise NotImplementedError
|
| 586 |
+
|
| 587 |
+
def release_on_behalf_of(self, borrower: object) -> None:
|
| 588 |
+
"""
|
| 589 |
+
Release the token held by the given borrower.
|
| 590 |
+
|
| 591 |
+
:raises RuntimeError: if the borrower has not borrowed a token from this
|
| 592 |
+
limiter.
|
| 593 |
+
|
| 594 |
+
"""
|
| 595 |
+
raise NotImplementedError
|
| 596 |
+
|
| 597 |
+
def statistics(self) -> CapacityLimiterStatistics:
|
| 598 |
+
"""
|
| 599 |
+
Return statistics about the current state of this limiter.
|
| 600 |
+
|
| 601 |
+
.. versionadded:: 3.0
|
| 602 |
+
|
| 603 |
+
"""
|
| 604 |
+
raise NotImplementedError
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class CapacityLimiterAdapter(CapacityLimiter):
|
| 608 |
+
_internal_limiter: CapacityLimiter | None = None
|
| 609 |
+
|
| 610 |
+
def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter:
|
| 611 |
+
return object.__new__(cls)
|
| 612 |
+
|
| 613 |
+
def __init__(self, total_tokens: float) -> None:
|
| 614 |
+
self.total_tokens = total_tokens
|
| 615 |
+
|
| 616 |
+
@property
|
| 617 |
+
def _limiter(self) -> CapacityLimiter:
|
| 618 |
+
if self._internal_limiter is None:
|
| 619 |
+
self._internal_limiter = get_async_backend().create_capacity_limiter(
|
| 620 |
+
self._total_tokens
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
return self._internal_limiter
|
| 624 |
+
|
| 625 |
+
async def __aenter__(self) -> None:
|
| 626 |
+
await self._limiter.__aenter__()
|
| 627 |
+
|
| 628 |
+
async def __aexit__(
|
| 629 |
+
self,
|
| 630 |
+
exc_type: type[BaseException] | None,
|
| 631 |
+
exc_val: BaseException | None,
|
| 632 |
+
exc_tb: TracebackType | None,
|
| 633 |
+
) -> bool | None:
|
| 634 |
+
return await self._limiter.__aexit__(exc_type, exc_val, exc_tb)
|
| 635 |
+
|
| 636 |
+
@property
|
| 637 |
+
def total_tokens(self) -> float:
|
| 638 |
+
if self._internal_limiter is None:
|
| 639 |
+
return self._total_tokens
|
| 640 |
+
|
| 641 |
+
return self._internal_limiter.total_tokens
|
| 642 |
+
|
| 643 |
+
@total_tokens.setter
|
| 644 |
+
def total_tokens(self, value: float) -> None:
|
| 645 |
+
if not isinstance(value, int) and value is not math.inf:
|
| 646 |
+
raise TypeError("total_tokens must be an int or math.inf")
|
| 647 |
+
elif value < 1:
|
| 648 |
+
raise ValueError("total_tokens must be >= 1")
|
| 649 |
+
|
| 650 |
+
if self._internal_limiter is None:
|
| 651 |
+
self._total_tokens = value
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
self._limiter.total_tokens = value
|
| 655 |
+
|
| 656 |
+
@property
|
| 657 |
+
def borrowed_tokens(self) -> int:
|
| 658 |
+
if self._internal_limiter is None:
|
| 659 |
+
return 0
|
| 660 |
+
|
| 661 |
+
return self._internal_limiter.borrowed_tokens
|
| 662 |
+
|
| 663 |
+
@property
|
| 664 |
+
def available_tokens(self) -> float:
|
| 665 |
+
if self._internal_limiter is None:
|
| 666 |
+
return self._total_tokens
|
| 667 |
+
|
| 668 |
+
return self._internal_limiter.available_tokens
|
| 669 |
+
|
| 670 |
+
def acquire_nowait(self) -> None:
|
| 671 |
+
self._limiter.acquire_nowait()
|
| 672 |
+
|
| 673 |
+
def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
|
| 674 |
+
self._limiter.acquire_on_behalf_of_nowait(borrower)
|
| 675 |
+
|
| 676 |
+
async def acquire(self) -> None:
|
| 677 |
+
await self._limiter.acquire()
|
| 678 |
+
|
| 679 |
+
async def acquire_on_behalf_of(self, borrower: object) -> None:
|
| 680 |
+
await self._limiter.acquire_on_behalf_of(borrower)
|
| 681 |
+
|
| 682 |
+
def release(self) -> None:
|
| 683 |
+
self._limiter.release()
|
| 684 |
+
|
| 685 |
+
def release_on_behalf_of(self, borrower: object) -> None:
|
| 686 |
+
self._limiter.release_on_behalf_of(borrower)
|
| 687 |
+
|
| 688 |
+
def statistics(self) -> CapacityLimiterStatistics:
|
| 689 |
+
if self._internal_limiter is None:
|
| 690 |
+
return CapacityLimiterStatistics(
|
| 691 |
+
borrowed_tokens=0,
|
| 692 |
+
total_tokens=self.total_tokens,
|
| 693 |
+
borrowers=(),
|
| 694 |
+
tasks_waiting=0,
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
return self._internal_limiter.statistics()
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
class ResourceGuard:
|
| 701 |
+
"""
|
| 702 |
+
A context manager for ensuring that a resource is only used by a single task at a
|
| 703 |
+
time.
|
| 704 |
+
|
| 705 |
+
Entering this context manager while the previous has not exited it yet will trigger
|
| 706 |
+
:exc:`BusyResourceError`.
|
| 707 |
+
|
| 708 |
+
:param action: the action to guard against (visible in the :exc:`BusyResourceError`
|
| 709 |
+
when triggered, e.g. "Another task is already {action} this resource")
|
| 710 |
+
|
| 711 |
+
.. versionadded:: 4.1
|
| 712 |
+
"""
|
| 713 |
+
|
| 714 |
+
__slots__ = "action", "_guarded"
|
| 715 |
+
|
| 716 |
+
def __init__(self, action: str = "using"):
|
| 717 |
+
self.action: str = action
|
| 718 |
+
self._guarded = False
|
| 719 |
+
|
| 720 |
+
def __enter__(self) -> None:
|
| 721 |
+
if self._guarded:
|
| 722 |
+
raise BusyResourceError(self.action)
|
| 723 |
+
|
| 724 |
+
self._guarded = True
|
| 725 |
+
|
| 726 |
+
def __exit__(
|
| 727 |
+
self,
|
| 728 |
+
exc_type: type[BaseException] | None,
|
| 729 |
+
exc_val: BaseException | None,
|
| 730 |
+
exc_tb: TracebackType | None,
|
| 731 |
+
) -> bool | None:
|
| 732 |
+
self._guarded = False
|
| 733 |
+
return None
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_tasks.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from collections.abc import Generator
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
|
| 8 |
+
from ..abc._tasks import TaskGroup, TaskStatus
|
| 9 |
+
from ._eventloop import get_async_backend
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _IgnoredTaskStatus(TaskStatus[object]):
|
| 13 |
+
def started(self, value: object = None) -> None:
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
TASK_STATUS_IGNORED = _IgnoredTaskStatus()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class CancelScope:
|
| 21 |
+
"""
|
| 22 |
+
Wraps a unit of work that can be made separately cancellable.
|
| 23 |
+
|
| 24 |
+
:param deadline: The time (clock value) when this scope is cancelled automatically
|
| 25 |
+
:param shield: ``True`` to shield the cancel scope from external cancellation
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __new__(
|
| 29 |
+
cls, *, deadline: float = math.inf, shield: bool = False
|
| 30 |
+
) -> CancelScope:
|
| 31 |
+
return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline)
|
| 32 |
+
|
| 33 |
+
def cancel(self) -> None:
|
| 34 |
+
"""Cancel this scope immediately."""
|
| 35 |
+
raise NotImplementedError
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def deadline(self) -> float:
|
| 39 |
+
"""
|
| 40 |
+
The time (clock value) when this scope is cancelled automatically.
|
| 41 |
+
|
| 42 |
+
Will be ``float('inf')`` if no timeout has been set.
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
raise NotImplementedError
|
| 46 |
+
|
| 47 |
+
@deadline.setter
|
| 48 |
+
def deadline(self, value: float) -> None:
|
| 49 |
+
raise NotImplementedError
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def cancel_called(self) -> bool:
|
| 53 |
+
"""``True`` if :meth:`cancel` has been called."""
|
| 54 |
+
raise NotImplementedError
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def cancelled_caught(self) -> bool:
|
| 58 |
+
"""
|
| 59 |
+
``True`` if this scope suppressed a cancellation exception it itself raised.
|
| 60 |
+
|
| 61 |
+
This is typically used to check if any work was interrupted, or to see if the
|
| 62 |
+
scope was cancelled due to its deadline being reached. The value will, however,
|
| 63 |
+
only be ``True`` if the cancellation was triggered by the scope itself (and not
|
| 64 |
+
an outer scope).
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
raise NotImplementedError
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def shield(self) -> bool:
|
| 71 |
+
"""
|
| 72 |
+
``True`` if this scope is shielded from external cancellation.
|
| 73 |
+
|
| 74 |
+
While a scope is shielded, it will not receive cancellations from outside.
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
@shield.setter
|
| 80 |
+
def shield(self, value: bool) -> None:
|
| 81 |
+
raise NotImplementedError
|
| 82 |
+
|
| 83 |
+
def __enter__(self) -> CancelScope:
|
| 84 |
+
raise NotImplementedError
|
| 85 |
+
|
| 86 |
+
def __exit__(
|
| 87 |
+
self,
|
| 88 |
+
exc_type: type[BaseException] | None,
|
| 89 |
+
exc_val: BaseException | None,
|
| 90 |
+
exc_tb: TracebackType | None,
|
| 91 |
+
) -> bool | None:
|
| 92 |
+
raise NotImplementedError
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@contextmanager
|
| 96 |
+
def fail_after(
|
| 97 |
+
delay: float | None, shield: bool = False
|
| 98 |
+
) -> Generator[CancelScope, None, None]:
|
| 99 |
+
"""
|
| 100 |
+
Create a context manager which raises a :class:`TimeoutError` if does not finish in
|
| 101 |
+
time.
|
| 102 |
+
|
| 103 |
+
:param delay: maximum allowed time (in seconds) before raising the exception, or
|
| 104 |
+
``None`` to disable the timeout
|
| 105 |
+
:param shield: ``True`` to shield the cancel scope from external cancellation
|
| 106 |
+
:return: a context manager that yields a cancel scope
|
| 107 |
+
:rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\]
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
current_time = get_async_backend().current_time
|
| 111 |
+
deadline = (current_time() + delay) if delay is not None else math.inf
|
| 112 |
+
with get_async_backend().create_cancel_scope(
|
| 113 |
+
deadline=deadline, shield=shield
|
| 114 |
+
) as cancel_scope:
|
| 115 |
+
yield cancel_scope
|
| 116 |
+
|
| 117 |
+
if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline:
|
| 118 |
+
raise TimeoutError
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def move_on_after(delay: float | None, shield: bool = False) -> CancelScope:
|
| 122 |
+
"""
|
| 123 |
+
Create a cancel scope with a deadline that expires after the given delay.
|
| 124 |
+
|
| 125 |
+
:param delay: maximum allowed time (in seconds) before exiting the context block, or
|
| 126 |
+
``None`` to disable the timeout
|
| 127 |
+
:param shield: ``True`` to shield the cancel scope from external cancellation
|
| 128 |
+
:return: a cancel scope
|
| 129 |
+
|
| 130 |
+
"""
|
| 131 |
+
deadline = (
|
| 132 |
+
(get_async_backend().current_time() + delay) if delay is not None else math.inf
|
| 133 |
+
)
|
| 134 |
+
return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def current_effective_deadline() -> float:
|
| 138 |
+
"""
|
| 139 |
+
Return the nearest deadline among all the cancel scopes effective for the current
|
| 140 |
+
task.
|
| 141 |
+
|
| 142 |
+
:return: a clock value from the event loop's internal clock (or ``float('inf')`` if
|
| 143 |
+
there is no deadline in effect, or ``float('-inf')`` if the current scope has
|
| 144 |
+
been cancelled)
|
| 145 |
+
:rtype: float
|
| 146 |
+
|
| 147 |
+
"""
|
| 148 |
+
return get_async_backend().current_effective_deadline()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def create_task_group() -> TaskGroup:
|
| 152 |
+
"""
|
| 153 |
+
Create a task group.
|
| 154 |
+
|
| 155 |
+
:return: a task group
|
| 156 |
+
|
| 157 |
+
"""
|
| 158 |
+
return get_async_backend().create_task_group()
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_testing.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Awaitable, Generator
|
| 4 |
+
from typing import Any, cast
|
| 5 |
+
|
| 6 |
+
from ._eventloop import get_async_backend
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TaskInfo:
|
| 10 |
+
"""
|
| 11 |
+
Represents an asynchronous task.
|
| 12 |
+
|
| 13 |
+
:ivar int id: the unique identifier of the task
|
| 14 |
+
:ivar parent_id: the identifier of the parent task, if any
|
| 15 |
+
:vartype parent_id: Optional[int]
|
| 16 |
+
:ivar str name: the description of the task (if any)
|
| 17 |
+
:ivar ~collections.abc.Coroutine coro: the coroutine object of the task
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
__slots__ = "_name", "id", "parent_id", "name", "coro"
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
id: int,
|
| 25 |
+
parent_id: int | None,
|
| 26 |
+
name: str | None,
|
| 27 |
+
coro: Generator[Any, Any, Any] | Awaitable[Any],
|
| 28 |
+
):
|
| 29 |
+
func = get_current_task
|
| 30 |
+
self._name = f"{func.__module__}.{func.__qualname__}"
|
| 31 |
+
self.id: int = id
|
| 32 |
+
self.parent_id: int | None = parent_id
|
| 33 |
+
self.name: str | None = name
|
| 34 |
+
self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro
|
| 35 |
+
|
| 36 |
+
def __eq__(self, other: object) -> bool:
|
| 37 |
+
if isinstance(other, TaskInfo):
|
| 38 |
+
return self.id == other.id
|
| 39 |
+
|
| 40 |
+
return NotImplemented
|
| 41 |
+
|
| 42 |
+
def __hash__(self) -> int:
|
| 43 |
+
return hash(self.id)
|
| 44 |
+
|
| 45 |
+
def __repr__(self) -> str:
|
| 46 |
+
return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})"
|
| 47 |
+
|
| 48 |
+
def has_pending_cancellation(self) -> bool:
|
| 49 |
+
"""
|
| 50 |
+
Return ``True`` if the task has a cancellation pending, ``False`` otherwise.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_current_task() -> TaskInfo:
|
| 57 |
+
"""
|
| 58 |
+
Return the current task.
|
| 59 |
+
|
| 60 |
+
:return: a representation of the current task
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
return get_async_backend().get_current_task()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_running_tasks() -> list[TaskInfo]:
|
| 67 |
+
"""
|
| 68 |
+
Return a list of running tasks in the current event loop.
|
| 69 |
+
|
| 70 |
+
:return: a list of task info objects
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
return cast("list[TaskInfo]", get_async_backend().get_running_tasks())
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
async def wait_all_tasks_blocked() -> None:
|
| 77 |
+
"""Wait until all other tasks are waiting for something."""
|
| 78 |
+
await get_async_backend().wait_all_tasks_blocked()
|
minigpt2/lib/python3.10/site-packages/anyio/_core/_typedattr.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Callable, Mapping
|
| 4 |
+
from typing import Any, TypeVar, final, overload
|
| 5 |
+
|
| 6 |
+
from ._exceptions import TypedAttributeLookupError
|
| 7 |
+
|
| 8 |
+
T_Attr = TypeVar("T_Attr")
|
| 9 |
+
T_Default = TypeVar("T_Default")
|
| 10 |
+
undefined = object()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def typed_attribute() -> Any:
|
| 14 |
+
"""Return a unique object, used to mark typed attributes."""
|
| 15 |
+
return object()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TypedAttributeSet:
|
| 19 |
+
"""
|
| 20 |
+
Superclass for typed attribute collections.
|
| 21 |
+
|
| 22 |
+
Checks that every public attribute of every subclass has a type annotation.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init_subclass__(cls) -> None:
|
| 26 |
+
annotations: dict[str, Any] = getattr(cls, "__annotations__", {})
|
| 27 |
+
for attrname in dir(cls):
|
| 28 |
+
if not attrname.startswith("_") and attrname not in annotations:
|
| 29 |
+
raise TypeError(
|
| 30 |
+
f"Attribute {attrname!r} is missing its type annotation"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
super().__init_subclass__()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TypedAttributeProvider:
|
| 37 |
+
"""Base class for classes that wish to provide typed extra attributes."""
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]:
|
| 41 |
+
"""
|
| 42 |
+
A mapping of the extra attributes to callables that return the corresponding
|
| 43 |
+
values.
|
| 44 |
+
|
| 45 |
+
If the provider wraps another provider, the attributes from that wrapper should
|
| 46 |
+
also be included in the returned mapping (but the wrapper may override the
|
| 47 |
+
callables from the wrapped instance).
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
return {}
|
| 51 |
+
|
| 52 |
+
@overload
|
| 53 |
+
def extra(self, attribute: T_Attr) -> T_Attr: ...
|
| 54 |
+
|
| 55 |
+
@overload
|
| 56 |
+
def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ...
|
| 57 |
+
|
| 58 |
+
@final
|
| 59 |
+
def extra(self, attribute: Any, default: object = undefined) -> object:
|
| 60 |
+
"""
|
| 61 |
+
extra(attribute, default=undefined)
|
| 62 |
+
|
| 63 |
+
Return the value of the given typed extra attribute.
|
| 64 |
+
|
| 65 |
+
:param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to
|
| 66 |
+
look for
|
| 67 |
+
:param default: the value that should be returned if no value is found for the
|
| 68 |
+
attribute
|
| 69 |
+
:raises ~anyio.TypedAttributeLookupError: if the search failed and no default
|
| 70 |
+
value was given
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
try:
|
| 74 |
+
getter = self.extra_attributes[attribute]
|
| 75 |
+
except KeyError:
|
| 76 |
+
if default is undefined:
|
| 77 |
+
raise TypedAttributeLookupError("Attribute not found") from None
|
| 78 |
+
else:
|
| 79 |
+
return default
|
| 80 |
+
|
| 81 |
+
return getter()
|
minigpt2/lib/python3.10/site-packages/anyio/abc/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from ._eventloop import AsyncBackend as AsyncBackend
|
| 4 |
+
from ._resources import AsyncResource as AsyncResource
|
| 5 |
+
from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket
|
| 6 |
+
from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket
|
| 7 |
+
from ._sockets import IPAddressType as IPAddressType
|
| 8 |
+
from ._sockets import IPSockAddrType as IPSockAddrType
|
| 9 |
+
from ._sockets import SocketAttribute as SocketAttribute
|
| 10 |
+
from ._sockets import SocketListener as SocketListener
|
| 11 |
+
from ._sockets import SocketStream as SocketStream
|
| 12 |
+
from ._sockets import UDPPacketType as UDPPacketType
|
| 13 |
+
from ._sockets import UDPSocket as UDPSocket
|
| 14 |
+
from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType
|
| 15 |
+
from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket
|
| 16 |
+
from ._sockets import UNIXSocketStream as UNIXSocketStream
|
| 17 |
+
from ._streams import AnyByteReceiveStream as AnyByteReceiveStream
|
| 18 |
+
from ._streams import AnyByteSendStream as AnyByteSendStream
|
| 19 |
+
from ._streams import AnyByteStream as AnyByteStream
|
| 20 |
+
from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream
|
| 21 |
+
from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream
|
| 22 |
+
from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream
|
| 23 |
+
from ._streams import ByteReceiveStream as ByteReceiveStream
|
| 24 |
+
from ._streams import ByteSendStream as ByteSendStream
|
| 25 |
+
from ._streams import ByteStream as ByteStream
|
| 26 |
+
from ._streams import Listener as Listener
|
| 27 |
+
from ._streams import ObjectReceiveStream as ObjectReceiveStream
|
| 28 |
+
from ._streams import ObjectSendStream as ObjectSendStream
|
| 29 |
+
from ._streams import ObjectStream as ObjectStream
|
| 30 |
+
from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream
|
| 31 |
+
from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream
|
| 32 |
+
from ._streams import UnreliableObjectStream as UnreliableObjectStream
|
| 33 |
+
from ._subprocesses import Process as Process
|
| 34 |
+
from ._tasks import TaskGroup as TaskGroup
|
| 35 |
+
from ._tasks import TaskStatus as TaskStatus
|
| 36 |
+
from ._testing import TestRunner as TestRunner
|
| 37 |
+
|
| 38 |
+
# Re-exported here, for backwards compatibility
|
| 39 |
+
# isort: off
|
| 40 |
+
from .._core._synchronization import (
|
| 41 |
+
CapacityLimiter as CapacityLimiter,
|
| 42 |
+
Condition as Condition,
|
| 43 |
+
Event as Event,
|
| 44 |
+
Lock as Lock,
|
| 45 |
+
Semaphore as Semaphore,
|
| 46 |
+
)
|
| 47 |
+
from .._core._tasks import CancelScope as CancelScope
|
| 48 |
+
from ..from_thread import BlockingPortal as BlockingPortal
|
| 49 |
+
|
| 50 |
+
# Re-export imports so they look like they live directly in this package
|
| 51 |
+
for __value in list(locals().values()):
|
| 52 |
+
if getattr(__value, "__module__", "").startswith("anyio.abc."):
|
| 53 |
+
__value.__module__ = __name__
|
| 54 |
+
|
| 55 |
+
del __value
|
minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_resources.cpython-310.pyc
ADDED
|
Binary file (1.44 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_streams.cpython-310.pyc
ADDED
|
Binary file (7.48 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/abc/__pycache__/_tasks.cpython-310.pyc
ADDED
|
Binary file (4.1 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/anyio/abc/_eventloop.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 4 |
+
import sys
|
| 5 |
+
from abc import ABCMeta, abstractmethod
|
| 6 |
+
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
| 7 |
+
from contextlib import AbstractContextManager
|
| 8 |
+
from os import PathLike
|
| 9 |
+
from signal import Signals
|
| 10 |
+
from socket import AddressFamily, SocketKind, socket
|
| 11 |
+
from typing import (
|
| 12 |
+
IO,
|
| 13 |
+
TYPE_CHECKING,
|
| 14 |
+
Any,
|
| 15 |
+
TypeVar,
|
| 16 |
+
Union,
|
| 17 |
+
overload,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if sys.version_info >= (3, 11):
|
| 21 |
+
from typing import TypeVarTuple, Unpack
|
| 22 |
+
else:
|
| 23 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 24 |
+
|
| 25 |
+
if sys.version_info >= (3, 10):
|
| 26 |
+
from typing import TypeAlias
|
| 27 |
+
else:
|
| 28 |
+
from typing_extensions import TypeAlias
|
| 29 |
+
|
| 30 |
+
if TYPE_CHECKING:
|
| 31 |
+
from _typeshed import HasFileno
|
| 32 |
+
|
| 33 |
+
from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore
|
| 34 |
+
from .._core._tasks import CancelScope
|
| 35 |
+
from .._core._testing import TaskInfo
|
| 36 |
+
from ..from_thread import BlockingPortal
|
| 37 |
+
from ._sockets import (
|
| 38 |
+
ConnectedUDPSocket,
|
| 39 |
+
ConnectedUNIXDatagramSocket,
|
| 40 |
+
IPSockAddrType,
|
| 41 |
+
SocketListener,
|
| 42 |
+
SocketStream,
|
| 43 |
+
UDPSocket,
|
| 44 |
+
UNIXDatagramSocket,
|
| 45 |
+
UNIXSocketStream,
|
| 46 |
+
)
|
| 47 |
+
from ._subprocesses import Process
|
| 48 |
+
from ._tasks import TaskGroup
|
| 49 |
+
from ._testing import TestRunner
|
| 50 |
+
|
| 51 |
+
T_Retval = TypeVar("T_Retval")
|
| 52 |
+
PosArgsT = TypeVarTuple("PosArgsT")
|
| 53 |
+
StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class AsyncBackend(metaclass=ABCMeta):
|
| 57 |
+
@classmethod
|
| 58 |
+
@abstractmethod
|
| 59 |
+
def run(
|
| 60 |
+
cls,
|
| 61 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 62 |
+
args: tuple[Unpack[PosArgsT]],
|
| 63 |
+
kwargs: dict[str, Any],
|
| 64 |
+
options: dict[str, Any],
|
| 65 |
+
) -> T_Retval:
|
| 66 |
+
"""
|
| 67 |
+
Run the given coroutine function in an asynchronous event loop.
|
| 68 |
+
|
| 69 |
+
The current thread must not be already running an event loop.
|
| 70 |
+
|
| 71 |
+
:param func: a coroutine function
|
| 72 |
+
:param args: positional arguments to ``func``
|
| 73 |
+
:param kwargs: positional arguments to ``func``
|
| 74 |
+
:param options: keyword arguments to call the backend ``run()`` implementation
|
| 75 |
+
with
|
| 76 |
+
:return: the return value of the coroutine function
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
@classmethod
|
| 80 |
+
@abstractmethod
|
| 81 |
+
def current_token(cls) -> object:
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
:return:
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
@classmethod
|
| 88 |
+
@abstractmethod
|
| 89 |
+
def current_time(cls) -> float:
|
| 90 |
+
"""
|
| 91 |
+
Return the current value of the event loop's internal clock.
|
| 92 |
+
|
| 93 |
+
:return: the clock value (seconds)
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
@classmethod
|
| 97 |
+
@abstractmethod
|
| 98 |
+
def cancelled_exception_class(cls) -> type[BaseException]:
|
| 99 |
+
"""Return the exception class that is raised in a task if it's cancelled."""
|
| 100 |
+
|
| 101 |
+
@classmethod
|
| 102 |
+
@abstractmethod
|
| 103 |
+
async def checkpoint(cls) -> None:
|
| 104 |
+
"""
|
| 105 |
+
Check if the task has been cancelled, and allow rescheduling of other tasks.
|
| 106 |
+
|
| 107 |
+
This is effectively the same as running :meth:`checkpoint_if_cancelled` and then
|
| 108 |
+
:meth:`cancel_shielded_checkpoint`.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
async def checkpoint_if_cancelled(cls) -> None:
|
| 113 |
+
"""
|
| 114 |
+
Check if the current task group has been cancelled.
|
| 115 |
+
|
| 116 |
+
This will check if the task has been cancelled, but will not allow other tasks
|
| 117 |
+
to be scheduled if not.
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
if cls.current_effective_deadline() == -math.inf:
|
| 121 |
+
await cls.checkpoint()
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
async def cancel_shielded_checkpoint(cls) -> None:
|
| 125 |
+
"""
|
| 126 |
+
Allow the rescheduling of other tasks.
|
| 127 |
+
|
| 128 |
+
This will give other tasks the opportunity to run, but without checking if the
|
| 129 |
+
current task group has been cancelled, unlike with :meth:`checkpoint`.
|
| 130 |
+
|
| 131 |
+
"""
|
| 132 |
+
with cls.create_cancel_scope(shield=True):
|
| 133 |
+
await cls.sleep(0)
|
| 134 |
+
|
| 135 |
+
@classmethod
|
| 136 |
+
@abstractmethod
|
| 137 |
+
async def sleep(cls, delay: float) -> None:
|
| 138 |
+
"""
|
| 139 |
+
Pause the current task for the specified duration.
|
| 140 |
+
|
| 141 |
+
:param delay: the duration, in seconds
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
@abstractmethod
|
| 146 |
+
def create_cancel_scope(
|
| 147 |
+
cls, *, deadline: float = math.inf, shield: bool = False
|
| 148 |
+
) -> CancelScope:
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
@classmethod
|
| 152 |
+
@abstractmethod
|
| 153 |
+
def current_effective_deadline(cls) -> float:
|
| 154 |
+
"""
|
| 155 |
+
Return the nearest deadline among all the cancel scopes effective for the
|
| 156 |
+
current task.
|
| 157 |
+
|
| 158 |
+
:return:
|
| 159 |
+
- a clock value from the event loop's internal clock
|
| 160 |
+
- ``inf`` if there is no deadline in effect
|
| 161 |
+
- ``-inf`` if the current scope has been cancelled
|
| 162 |
+
:rtype: float
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
@abstractmethod
|
| 167 |
+
def create_task_group(cls) -> TaskGroup:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
@classmethod
|
| 171 |
+
@abstractmethod
|
| 172 |
+
def create_event(cls) -> Event:
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
@abstractmethod
|
| 177 |
+
def create_lock(cls, *, fast_acquire: bool) -> Lock:
|
| 178 |
+
pass
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
@abstractmethod
|
| 182 |
+
def create_semaphore(
|
| 183 |
+
cls,
|
| 184 |
+
initial_value: int,
|
| 185 |
+
*,
|
| 186 |
+
max_value: int | None = None,
|
| 187 |
+
fast_acquire: bool = False,
|
| 188 |
+
) -> Semaphore:
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
@abstractmethod
|
| 193 |
+
def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter:
|
| 194 |
+
pass
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
@abstractmethod
|
| 198 |
+
async def run_sync_in_worker_thread(
|
| 199 |
+
cls,
|
| 200 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 201 |
+
args: tuple[Unpack[PosArgsT]],
|
| 202 |
+
abandon_on_cancel: bool = False,
|
| 203 |
+
limiter: CapacityLimiter | None = None,
|
| 204 |
+
) -> T_Retval:
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
@classmethod
|
| 208 |
+
@abstractmethod
|
| 209 |
+
def check_cancelled(cls) -> None:
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
@classmethod
|
| 213 |
+
@abstractmethod
|
| 214 |
+
def run_async_from_thread(
|
| 215 |
+
cls,
|
| 216 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
|
| 217 |
+
args: tuple[Unpack[PosArgsT]],
|
| 218 |
+
token: object,
|
| 219 |
+
) -> T_Retval:
|
| 220 |
+
pass
|
| 221 |
+
|
| 222 |
+
@classmethod
|
| 223 |
+
@abstractmethod
|
| 224 |
+
def run_sync_from_thread(
|
| 225 |
+
cls,
|
| 226 |
+
func: Callable[[Unpack[PosArgsT]], T_Retval],
|
| 227 |
+
args: tuple[Unpack[PosArgsT]],
|
| 228 |
+
token: object,
|
| 229 |
+
) -> T_Retval:
|
| 230 |
+
pass
|
| 231 |
+
|
| 232 |
+
@classmethod
|
| 233 |
+
@abstractmethod
|
| 234 |
+
def create_blocking_portal(cls) -> BlockingPortal:
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
@classmethod
|
| 238 |
+
@abstractmethod
|
| 239 |
+
async def open_process(
|
| 240 |
+
cls,
|
| 241 |
+
command: StrOrBytesPath | Sequence[StrOrBytesPath],
|
| 242 |
+
*,
|
| 243 |
+
stdin: int | IO[Any] | None,
|
| 244 |
+
stdout: int | IO[Any] | None,
|
| 245 |
+
stderr: int | IO[Any] | None,
|
| 246 |
+
**kwargs: Any,
|
| 247 |
+
) -> Process:
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
@classmethod
|
| 251 |
+
@abstractmethod
|
| 252 |
+
def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None:
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
@classmethod
|
| 256 |
+
@abstractmethod
|
| 257 |
+
async def connect_tcp(
|
| 258 |
+
cls, host: str, port: int, local_address: IPSockAddrType | None = None
|
| 259 |
+
) -> SocketStream:
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
@abstractmethod
|
| 264 |
+
async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream:
|
| 265 |
+
pass
|
| 266 |
+
|
| 267 |
+
@classmethod
|
| 268 |
+
@abstractmethod
|
| 269 |
+
def create_tcp_listener(cls, sock: socket) -> SocketListener:
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
@classmethod
|
| 273 |
+
@abstractmethod
|
| 274 |
+
def create_unix_listener(cls, sock: socket) -> SocketListener:
|
| 275 |
+
pass
|
| 276 |
+
|
| 277 |
+
@classmethod
|
| 278 |
+
@abstractmethod
|
| 279 |
+
async def create_udp_socket(
|
| 280 |
+
cls,
|
| 281 |
+
family: AddressFamily,
|
| 282 |
+
local_address: IPSockAddrType | None,
|
| 283 |
+
remote_address: IPSockAddrType | None,
|
| 284 |
+
reuse_port: bool,
|
| 285 |
+
) -> UDPSocket | ConnectedUDPSocket:
|
| 286 |
+
pass
|
| 287 |
+
|
| 288 |
+
@classmethod
|
| 289 |
+
@overload
|
| 290 |
+
async def create_unix_datagram_socket(
|
| 291 |
+
cls, raw_socket: socket, remote_path: None
|
| 292 |
+
) -> UNIXDatagramSocket: ...
|
| 293 |
+
|
| 294 |
+
@classmethod
|
| 295 |
+
@overload
|
| 296 |
+
async def create_unix_datagram_socket(
|
| 297 |
+
cls, raw_socket: socket, remote_path: str | bytes
|
| 298 |
+
) -> ConnectedUNIXDatagramSocket: ...
|
| 299 |
+
|
| 300 |
+
@classmethod
|
| 301 |
+
@abstractmethod
|
| 302 |
+
async def create_unix_datagram_socket(
|
| 303 |
+
cls, raw_socket: socket, remote_path: str | bytes | None
|
| 304 |
+
) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket:
|
| 305 |
+
pass
|
| 306 |
+
|
| 307 |
+
@classmethod
|
| 308 |
+
@abstractmethod
|
| 309 |
+
async def getaddrinfo(
|
| 310 |
+
cls,
|
| 311 |
+
host: bytes | str | None,
|
| 312 |
+
port: str | int | None,
|
| 313 |
+
*,
|
| 314 |
+
family: int | AddressFamily = 0,
|
| 315 |
+
type: int | SocketKind = 0,
|
| 316 |
+
proto: int = 0,
|
| 317 |
+
flags: int = 0,
|
| 318 |
+
) -> list[
|
| 319 |
+
tuple[
|
| 320 |
+
AddressFamily,
|
| 321 |
+
SocketKind,
|
| 322 |
+
int,
|
| 323 |
+
str,
|
| 324 |
+
tuple[str, int] | tuple[str, int, int, int],
|
| 325 |
+
]
|
| 326 |
+
]:
|
| 327 |
+
pass
|
| 328 |
+
|
| 329 |
+
@classmethod
|
| 330 |
+
@abstractmethod
|
| 331 |
+
async def getnameinfo(
|
| 332 |
+
cls, sockaddr: IPSockAddrType, flags: int = 0
|
| 333 |
+
) -> tuple[str, str]:
|
| 334 |
+
pass
|
| 335 |
+
|
| 336 |
+
@classmethod
|
| 337 |
+
@abstractmethod
|
| 338 |
+
async def wait_readable(cls, obj: HasFileno | int) -> None:
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
@classmethod
|
| 342 |
+
@abstractmethod
|
| 343 |
+
async def wait_writable(cls, obj: HasFileno | int) -> None:
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
@classmethod
|
| 347 |
+
@abstractmethod
|
| 348 |
+
def current_default_thread_limiter(cls) -> CapacityLimiter:
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
@classmethod
|
| 352 |
+
@abstractmethod
|
| 353 |
+
def open_signal_receiver(
|
| 354 |
+
cls, *signals: Signals
|
| 355 |
+
) -> AbstractContextManager[AsyncIterator[Signals]]:
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
@classmethod
|
| 359 |
+
@abstractmethod
|
| 360 |
+
def get_current_task(cls) -> TaskInfo:
|
| 361 |
+
pass
|
| 362 |
+
|
| 363 |
+
@classmethod
|
| 364 |
+
@abstractmethod
|
| 365 |
+
def get_running_tasks(cls) -> Sequence[TaskInfo]:
|
| 366 |
+
pass
|
| 367 |
+
|
| 368 |
+
@classmethod
|
| 369 |
+
@abstractmethod
|
| 370 |
+
async def wait_all_tasks_blocked(cls) -> None:
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
@classmethod
|
| 374 |
+
@abstractmethod
|
| 375 |
+
def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
|
| 376 |
+
pass
|
minigpt2/lib/python3.10/site-packages/anyio/abc/_resources.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import ABCMeta, abstractmethod
|
| 4 |
+
from types import TracebackType
|
| 5 |
+
from typing import TypeVar
|
| 6 |
+
|
| 7 |
+
T = TypeVar("T")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AsyncResource(metaclass=ABCMeta):
|
| 11 |
+
"""
|
| 12 |
+
Abstract base class for all closeable asynchronous resources.
|
| 13 |
+
|
| 14 |
+
Works as an asynchronous context manager which returns the instance itself on enter,
|
| 15 |
+
and calls :meth:`aclose` on exit.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
__slots__ = ()
|
| 19 |
+
|
| 20 |
+
async def __aenter__(self: T) -> T:
|
| 21 |
+
return self
|
| 22 |
+
|
| 23 |
+
async def __aexit__(
|
| 24 |
+
self,
|
| 25 |
+
exc_type: type[BaseException] | None,
|
| 26 |
+
exc_val: BaseException | None,
|
| 27 |
+
exc_tb: TracebackType | None,
|
| 28 |
+
) -> None:
|
| 29 |
+
await self.aclose()
|
| 30 |
+
|
| 31 |
+
@abstractmethod
|
| 32 |
+
async def aclose(self) -> None:
|
| 33 |
+
"""Close the resource."""
|
minigpt2/lib/python3.10/site-packages/anyio/abc/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import socket
|
| 4 |
+
from abc import abstractmethod
|
| 5 |
+
from collections.abc import Callable, Collection, Mapping
|
| 6 |
+
from contextlib import AsyncExitStack
|
| 7 |
+
from io import IOBase
|
| 8 |
+
from ipaddress import IPv4Address, IPv6Address
|
| 9 |
+
from socket import AddressFamily
|
| 10 |
+
from types import TracebackType
|
| 11 |
+
from typing import Any, TypeVar, Union
|
| 12 |
+
|
| 13 |
+
from .._core._typedattr import (
|
| 14 |
+
TypedAttributeProvider,
|
| 15 |
+
TypedAttributeSet,
|
| 16 |
+
typed_attribute,
|
| 17 |
+
)
|
| 18 |
+
from ._streams import ByteStream, Listener, UnreliableObjectStream
|
| 19 |
+
from ._tasks import TaskGroup
|
| 20 |
+
|
| 21 |
+
IPAddressType = Union[str, IPv4Address, IPv6Address]
|
| 22 |
+
IPSockAddrType = tuple[str, int]
|
| 23 |
+
SockAddrType = Union[IPSockAddrType, str]
|
| 24 |
+
UDPPacketType = tuple[bytes, IPSockAddrType]
|
| 25 |
+
UNIXDatagramPacketType = tuple[bytes, str]
|
| 26 |
+
T_Retval = TypeVar("T_Retval")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class _NullAsyncContextManager:
|
| 30 |
+
async def __aenter__(self) -> None:
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
async def __aexit__(
|
| 34 |
+
self,
|
| 35 |
+
exc_type: type[BaseException] | None,
|
| 36 |
+
exc_val: BaseException | None,
|
| 37 |
+
exc_tb: TracebackType | None,
|
| 38 |
+
) -> bool | None:
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SocketAttribute(TypedAttributeSet):
|
| 43 |
+
#: the address family of the underlying socket
|
| 44 |
+
family: AddressFamily = typed_attribute()
|
| 45 |
+
#: the local socket address of the underlying socket
|
| 46 |
+
local_address: SockAddrType = typed_attribute()
|
| 47 |
+
#: for IP addresses, the local port the underlying socket is bound to
|
| 48 |
+
local_port: int = typed_attribute()
|
| 49 |
+
#: the underlying stdlib socket object
|
| 50 |
+
raw_socket: socket.socket = typed_attribute()
|
| 51 |
+
#: the remote address the underlying socket is connected to
|
| 52 |
+
remote_address: SockAddrType = typed_attribute()
|
| 53 |
+
#: for IP addresses, the remote port the underlying socket is connected to
|
| 54 |
+
remote_port: int = typed_attribute()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class _SocketProvider(TypedAttributeProvider):
|
| 58 |
+
@property
|
| 59 |
+
def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
|
| 60 |
+
from .._core._sockets import convert_ipv6_sockaddr as convert
|
| 61 |
+
|
| 62 |
+
attributes: dict[Any, Callable[[], Any]] = {
|
| 63 |
+
SocketAttribute.family: lambda: self._raw_socket.family,
|
| 64 |
+
SocketAttribute.local_address: lambda: convert(
|
| 65 |
+
self._raw_socket.getsockname()
|
| 66 |
+
),
|
| 67 |
+
SocketAttribute.raw_socket: lambda: self._raw_socket,
|
| 68 |
+
}
|
| 69 |
+
try:
|
| 70 |
+
peername: tuple[str, int] | None = convert(self._raw_socket.getpeername())
|
| 71 |
+
except OSError:
|
| 72 |
+
peername = None
|
| 73 |
+
|
| 74 |
+
# Provide the remote address for connected sockets
|
| 75 |
+
if peername is not None:
|
| 76 |
+
attributes[SocketAttribute.remote_address] = lambda: peername
|
| 77 |
+
|
| 78 |
+
# Provide local and remote ports for IP based sockets
|
| 79 |
+
if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6):
|
| 80 |
+
attributes[SocketAttribute.local_port] = (
|
| 81 |
+
lambda: self._raw_socket.getsockname()[1]
|
| 82 |
+
)
|
| 83 |
+
if peername is not None:
|
| 84 |
+
remote_port = peername[1]
|
| 85 |
+
attributes[SocketAttribute.remote_port] = lambda: remote_port
|
| 86 |
+
|
| 87 |
+
return attributes
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
@abstractmethod
|
| 91 |
+
def _raw_socket(self) -> socket.socket:
|
| 92 |
+
pass
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class SocketStream(ByteStream, _SocketProvider):
|
| 96 |
+
"""
|
| 97 |
+
Transports bytes over a socket.
|
| 98 |
+
|
| 99 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class UNIXSocketStream(SocketStream):
|
| 104 |
+
@abstractmethod
|
| 105 |
+
async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
|
| 106 |
+
"""
|
| 107 |
+
Send file descriptors along with a message to the peer.
|
| 108 |
+
|
| 109 |
+
:param message: a non-empty bytestring
|
| 110 |
+
:param fds: a collection of files (either numeric file descriptors or open file
|
| 111 |
+
or socket objects)
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
@abstractmethod
|
| 115 |
+
async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
|
| 116 |
+
"""
|
| 117 |
+
Receive file descriptors along with a message from the peer.
|
| 118 |
+
|
| 119 |
+
:param msglen: length of the message to expect from the peer
|
| 120 |
+
:param maxfds: maximum number of file descriptors to expect from the peer
|
| 121 |
+
:return: a tuple of (message, file descriptors)
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class SocketListener(Listener[SocketStream], _SocketProvider):
|
| 126 |
+
"""
|
| 127 |
+
Listens to incoming socket connections.
|
| 128 |
+
|
| 129 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
@abstractmethod
|
| 133 |
+
async def accept(self) -> SocketStream:
|
| 134 |
+
"""Accept an incoming connection."""
|
| 135 |
+
|
| 136 |
+
async def serve(
|
| 137 |
+
self,
|
| 138 |
+
handler: Callable[[SocketStream], Any],
|
| 139 |
+
task_group: TaskGroup | None = None,
|
| 140 |
+
) -> None:
|
| 141 |
+
from .. import create_task_group
|
| 142 |
+
|
| 143 |
+
async with AsyncExitStack() as stack:
|
| 144 |
+
if task_group is None:
|
| 145 |
+
task_group = await stack.enter_async_context(create_task_group())
|
| 146 |
+
|
| 147 |
+
while True:
|
| 148 |
+
stream = await self.accept()
|
| 149 |
+
task_group.start_soon(handler, stream)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider):
|
| 153 |
+
"""
|
| 154 |
+
Represents an unconnected UDP socket.
|
| 155 |
+
|
| 156 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
async def sendto(self, data: bytes, host: str, port: int) -> None:
|
| 160 |
+
"""
|
| 161 |
+
Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))).
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
return await self.send((data, (host, port)))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider):
|
| 168 |
+
"""
|
| 169 |
+
Represents an connected UDP socket.
|
| 170 |
+
|
| 171 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class UNIXDatagramSocket(
|
| 176 |
+
UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider
|
| 177 |
+
):
|
| 178 |
+
"""
|
| 179 |
+
Represents an unconnected Unix datagram socket.
|
| 180 |
+
|
| 181 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
async def sendto(self, data: bytes, path: str) -> None:
|
| 185 |
+
"""Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path))."""
|
| 186 |
+
return await self.send((data, path))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider):
|
| 190 |
+
"""
|
| 191 |
+
Represents a connected Unix datagram socket.
|
| 192 |
+
|
| 193 |
+
Supports all relevant extra attributes from :class:`~SocketAttribute`.
|
| 194 |
+
"""
|
minigpt2/lib/python3.10/site-packages/anyio/abc/_streams.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import abstractmethod
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from typing import Any, Generic, TypeVar, Union
|
| 6 |
+
|
| 7 |
+
from .._core._exceptions import EndOfStream
|
| 8 |
+
from .._core._typedattr import TypedAttributeProvider
|
| 9 |
+
from ._resources import AsyncResource
|
| 10 |
+
from ._tasks import TaskGroup
|
| 11 |
+
|
| 12 |
+
T_Item = TypeVar("T_Item")
|
| 13 |
+
T_co = TypeVar("T_co", covariant=True)
|
| 14 |
+
T_contra = TypeVar("T_contra", contravariant=True)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class UnreliableObjectReceiveStream(
|
| 18 |
+
Generic[T_co], AsyncResource, TypedAttributeProvider
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
An interface for receiving objects.
|
| 22 |
+
|
| 23 |
+
This interface makes no guarantees that the received messages arrive in the order in
|
| 24 |
+
which they were sent, or that no messages are missed.
|
| 25 |
+
|
| 26 |
+
Asynchronously iterating over objects of this type will yield objects matching the
|
| 27 |
+
given type parameter.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]:
|
| 31 |
+
return self
|
| 32 |
+
|
| 33 |
+
async def __anext__(self) -> T_co:
|
| 34 |
+
try:
|
| 35 |
+
return await self.receive()
|
| 36 |
+
except EndOfStream:
|
| 37 |
+
raise StopAsyncIteration
|
| 38 |
+
|
| 39 |
+
@abstractmethod
|
| 40 |
+
async def receive(self) -> T_co:
|
| 41 |
+
"""
|
| 42 |
+
Receive the next item.
|
| 43 |
+
|
| 44 |
+
:raises ~anyio.ClosedResourceError: if the receive stream has been explicitly
|
| 45 |
+
closed
|
| 46 |
+
:raises ~anyio.EndOfStream: if this stream has been closed from the other end
|
| 47 |
+
:raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
|
| 48 |
+
due to external causes
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class UnreliableObjectSendStream(
|
| 53 |
+
Generic[T_contra], AsyncResource, TypedAttributeProvider
|
| 54 |
+
):
|
| 55 |
+
"""
|
| 56 |
+
An interface for sending objects.
|
| 57 |
+
|
| 58 |
+
This interface makes no guarantees that the messages sent will reach the
|
| 59 |
+
recipient(s) in the same order in which they were sent, or at all.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
@abstractmethod
|
| 63 |
+
async def send(self, item: T_contra) -> None:
|
| 64 |
+
"""
|
| 65 |
+
Send an item to the peer(s).
|
| 66 |
+
|
| 67 |
+
:param item: the item to send
|
| 68 |
+
:raises ~anyio.ClosedResourceError: if the send stream has been explicitly
|
| 69 |
+
closed
|
| 70 |
+
:raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
|
| 71 |
+
due to external causes
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class UnreliableObjectStream(
|
| 76 |
+
UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item]
|
| 77 |
+
):
|
| 78 |
+
"""
|
| 79 |
+
A bidirectional message stream which does not guarantee the order or reliability of
|
| 80 |
+
message delivery.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]):
|
| 85 |
+
"""
|
| 86 |
+
A receive message stream which guarantees that messages are received in the same
|
| 87 |
+
order in which they were sent, and that no messages are missed.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class ObjectSendStream(UnreliableObjectSendStream[T_contra]):
|
| 92 |
+
"""
|
| 93 |
+
A send message stream which guarantees that messages are delivered in the same order
|
| 94 |
+
in which they were sent, without missing any messages in the middle.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ObjectStream(
|
| 99 |
+
ObjectReceiveStream[T_Item],
|
| 100 |
+
ObjectSendStream[T_Item],
|
| 101 |
+
UnreliableObjectStream[T_Item],
|
| 102 |
+
):
|
| 103 |
+
"""
|
| 104 |
+
A bidirectional message stream which guarantees the order and reliability of message
|
| 105 |
+
delivery.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
@abstractmethod
|
| 109 |
+
async def send_eof(self) -> None:
|
| 110 |
+
"""
|
| 111 |
+
Send an end-of-file indication to the peer.
|
| 112 |
+
|
| 113 |
+
You should not try to send any further data to this stream after calling this
|
| 114 |
+
method. This method is idempotent (does nothing on successive calls).
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class ByteReceiveStream(AsyncResource, TypedAttributeProvider):
|
| 119 |
+
"""
|
| 120 |
+
An interface for receiving bytes from a single peer.
|
| 121 |
+
|
| 122 |
+
Iterating this byte stream will yield a byte string of arbitrary length, but no more
|
| 123 |
+
than 65536 bytes.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __aiter__(self) -> ByteReceiveStream:
|
| 127 |
+
return self
|
| 128 |
+
|
| 129 |
+
async def __anext__(self) -> bytes:
|
| 130 |
+
try:
|
| 131 |
+
return await self.receive()
|
| 132 |
+
except EndOfStream:
|
| 133 |
+
raise StopAsyncIteration
|
| 134 |
+
|
| 135 |
+
@abstractmethod
|
| 136 |
+
async def receive(self, max_bytes: int = 65536) -> bytes:
|
| 137 |
+
"""
|
| 138 |
+
Receive at most ``max_bytes`` bytes from the peer.
|
| 139 |
+
|
| 140 |
+
.. note:: Implementors of this interface should not return an empty
|
| 141 |
+
:class:`bytes` object, and users should ignore them.
|
| 142 |
+
|
| 143 |
+
:param max_bytes: maximum number of bytes to receive
|
| 144 |
+
:return: the received bytes
|
| 145 |
+
:raises ~anyio.EndOfStream: if this stream has been closed from the other end
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class ByteSendStream(AsyncResource, TypedAttributeProvider):
|
| 150 |
+
"""An interface for sending bytes to a single peer."""
|
| 151 |
+
|
| 152 |
+
@abstractmethod
|
| 153 |
+
async def send(self, item: bytes) -> None:
|
| 154 |
+
"""
|
| 155 |
+
Send the given bytes to the peer.
|
| 156 |
+
|
| 157 |
+
:param item: the bytes to send
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class ByteStream(ByteReceiveStream, ByteSendStream):
|
| 162 |
+
"""A bidirectional byte stream."""
|
| 163 |
+
|
| 164 |
+
@abstractmethod
|
| 165 |
+
async def send_eof(self) -> None:
|
| 166 |
+
"""
|
| 167 |
+
Send an end-of-file indication to the peer.
|
| 168 |
+
|
| 169 |
+
You should not try to send any further data to this stream after calling this
|
| 170 |
+
method. This method is idempotent (does nothing on successive calls).
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
#: Type alias for all unreliable bytes-oriented receive streams.
|
| 175 |
+
AnyUnreliableByteReceiveStream = Union[
|
| 176 |
+
UnreliableObjectReceiveStream[bytes], ByteReceiveStream
|
| 177 |
+
]
|
| 178 |
+
#: Type alias for all unreliable bytes-oriented send streams.
|
| 179 |
+
AnyUnreliableByteSendStream = Union[UnreliableObjectSendStream[bytes], ByteSendStream]
|
| 180 |
+
#: Type alias for all unreliable bytes-oriented streams.
|
| 181 |
+
AnyUnreliableByteStream = Union[UnreliableObjectStream[bytes], ByteStream]
|
| 182 |
+
#: Type alias for all bytes-oriented receive streams.
|
| 183 |
+
AnyByteReceiveStream = Union[ObjectReceiveStream[bytes], ByteReceiveStream]
|
| 184 |
+
#: Type alias for all bytes-oriented send streams.
|
| 185 |
+
AnyByteSendStream = Union[ObjectSendStream[bytes], ByteSendStream]
|
| 186 |
+
#: Type alias for all bytes-oriented streams.
|
| 187 |
+
AnyByteStream = Union[ObjectStream[bytes], ByteStream]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider):
|
| 191 |
+
"""An interface for objects that let you accept incoming connections."""
|
| 192 |
+
|
| 193 |
+
@abstractmethod
|
| 194 |
+
async def serve(
|
| 195 |
+
self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None
|
| 196 |
+
) -> None:
|
| 197 |
+
"""
|
| 198 |
+
Accept incoming connections as they come in and start tasks to handle them.
|
| 199 |
+
|
| 200 |
+
:param handler: a callable that will be used to handle each accepted connection
|
| 201 |
+
:param task_group: the task group that will be used to start tasks for handling
|
| 202 |
+
each accepted connection (if omitted, an ad-hoc task group will be created)
|
| 203 |
+
"""
|
minigpt2/lib/python3.10/site-packages/anyio/abc/_subprocesses.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import abstractmethod
|
| 4 |
+
from signal import Signals
|
| 5 |
+
|
| 6 |
+
from ._resources import AsyncResource
|
| 7 |
+
from ._streams import ByteReceiveStream, ByteSendStream
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Process(AsyncResource):
|
| 11 |
+
"""An asynchronous version of :class:`subprocess.Popen`."""
|
| 12 |
+
|
| 13 |
+
@abstractmethod
|
| 14 |
+
async def wait(self) -> int:
|
| 15 |
+
"""
|
| 16 |
+
Wait until the process exits.
|
| 17 |
+
|
| 18 |
+
:return: the exit code of the process
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@abstractmethod
|
| 22 |
+
def terminate(self) -> None:
|
| 23 |
+
"""
|
| 24 |
+
Terminates the process, gracefully if possible.
|
| 25 |
+
|
| 26 |
+
On Windows, this calls ``TerminateProcess()``.
|
| 27 |
+
On POSIX systems, this sends ``SIGTERM`` to the process.
|
| 28 |
+
|
| 29 |
+
.. seealso:: :meth:`subprocess.Popen.terminate`
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
@abstractmethod
|
| 33 |
+
def kill(self) -> None:
|
| 34 |
+
"""
|
| 35 |
+
Kills the process.
|
| 36 |
+
|
| 37 |
+
On Windows, this calls ``TerminateProcess()``.
|
| 38 |
+
On POSIX systems, this sends ``SIGKILL`` to the process.
|
| 39 |
+
|
| 40 |
+
.. seealso:: :meth:`subprocess.Popen.kill`
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
@abstractmethod
|
| 44 |
+
def send_signal(self, signal: Signals) -> None:
|
| 45 |
+
"""
|
| 46 |
+
Send a signal to the subprocess.
|
| 47 |
+
|
| 48 |
+
.. seealso:: :meth:`subprocess.Popen.send_signal`
|
| 49 |
+
|
| 50 |
+
:param signal: the signal number (e.g. :data:`signal.SIGHUP`)
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
@abstractmethod
|
| 55 |
+
def pid(self) -> int:
|
| 56 |
+
"""The process ID of the process."""
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
@abstractmethod
|
| 60 |
+
def returncode(self) -> int | None:
|
| 61 |
+
"""
|
| 62 |
+
The return code of the process. If the process has not yet terminated, this will
|
| 63 |
+
be ``None``.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
@abstractmethod
|
| 68 |
+
def stdin(self) -> ByteSendStream | None:
|
| 69 |
+
"""The stream for the standard input of the process."""
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
@abstractmethod
|
| 73 |
+
def stdout(self) -> ByteReceiveStream | None:
|
| 74 |
+
"""The stream for the standard output of the process."""
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
@abstractmethod
|
| 78 |
+
def stderr(self) -> ByteReceiveStream | None:
|
| 79 |
+
"""The stream for the standard error output of the process."""
|
minigpt2/lib/python3.10/site-packages/anyio/abc/_tasks.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from abc import ABCMeta, abstractmethod
|
| 5 |
+
from collections.abc import Awaitable, Callable
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, overload
|
| 8 |
+
|
| 9 |
+
if sys.version_info >= (3, 11):
|
| 10 |
+
from typing import TypeVarTuple, Unpack
|
| 11 |
+
else:
|
| 12 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from .._core._tasks import CancelScope
|
| 16 |
+
|
| 17 |
+
T_Retval = TypeVar("T_Retval")
|
| 18 |
+
T_contra = TypeVar("T_contra", contravariant=True)
|
| 19 |
+
PosArgsT = TypeVarTuple("PosArgsT")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TaskStatus(Protocol[T_contra]):
|
| 23 |
+
@overload
|
| 24 |
+
def started(self: TaskStatus[None]) -> None: ...
|
| 25 |
+
|
| 26 |
+
@overload
|
| 27 |
+
def started(self, value: T_contra) -> None: ...
|
| 28 |
+
|
| 29 |
+
def started(self, value: T_contra | None = None) -> None:
|
| 30 |
+
"""
|
| 31 |
+
Signal that the task has started.
|
| 32 |
+
|
| 33 |
+
:param value: object passed back to the starter of the task
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TaskGroup(metaclass=ABCMeta):
|
| 38 |
+
"""
|
| 39 |
+
Groups several asynchronous tasks together.
|
| 40 |
+
|
| 41 |
+
:ivar cancel_scope: the cancel scope inherited by all child tasks
|
| 42 |
+
:vartype cancel_scope: CancelScope
|
| 43 |
+
|
| 44 |
+
.. note:: On asyncio, support for eager task factories is considered to be
|
| 45 |
+
**experimental**. In particular, they don't follow the usual semantics of new
|
| 46 |
+
tasks being scheduled on the next iteration of the event loop, and may thus
|
| 47 |
+
cause unexpected behavior in code that wasn't written with such semantics in
|
| 48 |
+
mind.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
cancel_scope: CancelScope
|
| 52 |
+
|
| 53 |
+
@abstractmethod
|
| 54 |
+
def start_soon(
|
| 55 |
+
self,
|
| 56 |
+
func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
|
| 57 |
+
*args: Unpack[PosArgsT],
|
| 58 |
+
name: object = None,
|
| 59 |
+
) -> None:
|
| 60 |
+
"""
|
| 61 |
+
Start a new task in this task group.
|
| 62 |
+
|
| 63 |
+
:param func: a coroutine function
|
| 64 |
+
:param args: positional arguments to call the function with
|
| 65 |
+
:param name: name of the task, for the purposes of introspection and debugging
|
| 66 |
+
|
| 67 |
+
.. versionadded:: 3.0
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
@abstractmethod
|
| 71 |
+
async def start(
|
| 72 |
+
self,
|
| 73 |
+
func: Callable[..., Awaitable[Any]],
|
| 74 |
+
*args: object,
|
| 75 |
+
name: object = None,
|
| 76 |
+
) -> Any:
|
| 77 |
+
"""
|
| 78 |
+
Start a new task and wait until it signals for readiness.
|
| 79 |
+
|
| 80 |
+
:param func: a coroutine function
|
| 81 |
+
:param args: positional arguments to call the function with
|
| 82 |
+
:param name: name of the task, for the purposes of introspection and debugging
|
| 83 |
+
:return: the value passed to ``task_status.started()``
|
| 84 |
+
:raises RuntimeError: if the task finishes without calling
|
| 85 |
+
``task_status.started()``
|
| 86 |
+
|
| 87 |
+
.. versionadded:: 3.0
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
@abstractmethod
|
| 91 |
+
async def __aenter__(self) -> TaskGroup:
|
| 92 |
+
"""Enter the task group context and allow starting new tasks."""
|
| 93 |
+
|
| 94 |
+
@abstractmethod
|
| 95 |
+
async def __aexit__(
|
| 96 |
+
self,
|
| 97 |
+
exc_type: type[BaseException] | None,
|
| 98 |
+
exc_val: BaseException | None,
|
| 99 |
+
exc_tb: TracebackType | None,
|
| 100 |
+
) -> bool | None:
|
| 101 |
+
"""Exit the task group context waiting for all tasks to finish."""
|