| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import socket |
| 4 |
from abc import ABC, abstractmethod |
| 5 |
from typing import TYPE_CHECKING, Generic, TypeVar |
| 6 |
|
| 7 |
import trio |
| 8 |
|
| 9 |
if TYPE_CHECKING: |
| 10 |
from types import TracebackType |
| 11 |
|
| 12 |
from typing_extensions import Self |
| 13 |
|
| 14 |
# both of these introduce circular imports if outside a TYPE_CHECKING guard |
| 15 |
from ._socket import SocketType |
| 16 |
from .lowlevel import Task |
| 17 |
|
| 18 |
|
| 19 |
class Clock(ABC): |
| 20 |
"""The interface for custom run loop clocks.""" |
| 21 |
|
| 22 |
__slots__ = () |
| 23 |
|
| 24 |
@abstractmethod |
| 25 |
def start_clock(self) -> None: |
| 26 |
"""Do any setup this clock might need. |
| 27 |
|
| 28 |
Called at the beginning of the run. |
| 29 |
|
| 30 |
""" |
| 31 |
|
| 32 |
@abstractmethod |
| 33 |
def current_time(self) -> float: |
| 34 |
"""Return the current time, according to this clock. |
| 35 |
|
| 36 |
This is used to implement functions like :func:`trio.current_time` and |
| 37 |
:func:`trio.move_on_after`. |
| 38 |
|
| 39 |
Returns: |
| 40 |
float: The current time. |
| 41 |
|
| 42 |
""" |
| 43 |
|
| 44 |
@abstractmethod |
| 45 |
def deadline_to_sleep_time(self, deadline: float) -> float: |
| 46 |
"""Compute the real time until the given deadline. |
| 47 |
|
| 48 |
This is called before we enter a system-specific wait function like |
| 49 |
:func:`select.select`, to get the timeout to pass. |
| 50 |
|
| 51 |
For a clock using wall-time, this should be something like:: |
| 52 |
|
| 53 |
return deadline - self.current_time() |
| 54 |
|
| 55 |
but of course it may be different if you're implementing some kind of |
| 56 |
virtual clock. |
| 57 |
|
| 58 |
Args: |
| 59 |
deadline (float): The absolute time of the next deadline, |
| 60 |
according to this clock. |
| 61 |
|
| 62 |
Returns: |
| 63 |
float: The number of real seconds to sleep until the given |
| 64 |
deadline. May be :data:`math.inf`. |
| 65 |
|
| 66 |
""" |
| 67 |
|
| 68 |
|
| 69 |
class Instrument(ABC): # noqa: B024 # conceptually is ABC |
| 70 |
"""The interface for run loop instrumentation. |
| 71 |
|
| 72 |
Instruments don't have to inherit from this abstract base class, and all |
| 73 |
of these methods are optional. This class serves mostly as documentation. |
| 74 |
|
| 75 |
""" |
| 76 |
|
| 77 |
__slots__ = () |
| 78 |
|
| 79 |
def before_run(self) -> None: |
| 80 |
"""Called at the beginning of :func:`trio.run`.""" |
| 81 |
return |
| 82 |
|
| 83 |
def after_run(self) -> None: |
| 84 |
"""Called just before :func:`trio.run` returns.""" |
| 85 |
return |
| 86 |
|
| 87 |
def task_spawned(self, task: Task) -> None: |
| 88 |
"""Called when the given task is created. |
| 89 |
|
| 90 |
Args: |
| 91 |
task (trio.lowlevel.Task): The new task. |
| 92 |
|
| 93 |
""" |
| 94 |
return |
| 95 |
|
| 96 |
def task_scheduled(self, task: Task) -> None: |
| 97 |
"""Called when the given task becomes runnable. |
| 98 |
|
| 99 |
It may still be some time before it actually runs, if there are other |
| 100 |
runnable tasks ahead of it. |
| 101 |
|
| 102 |
Args: |
| 103 |
task (trio.lowlevel.Task): The task that became runnable. |
| 104 |
|
| 105 |
""" |
| 106 |
return |
| 107 |
|
| 108 |
def before_task_step(self, task: Task) -> None: |
| 109 |
"""Called immediately before we resume running the given task. |
| 110 |
|
| 111 |
Args: |
| 112 |
task (trio.lowlevel.Task): The task that is about to run. |
| 113 |
|
| 114 |
""" |
| 115 |
return |
| 116 |
|
| 117 |
def after_task_step(self, task: Task) -> None: |
| 118 |
"""Called when we return to the main run loop after a task has yielded. |
| 119 |
|
| 120 |
Args: |
| 121 |
task (trio.lowlevel.Task): The task that just ran. |
| 122 |
|
| 123 |
""" |
| 124 |
return |
| 125 |
|
| 126 |
def task_exited(self, task: Task) -> None: |
| 127 |
"""Called when the given task exits. |
| 128 |
|
| 129 |
Args: |
| 130 |
task (trio.lowlevel.Task): The finished task. |
| 131 |
|
| 132 |
""" |
| 133 |
return |
| 134 |
|
| 135 |
def before_io_wait(self, timeout: float) -> None: |
| 136 |
"""Called before blocking to wait for I/O readiness. |
| 137 |
|
| 138 |
Args: |
| 139 |
timeout (float): The number of seconds we are willing to wait. |
| 140 |
|
| 141 |
""" |
| 142 |
return |
| 143 |
|
| 144 |
def after_io_wait(self, timeout: float) -> None: |
| 145 |
"""Called after handling pending I/O. |
| 146 |
|
| 147 |
Args: |
| 148 |
timeout (float): The number of seconds we were willing to |
| 149 |
wait. This much time may or may not have elapsed, depending on |
| 150 |
whether any I/O was ready. |
| 151 |
|
| 152 |
""" |
| 153 |
return |
| 154 |
|
| 155 |
|
| 156 |
class HostnameResolver(ABC): |
| 157 |
"""If you have a custom hostname resolver, then implementing |
| 158 |
:class:`HostnameResolver` allows you to register this to be used by Trio. |
| 159 |
|
| 160 |
See :func:`trio.socket.set_custom_hostname_resolver`. |
| 161 |
|
| 162 |
""" |
| 163 |
|
| 164 |
__slots__ = () |
| 165 |
|
| 166 |
@abstractmethod |
| 167 |
async def getaddrinfo( |
| 168 |
self, |
| 169 |
host: bytes | None, |
| 170 |
port: bytes | str | int | None, |
| 171 |
family: int = 0, |
| 172 |
type: int = 0, |
| 173 |
proto: int = 0, |
| 174 |
flags: int = 0, |
| 175 |
) -> list[ |
| 176 |
tuple[ |
| 177 |
socket.AddressFamily, |
| 178 |
socket.SocketKind, |
| 179 |
int, |
| 180 |
str, |
| 181 |
tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], |
| 182 |
] |
| 183 |
]: |
| 184 |
"""A custom implementation of :func:`~trio.socket.getaddrinfo`. |
| 185 |
|
| 186 |
Called by :func:`trio.socket.getaddrinfo`. |
| 187 |
|
| 188 |
If ``host`` is given as a numeric IP address, then |
| 189 |
:func:`~trio.socket.getaddrinfo` may handle the request itself rather |
| 190 |
than calling this method. |
| 191 |
|
| 192 |
Any required IDNA encoding is handled before calling this function; |
| 193 |
your implementation can assume that it will never see U-labels like |
| 194 |
``"café.com"``, and only needs to handle A-labels like |
| 195 |
``b"xn--caf-dma.com"``.""" # spellchecker:disable-line |
| 196 |
|
| 197 |
@abstractmethod |
| 198 |
async def getnameinfo( |
| 199 |
self, |
| 200 |
sockaddr: tuple[str, int] | tuple[str, int, int, int], |
| 201 |
flags: int, |
| 202 |
) -> tuple[str, str]: |
| 203 |
"""A custom implementation of :func:`~trio.socket.getnameinfo`. |
| 204 |
|
| 205 |
Called by :func:`trio.socket.getnameinfo`. |
| 206 |
|
| 207 |
""" |
| 208 |
|
| 209 |
|
| 210 |
class SocketFactory(ABC): |
| 211 |
"""If you write a custom class implementing the Trio socket interface, |
| 212 |
then you can use a :class:`SocketFactory` to get Trio to use it. |
| 213 |
|
| 214 |
See :func:`trio.socket.set_custom_socket_factory`. |
| 215 |
|
| 216 |
""" |
| 217 |
|
| 218 |
__slots__ = () |
| 219 |
|
| 220 |
@abstractmethod |
| 221 |
def socket( |
| 222 |
self, |
| 223 |
family: socket.AddressFamily | int = socket.AF_INET, |
| 224 |
type: socket.SocketKind | int = socket.SOCK_STREAM, |
| 225 |
proto: int = 0, |
| 226 |
) -> SocketType: |
| 227 |
"""Create and return a socket object. |
| 228 |
|
| 229 |
Your socket object must inherit from :class:`trio.socket.SocketType`, |
| 230 |
which is an empty class whose only purpose is to "mark" which classes |
| 231 |
should be considered valid Trio sockets. |
| 232 |
|
| 233 |
Called by :func:`trio.socket.socket`. |
| 234 |
|
| 235 |
Note that unlike :func:`trio.socket.socket`, this does not take a |
| 236 |
``fileno=`` argument. If a ``fileno=`` is specified, then |
| 237 |
:func:`trio.socket.socket` returns a regular Trio socket object |
| 238 |
instead of calling this method. |
| 239 |
|
| 240 |
""" |
| 241 |
|
| 242 |
|
| 243 |
class AsyncResource(ABC): |
| 244 |
"""A standard interface for resources that needs to be cleaned up, and |
| 245 |
where that cleanup may require blocking operations. |
| 246 |
|
| 247 |
This class distinguishes between "graceful" closes, which may perform I/O |
| 248 |
and thus block, and a "forceful" close, which cannot. For example, cleanly |
| 249 |
shutting down a TLS-encrypted connection requires sending a "goodbye" |
| 250 |
message; but if a peer has become non-responsive, then sending this |
| 251 |
message might block forever, so we may want to just drop the connection |
| 252 |
instead. Therefore the :meth:`aclose` method is unusual in that it |
| 253 |
should always close the connection (or at least make its best attempt) |
| 254 |
*even if it fails*; failure indicates a failure to achieve grace, not a |
| 255 |
failure to close the connection. |
| 256 |
|
| 257 |
Objects that implement this interface can be used as async context |
| 258 |
managers, i.e., you can write:: |
| 259 |
|
| 260 |
async with create_resource() as some_async_resource: |
| 261 |
... |
| 262 |
|
| 263 |
Entering the context manager is synchronous (not a checkpoint); exiting it |
| 264 |
calls :meth:`aclose`. The default implementations of |
| 265 |
``__aenter__`` and ``__aexit__`` should be adequate for all subclasses. |
| 266 |
|
| 267 |
""" |
| 268 |
|
| 269 |
__slots__ = () |
| 270 |
|
| 271 |
@abstractmethod |
| 272 |
async def aclose(self) -> None: |
| 273 |
"""Close this resource, possibly blocking. |
| 274 |
|
| 275 |
IMPORTANT: This method may block in order to perform a "graceful" |
| 276 |
shutdown. But, if this fails, then it still *must* close any |
| 277 |
underlying resources before returning. An error from this method |
| 278 |
indicates a failure to achieve grace, *not* a failure to close the |
| 279 |
connection. |
| 280 |
|
| 281 |
For example, suppose we call :meth:`aclose` on a TLS-encrypted |
| 282 |
connection. This requires sending a "goodbye" message; but if the peer |
| 283 |
has become non-responsive, then our attempt to send this message might |
| 284 |
block forever, and eventually time out and be cancelled. In this case |
| 285 |
the :meth:`aclose` method on :class:`~trio.SSLStream` will |
| 286 |
immediately close the underlying transport stream using |
| 287 |
:func:`trio.aclose_forcefully` before raising :exc:`~trio.Cancelled`. |
| 288 |
|
| 289 |
If the resource is already closed, then this method should silently |
| 290 |
succeed. |
| 291 |
|
| 292 |
Once this method completes, any other pending or future operations on |
| 293 |
this resource should generally raise :exc:`~trio.ClosedResourceError`, |
| 294 |
unless there's a good reason to do otherwise. |
| 295 |
|
| 296 |
See also: :func:`trio.aclose_forcefully`. |
| 297 |
|
| 298 |
""" |
| 299 |
|
| 300 |
async def __aenter__(self) -> Self: |
| 301 |
return self |
| 302 |
|
| 303 |
async def __aexit__( |
| 304 |
self, |
| 305 |
exc_type: type[BaseException] | None, |
| 306 |
exc_value: BaseException | None, |
| 307 |
traceback: TracebackType | None, |
| 308 |
) -> None: |
| 309 |
await self.aclose() |
| 310 |
|
| 311 |
|
| 312 |
class SendStream(AsyncResource): |
| 313 |
"""A standard interface for sending data on a byte stream. |
| 314 |
|
| 315 |
The underlying stream may be unidirectional, or bidirectional. If it's |
| 316 |
bidirectional, then you probably want to also implement |
| 317 |
:class:`ReceiveStream`, which makes your object a :class:`Stream`. |
| 318 |
|
| 319 |
:class:`SendStream` objects also implement the :class:`AsyncResource` |
| 320 |
interface, so they can be closed by calling :meth:`~AsyncResource.aclose` |
| 321 |
or using an ``async with`` block. |
| 322 |
|
| 323 |
If you want to send Python objects rather than raw bytes, see |
| 324 |
:class:`SendChannel`. |
| 325 |
|
| 326 |
""" |
| 327 |
|
| 328 |
__slots__ = () |
| 329 |
|
| 330 |
@abstractmethod |
| 331 |
async def send_all(self, data: bytes | bytearray | memoryview) -> None: |
| 332 |
"""Sends the given data through the stream, blocking if necessary. |
| 333 |
|
| 334 |
Args: |
| 335 |
data (bytes, bytearray, or memoryview): The data to send. |
| 336 |
|
| 337 |
Raises: |
| 338 |
trio.BusyResourceError: if another task is already executing a |
| 339 |
:meth:`send_all`, :meth:`wait_send_all_might_not_block`, or |
| 340 |
:meth:`HalfCloseableStream.send_eof` on this stream. |
| 341 |
trio.BrokenResourceError: if something has gone wrong, and the stream |
| 342 |
is broken. |
| 343 |
trio.ClosedResourceError: if you previously closed this stream |
| 344 |
object, or if another task closes this stream object while |
| 345 |
:meth:`send_all` is running. |
| 346 |
|
| 347 |
Most low-level operations in Trio provide a guarantee: if they raise |
| 348 |
:exc:`trio.Cancelled`, this means that they had no effect, so the |
| 349 |
system remains in a known state. This is **not true** for |
| 350 |
:meth:`send_all`. If this operation raises :exc:`trio.Cancelled` (or |
| 351 |
any other exception for that matter), then it may have sent some, all, |
| 352 |
or none of the requested data, and there is no way to know which. |
| 353 |
|
| 354 |
""" |
| 355 |
|
| 356 |
@abstractmethod |
| 357 |
async def wait_send_all_might_not_block(self) -> None: |
| 358 |
"""Block until it's possible that :meth:`send_all` might not block. |
| 359 |
|
| 360 |
This method may return early: it's possible that after it returns, |
| 361 |
:meth:`send_all` will still block. (In the worst case, if no better |
| 362 |
implementation is available, then it might always return immediately |
| 363 |
without blocking. It's nice to do better than that when possible, |
| 364 |
though.) |
| 365 |
|
| 366 |
This method **must not** return *late*: if it's possible for |
| 367 |
:meth:`send_all` to complete without blocking, then it must |
| 368 |
return. When implementing it, err on the side of returning early. |
| 369 |
|
| 370 |
Raises: |
| 371 |
trio.BusyResourceError: if another task is already executing a |
| 372 |
:meth:`send_all`, :meth:`wait_send_all_might_not_block`, or |
| 373 |
:meth:`HalfCloseableStream.send_eof` on this stream. |
| 374 |
trio.BrokenResourceError: if something has gone wrong, and the stream |
| 375 |
is broken. |
| 376 |
trio.ClosedResourceError: if you previously closed this stream |
| 377 |
object, or if another task closes this stream object while |
| 378 |
:meth:`wait_send_all_might_not_block` is running. |
| 379 |
|
| 380 |
Note: |
| 381 |
|
| 382 |
This method is intended to aid in implementing protocols that want |
| 383 |
to delay choosing which data to send until the last moment. E.g., |
| 384 |
suppose you're working on an implementation of a remote display server |
| 385 |
like `VNC |
| 386 |
<https://en.wikipedia.org/wiki/Virtual_Network_Computing>`__, and |
| 387 |
the network connection is currently backed up so that if you call |
| 388 |
:meth:`send_all` now then it will sit for 0.5 seconds before actually |
| 389 |
sending anything. In this case it doesn't make sense to take a |
| 390 |
screenshot, then wait 0.5 seconds, and then send it, because the |
| 391 |
screen will keep changing while you wait; it's better to wait 0.5 |
| 392 |
seconds, then take the screenshot, and then send it, because this |
| 393 |
way the data you deliver will be more |
| 394 |
up-to-date. Using :meth:`wait_send_all_might_not_block` makes it |
| 395 |
possible to implement the better strategy. |
| 396 |
|
| 397 |
If you use this method, you might also want to read up on |
| 398 |
``TCP_NOTSENT_LOWAT``. |
| 399 |
|
| 400 |
Further reading: |
| 401 |
|
| 402 |
* `Prioritization Only Works When There's Pending Data to Prioritize |
| 403 |
<https://insouciant.org/tech/prioritization-only-works-when-theres-pending-data-to-prioritize/>`__ |
| 404 |
|
| 405 |
* WWDC 2015: Your App and Next Generation Networks: `slides |
| 406 |
<http://devstreaming.apple.com/videos/wwdc/2015/719ui2k57m/719/719_your_app_and_next_generation_networks.pdf?dl=1>`__, |
| 407 |
`video and transcript |
| 408 |
<https://developer.apple.com/videos/play/wwdc2015/719/>`__ |
| 409 |
|
| 410 |
""" |
| 411 |
|
| 412 |
|
| 413 |
class ReceiveStream(AsyncResource): |
| 414 |
"""A standard interface for receiving data on a byte stream. |
| 415 |
|
| 416 |
The underlying stream may be unidirectional, or bidirectional. If it's |
| 417 |
bidirectional, then you probably want to also implement |
| 418 |
:class:`SendStream`, which makes your object a :class:`Stream`. |
| 419 |
|
| 420 |
:class:`ReceiveStream` objects also implement the :class:`AsyncResource` |
| 421 |
interface, so they can be closed by calling :meth:`~AsyncResource.aclose` |
| 422 |
or using an ``async with`` block. |
| 423 |
|
| 424 |
If you want to receive Python objects rather than raw bytes, see |
| 425 |
:class:`ReceiveChannel`. |
| 426 |
|
| 427 |
`ReceiveStream` objects can be used in ``async for`` loops. Each iteration |
| 428 |
will produce an arbitrary sized chunk of bytes, like calling |
| 429 |
`receive_some` with no arguments. Every chunk will contain at least one |
| 430 |
byte, and the loop automatically exits when reaching end-of-file. |
| 431 |
|
| 432 |
""" |
| 433 |
|
| 434 |
__slots__ = () |
| 435 |
|
| 436 |
@abstractmethod |
| 437 |
async def receive_some(self, max_bytes: int | None = None) -> bytes | bytearray: |
| 438 |
"""Wait until there is data available on this stream, and then return |
| 439 |
some of it. |
| 440 |
|
| 441 |
A return value of ``b""`` (an empty bytestring) indicates that the |
| 442 |
stream has reached end-of-file. Implementations should be careful that |
| 443 |
they return ``b""`` if, and only if, the stream has reached |
| 444 |
end-of-file! |
| 445 |
|
| 446 |
Args: |
| 447 |
max_bytes (int): The maximum number of bytes to return. Must be |
| 448 |
greater than zero. Optional; if omitted, then the stream object |
| 449 |
is free to pick a reasonable default. |
| 450 |
|
| 451 |
Returns: |
| 452 |
bytes or bytearray: The data received. |
| 453 |
|
| 454 |
Raises: |
| 455 |
trio.BusyResourceError: if two tasks attempt to call |
| 456 |
:meth:`receive_some` on the same stream at the same time. |
| 457 |
trio.BrokenResourceError: if something has gone wrong, and the stream |
| 458 |
is broken. |
| 459 |
trio.ClosedResourceError: if you previously closed this stream |
| 460 |
object, or if another task closes this stream object while |
| 461 |
:meth:`receive_some` is running. |
| 462 |
|
| 463 |
""" |
| 464 |
|
| 465 |
def __aiter__(self) -> Self: |
| 466 |
return self |
| 467 |
|
| 468 |
async def __anext__(self) -> bytes | bytearray: |
| 469 |
data = await self.receive_some() |
| 470 |
if not data: |
| 471 |
raise StopAsyncIteration |
| 472 |
return data |
| 473 |
|
| 474 |
|
| 475 |
class Stream(SendStream, ReceiveStream): |
| 476 |
"""A standard interface for interacting with bidirectional byte streams. |
| 477 |
|
| 478 |
A :class:`Stream` is an object that implements both the |
| 479 |
:class:`SendStream` and :class:`ReceiveStream` interfaces. |
| 480 |
|
| 481 |
If implementing this interface, you should consider whether you can go one |
| 482 |
step further and implement :class:`HalfCloseableStream`. |
| 483 |
|
| 484 |
""" |
| 485 |
|
| 486 |
__slots__ = () |
| 487 |
|
| 488 |
|
| 489 |
class HalfCloseableStream(Stream): |
| 490 |
"""This interface extends :class:`Stream` to also allow closing the send |
| 491 |
part of the stream without closing the receive part. |
| 492 |
|
| 493 |
""" |
| 494 |
|
| 495 |
__slots__ = () |
| 496 |
|
| 497 |
@abstractmethod |
| 498 |
async def send_eof(self) -> None: |
| 499 |
"""Send an end-of-file indication on this stream, if possible. |
| 500 |
|
| 501 |
The difference between :meth:`send_eof` and |
| 502 |
:meth:`~AsyncResource.aclose` is that :meth:`send_eof` is a |
| 503 |
*unidirectional* end-of-file indication. After you call this method, |
| 504 |
you shouldn't try sending any more data on this stream, and your |
| 505 |
remote peer should receive an end-of-file indication (eventually, |
| 506 |
after receiving all the data you sent before that). But, they may |
| 507 |
continue to send data to you, and you can continue to receive it by |
| 508 |
calling :meth:`~ReceiveStream.receive_some`. You can think of it as |
| 509 |
calling :meth:`~AsyncResource.aclose` on just the |
| 510 |
:class:`SendStream` "half" of the stream object (and in fact that's |
| 511 |
literally how :class:`trio.StapledStream` implements it). |
| 512 |
|
| 513 |
Examples: |
| 514 |
|
| 515 |
* On a socket, this corresponds to ``shutdown(..., SHUT_WR)`` (`man |
| 516 |
page <https://linux.die.net/man/2/shutdown>`__). |
| 517 |
|
| 518 |
* The SSH protocol provides the ability to multiplex bidirectional |
| 519 |
"channels" on top of a single encrypted connection. A Trio |
| 520 |
implementation of SSH could expose these channels as |
| 521 |
:class:`HalfCloseableStream` objects, and calling :meth:`send_eof` |
| 522 |
would send an ``SSH_MSG_CHANNEL_EOF`` request (see `RFC 4254 §5.3 |
| 523 |
<https://tools.ietf.org/html/rfc4254#section-5.3>`__). |
| 524 |
|
| 525 |
* On an SSL/TLS-encrypted connection, the protocol doesn't provide any |
| 526 |
way to do a unidirectional shutdown without closing the connection |
| 527 |
entirely, so :class:`~trio.SSLStream` implements |
| 528 |
:class:`Stream`, not :class:`HalfCloseableStream`. |
| 529 |
|
| 530 |
If an EOF has already been sent, then this method should silently |
| 531 |
succeed. |
| 532 |
|
| 533 |
Raises: |
| 534 |
trio.BusyResourceError: if another task is already executing a |
| 535 |
:meth:`~SendStream.send_all`, |
| 536 |
:meth:`~SendStream.wait_send_all_might_not_block`, or |
| 537 |
:meth:`send_eof` on this stream. |
| 538 |
trio.BrokenResourceError: if something has gone wrong, and the stream |
| 539 |
is broken. |
| 540 |
trio.ClosedResourceError: if you previously closed this stream |
| 541 |
object, or if another task closes this stream object while |
| 542 |
:meth:`send_eof` is running. |
| 543 |
|
| 544 |
""" |
| 545 |
|
| 546 |
|
| 547 |
# A regular invariant generic type |
| 548 |
T = TypeVar("T") |
| 549 |
|
| 550 |
# The type of object produced by a ReceiveChannel (covariant because |
| 551 |
# ReceiveChannel[Derived] can be passed to someone expecting |
| 552 |
# ReceiveChannel[Base]) |
| 553 |
ReceiveType = TypeVar("ReceiveType", covariant=True) |
| 554 |
|
| 555 |
# The type of object accepted by a SendChannel (contravariant because |
| 556 |
# SendChannel[Base] can be passed to someone expecting |
| 557 |
# SendChannel[Derived]) |
| 558 |
SendType = TypeVar("SendType", contravariant=True) |
| 559 |
|
| 560 |
# The type of object produced by a Listener (covariant plus must be |
| 561 |
# an AsyncResource) |
| 562 |
T_resource = TypeVar("T_resource", bound=AsyncResource, covariant=True) |
| 563 |
|
| 564 |
|
| 565 |
class Listener(AsyncResource, Generic[T_resource]): |
| 566 |
"""A standard interface for listening for incoming connections. |
| 567 |
|
| 568 |
:class:`Listener` objects also implement the :class:`AsyncResource` |
| 569 |
interface, so they can be closed by calling :meth:`~AsyncResource.aclose` |
| 570 |
or using an ``async with`` block. |
| 571 |
|
| 572 |
""" |
| 573 |
|
| 574 |
__slots__ = () |
| 575 |
|
| 576 |
@abstractmethod |
| 577 |
async def accept(self) -> T_resource: |
| 578 |
"""Wait until an incoming connection arrives, and then return it. |
| 579 |
|
| 580 |
Returns: |
| 581 |
AsyncResource: An object representing the incoming connection. In |
| 582 |
practice this is generally some kind of :class:`Stream`, |
| 583 |
but in principle you could also define a :class:`Listener` that |
| 584 |
returned, say, channel objects. |
| 585 |
|
| 586 |
Raises: |
| 587 |
trio.BusyResourceError: if two tasks attempt to call |
| 588 |
:meth:`accept` on the same listener at the same time. |
| 589 |
trio.ClosedResourceError: if you previously closed this listener |
| 590 |
object, or if another task closes this listener object while |
| 591 |
:meth:`accept` is running. |
| 592 |
|
| 593 |
Listeners don't generally raise :exc:`~trio.BrokenResourceError`, |
| 594 |
because for listeners there is no general condition of "the |
| 595 |
network/remote peer broke the connection" that can be handled in a |
| 596 |
generic way, like there is for streams. Other errors *can* occur and |
| 597 |
be raised from :meth:`accept` – for example, if you run out of file |
| 598 |
descriptors then you might get an :class:`OSError` with its errno set |
| 599 |
to ``EMFILE``. |
| 600 |
|
| 601 |
""" |
| 602 |
|
| 603 |
|
| 604 |
class SendChannel(AsyncResource, Generic[SendType]): |
| 605 |
"""A standard interface for sending Python objects to some receiver. |
| 606 |
|
| 607 |
`SendChannel` objects also implement the `AsyncResource` interface, so |
| 608 |
they can be closed by calling `~AsyncResource.aclose` or using an ``async |
| 609 |
with`` block. |
| 610 |
|
| 611 |
If you want to send raw bytes rather than Python objects, see |
| 612 |
`SendStream`. |
| 613 |
|
| 614 |
""" |
| 615 |
|
| 616 |
__slots__ = () |
| 617 |
|
| 618 |
@abstractmethod |
| 619 |
async def send(self, value: SendType) -> None: |
| 620 |
"""Attempt to send an object through the channel, blocking if necessary. |
| 621 |
|
| 622 |
Args: |
| 623 |
value (object): The object to send. |
| 624 |
|
| 625 |
Raises: |
| 626 |
trio.BrokenResourceError: if something has gone wrong, and the |
| 627 |
channel is broken. For example, you may get this if the receiver |
| 628 |
has already been closed. |
| 629 |
trio.ClosedResourceError: if you previously closed this |
| 630 |
:class:`SendChannel` object, or if another task closes it while |
| 631 |
:meth:`send` is running. |
| 632 |
trio.BusyResourceError: some channels allow multiple tasks to call |
| 633 |
`send` at the same time, but others don't. If you try to call |
| 634 |
`send` simultaneously from multiple tasks on a channel that |
| 635 |
doesn't support it, then you can get `~trio.BusyResourceError`. |
| 636 |
|
| 637 |
""" |
| 638 |
|
| 639 |
|
| 640 |
class ReceiveChannel(AsyncResource, Generic[ReceiveType]): |
| 641 |
"""A standard interface for receiving Python objects from some sender. |
| 642 |
|
| 643 |
You can iterate over a :class:`ReceiveChannel` using an ``async for`` |
| 644 |
loop:: |
| 645 |
|
| 646 |
async for value in receive_channel: |
| 647 |
... |
| 648 |
|
| 649 |
This is equivalent to calling :meth:`receive` repeatedly. The loop exits |
| 650 |
without error when `receive` raises `~trio.EndOfChannel`. |
| 651 |
|
| 652 |
`ReceiveChannel` objects also implement the `AsyncResource` interface, so |
| 653 |
they can be closed by calling `~AsyncResource.aclose` or using an ``async |
| 654 |
with`` block. |
| 655 |
|
| 656 |
If you want to receive raw bytes rather than Python objects, see |
| 657 |
`ReceiveStream`. |
| 658 |
|
| 659 |
""" |
| 660 |
|
| 661 |
__slots__ = () |
| 662 |
|
| 663 |
@abstractmethod |
| 664 |
async def receive(self) -> ReceiveType: |
| 665 |
"""Attempt to receive an incoming object, blocking if necessary. |
| 666 |
|
| 667 |
Returns: |
| 668 |
object: Whatever object was received. |
| 669 |
|
| 670 |
Raises: |
| 671 |
trio.EndOfChannel: if the sender has been closed cleanly, and no |
| 672 |
more objects are coming. This is not an error condition. |
| 673 |
trio.ClosedResourceError: if you previously closed this |
| 674 |
:class:`ReceiveChannel` object. |
| 675 |
trio.BrokenResourceError: if something has gone wrong, and the |
| 676 |
channel is broken. |
| 677 |
trio.BusyResourceError: some channels allow multiple tasks to call |
| 678 |
`receive` at the same time, but others don't. If you try to call |
| 679 |
`receive` simultaneously from multiple tasks on a channel that |
| 680 |
doesn't support it, then you can get `~trio.BusyResourceError`. |
| 681 |
|
| 682 |
""" |
| 683 |
|
| 684 |
def __aiter__(self) -> Self: |
| 685 |
return self |
| 686 |
|
| 687 |
async def __anext__(self) -> ReceiveType: |
| 688 |
try: |
| 689 |
return await self.receive() |
| 690 |
except trio.EndOfChannel: |
| 691 |
raise StopAsyncIteration from None |
| 692 |
|
| 693 |
|
| 694 |
# these are necessary for Sphinx's :show-inheritance: with type args. |
| 695 |
# (this should be removed if possible) |
| 696 |
# see: https://github.com/python/cpython/issues/123250 |
| 697 |
SendChannel.__module__ = SendChannel.__module__.replace("_abc", "abc") |
| 698 |
ReceiveChannel.__module__ = ReceiveChannel.__module__.replace("_abc", "abc") |
| 699 |
Listener.__module__ = Listener.__module__.replace("_abc", "abc") |
| 700 |
|
| 701 |
|
| 702 |
class Channel(SendChannel[T], ReceiveChannel[T]): |
| 703 |
"""A standard interface for interacting with bidirectional channels. |
| 704 |
|
| 705 |
A `Channel` is an object that implements both the `SendChannel` and |
| 706 |
`ReceiveChannel` interfaces, so you can both send and receive objects. |
| 707 |
|
| 708 |
""" |
| 709 |
|
| 710 |
__slots__ = () |
| 711 |
|
| 712 |
|
| 713 |
# see above |
| 714 |
Channel.__module__ = Channel.__module__.replace("_abc", "abc") |