Debian Codegraph @

src/trio/_channel.py

raw
1 from __future__ import annotations
2
3 import sys
4 from collections import OrderedDict, deque
5 from collections.abc import AsyncGenerator, Callable # noqa: TC003 # Needed for Sphinx
6 from contextlib import AbstractAsyncContextManager, asynccontextmanager
7 from functools import wraps
8 from math import inf
9 from typing import (
10 TYPE_CHECKING,
11 Generic,
12 )
13
14 import attrs
15 from outcome import Error, Value
16
17 import trio
18
19 from ._abc import ReceiveChannel, ReceiveType, SendChannel, SendType, T
20 from ._core import Abort, BrokenResourceError, RaiseCancelT, Task, enable_ki_protection
21 from ._util import (
22 MultipleExceptionError,
23 NoPublicConstructor,
24 final,
25 raise_single_exception_from_group,
26 )
27
28 if sys.version_info < (3, 11):
29 from exceptiongroup import BaseExceptionGroup
30
31 if TYPE_CHECKING:
32 from types import TracebackType
33
34 from typing_extensions import ParamSpec, Self
35
36 P = ParamSpec("P")
37 elif "sphinx.ext.autodoc" in sys.modules:
38 # P needs to exist for Sphinx to parse the type hints successfully.
39 try:
40 from typing_extensions import ParamSpec
41 except ImportError:
42 P = ... # This is valid in Callable, though not correct
43 else:
44 P = ParamSpec("P")
45
46
47 # written as a class so you can say open_memory_channel[int](5)
48 @final
49 class open_memory_channel(tuple["MemorySendChannel[T]", "MemoryReceiveChannel[T]"]):
50 """Open a channel for passing objects between tasks within a process.
51
52 Memory channels are lightweight, cheap to allocate, and entirely
53 in-memory. They don't involve any operating-system resources, or any kind
54 of serialization. They just pass Python objects directly between tasks
55 (with a possible stop in an internal buffer along the way).
56
57 Channel objects can be closed by calling `~trio.abc.AsyncResource.aclose`
58 or using ``async with``. They are *not* automatically closed when garbage
59 collected. Closing memory channels isn't mandatory, but it is generally a
60 good idea, because it helps avoid situations where tasks get stuck waiting
61 on a channel when there's no-one on the other side. See
62 :ref:`channel-shutdown` for details.
63
64 Memory channel operations are all atomic with respect to
65 cancellation, either `~trio.abc.ReceiveChannel.receive` will
66 successfully return an object, or it will raise :exc:`Cancelled`
67 while leaving the channel unchanged.
68
69 Args:
70 max_buffer_size (int or math.inf): The maximum number of items that can
71 be buffered in the channel before :meth:`~trio.abc.SendChannel.send`
72 blocks. Choosing a sensible value here is important to ensure that
73 backpressure is communicated promptly and avoid unnecessary latency;
74 see :ref:`channel-buffering` for more details. If in doubt, use 0.
75
76 Returns:
77 A pair ``(send_channel, receive_channel)``. If you have
78 trouble remembering which order these go in, remember: data
79 flows from left → right.
80
81 In addition to the standard channel methods, all memory channel objects
82 provide a ``statistics()`` method, which returns an object with the
83 following fields:
84
85 * ``current_buffer_used``: The number of items currently stored in the
86 channel buffer.
87 * ``max_buffer_size``: The maximum number of items allowed in the buffer,
88 as passed to :func:`open_memory_channel`.
89 * ``open_send_channels``: The number of open
90 :class:`MemorySendChannel` endpoints pointing to this channel.
91 Initially 1, but can be increased by
92 :meth:`MemorySendChannel.clone`.
93 * ``open_receive_channels``: Likewise, but for open
94 :class:`MemoryReceiveChannel` endpoints.
95 * ``tasks_waiting_send``: The number of tasks blocked in ``send`` on this
96 channel (summing over all clones).
97 * ``tasks_waiting_receive``: The number of tasks blocked in ``receive`` on
98 this channel (summing over all clones).
99 * ``peak_buffer_used``: The largest number of items that have been in the
100 buffer at once since the channel was created.
101 """
102
103 def __new__( # type: ignore[misc] # "must return a subtype"
104 cls,
105 max_buffer_size: int | float, # noqa: PYI041
106 ) -> tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]:
107 if max_buffer_size != inf and not isinstance(max_buffer_size, int):
108 raise TypeError("max_buffer_size must be an integer or math.inf")
109 if max_buffer_size < 0:
110 raise ValueError("max_buffer_size must be >= 0")
111 state: MemoryChannelState[T] = MemoryChannelState(max_buffer_size)
112 return (
113 MemorySendChannel[T]._create(state),
114 MemoryReceiveChannel[T]._create(state),
115 )
116
117 def __init__(self, max_buffer_size: int | float) -> None: # noqa: PYI041
118 ...
119
120
121 @attrs.frozen
122 class MemoryChannelStatistics:
123 """Statistics describing the current state of a memory channel.
124
125 Returned by :meth:`MemorySendChannel.statistics` and
126 :meth:`MemoryReceiveChannel.statistics`.
127 """
128
129 current_buffer_used: int
130 """The number of items currently stored in the channel buffer."""
131
132 max_buffer_size: int | float
133 """The maximum number of items that can be buffered in the channel."""
134
135 open_send_channels: int
136 """The number of open :class:`MemorySendChannel` endpoints pointing to this channel."""
137
138 open_receive_channels: int
139 """The number of open :class:`MemoryReceiveChannel` endpoints pointing to this channel."""
140
141 tasks_waiting_send: int
142 """The number of tasks currently blocked waiting to send."""
143
144 tasks_waiting_receive: int
145 """The number of tasks currently blocked waiting to receive."""
146
147 peak_buffer_used: int
148 """The largest number of items that have been in the buffer at once
149 since the channel was created."""
150
151
152 @attrs.define
153 class MemoryChannelState(Generic[T]):
154 max_buffer_size: int | float
155 data: deque[T] = attrs.Factory(deque)
156 # Counts of open endpoints using this state
157 open_send_channels: int = 0
158 open_receive_channels: int = 0
159 # {task: value}
160 send_tasks: OrderedDict[Task, T] = attrs.Factory(OrderedDict)
161 # {task: None}
162 receive_tasks: OrderedDict[Task, None] = attrs.Factory(OrderedDict)
163 # The largest len(self.data) has ever been
164 peak_buffer_used: int = 0
165
166 def statistics(self) -> MemoryChannelStatistics:
167 return MemoryChannelStatistics(
168 current_buffer_used=len(self.data),
169 max_buffer_size=self.max_buffer_size,
170 open_send_channels=self.open_send_channels,
171 open_receive_channels=self.open_receive_channels,
172 tasks_waiting_send=len(self.send_tasks),
173 tasks_waiting_receive=len(self.receive_tasks),
174 peak_buffer_used=self.peak_buffer_used,
175 )
176
177
178 @final
179 @attrs.define(eq=False, repr=False, slots=False)
180 class MemorySendChannel(SendChannel[SendType], metaclass=NoPublicConstructor):
181 """A memory channel endpoint for sending Python objects.
182
183 Instances of this class are created by
184 :func:`open_memory_channel` and cannot be instantiated directly.
185 """
186
187 _state: MemoryChannelState[SendType]
188 _closed: bool = False
189 # This is just the tasks waiting on *this* object. As compared to
190 # self._state.send_tasks, which includes tasks from this object and
191 # all clones.
192 _tasks: set[Task] = attrs.Factory(set)
193
194 def __attrs_post_init__(self) -> None:
195 self._state.open_send_channels += 1
196
197 def __repr__(self) -> str:
198 return f"<send channel at {id(self):#x}, using buffer at {id(self._state):#x}>"
199
200 def statistics(self) -> MemoryChannelStatistics:
201 """Returns a `MemoryChannelStatistics` for the memory channel this is
202 associated with."""
203 # XX should we also report statistics specific to this object?
204 return self._state.statistics()
205
206 @enable_ki_protection
207 def send_nowait(self, value: SendType) -> None:
208 """Like `~trio.abc.SendChannel.send`, but if the channel's buffer is
209 full, raises `WouldBlock` instead of blocking.
210
211 """
212 if self._closed:
213 raise trio.ClosedResourceError
214 if self._state.open_receive_channels == 0:
215 raise trio.BrokenResourceError
216 if self._state.receive_tasks:
217 assert not self._state.data
218 task, _ = self._state.receive_tasks.popitem(last=False)
219 task.custom_sleep_data._tasks.remove(task)
220 trio.lowlevel.reschedule(task, Value(value))
221 elif len(self._state.data) < self._state.max_buffer_size:
222 self._state.data.append(value)
223 self._state.peak_buffer_used = max(
224 self._state.peak_buffer_used,
225 len(self._state.data),
226 )
227 else:
228 raise trio.WouldBlock
229
230 @enable_ki_protection
231 async def send(self, value: SendType) -> None:
232 """See `SendChannel.send <trio.abc.SendChannel.send>`.
233
234 Memory channels allow multiple tasks to call `send` at the same time.
235
236 """
237 await trio.lowlevel.checkpoint_if_cancelled()
238 try:
239 self.send_nowait(value)
240 except trio.WouldBlock:
241 pass
242 else:
243 await trio.lowlevel.cancel_shielded_checkpoint()
244 return
245
246 task = trio.lowlevel.current_task()
247 self._tasks.add(task)
248 self._state.send_tasks[task] = value
249 task.custom_sleep_data = self
250
251 def abort_fn(_: RaiseCancelT) -> Abort:
252 self._tasks.remove(task)
253 del self._state.send_tasks[task]
254 return trio.lowlevel.Abort.SUCCEEDED
255
256 await trio.lowlevel.wait_task_rescheduled(abort_fn)
257
258 # Return type must be stringified or use a TypeVar
259 @enable_ki_protection
260 def clone(self) -> MemorySendChannel[SendType]:
261 """Clone this send channel object.
262
263 This returns a new `MemorySendChannel` object, which acts as a
264 duplicate of the original: sending on the new object does exactly the
265 same thing as sending on the old object. (If you're familiar with
266 `os.dup`, then this is a similar idea.)
267
268 However, closing one of the objects does not close the other, and
269 receivers don't get `EndOfChannel` until *all* clones have been
270 closed.
271
272 This is useful for communication patterns that involve multiple
273 producers all sending objects to the same destination. If you give
274 each producer its own clone of the `MemorySendChannel`, and then make
275 sure to close each `MemorySendChannel` when it's finished, receivers
276 will automatically get notified when all producers are finished. See
277 :ref:`channel-mpmc` for examples.
278
279 Raises:
280 trio.ClosedResourceError: if you already closed this
281 `MemorySendChannel` object.
282
283 """
284 if self._closed:
285 raise trio.ClosedResourceError
286 return MemorySendChannel._create(self._state)
287
288 def __enter__(self) -> Self:
289 return self
290
291 def __exit__(
292 self,
293 exc_type: type[BaseException] | None,
294 exc_value: BaseException | None,
295 traceback: TracebackType | None,
296 ) -> None:
297 self.close()
298
299 @enable_ki_protection
300 def close(self) -> None:
301 """Close this send channel object synchronously.
302
303 All channel objects have an asynchronous `~.AsyncResource.aclose` method.
304 Memory channels can also be closed synchronously. This has the same
305 effect on the channel and other tasks using it, but `close` is not a
306 trio checkpoint. This simplifies cleaning up in cancelled tasks.
307
308 Using ``with send_channel:`` will close the channel object on leaving
309 the with block.
310
311 """
312 if self._closed:
313 return
314 self._closed = True
315 for task in self._tasks:
316 trio.lowlevel.reschedule(task, Error(trio.ClosedResourceError()))
317 del self._state.send_tasks[task]
318 self._tasks.clear()
319 self._state.open_send_channels -= 1
320 if self._state.open_send_channels == 0:
321 assert not self._state.send_tasks
322 for task in self._state.receive_tasks:
323 task.custom_sleep_data._tasks.remove(task)
324 trio.lowlevel.reschedule(task, Error(trio.EndOfChannel()))
325 self._state.receive_tasks.clear()
326
327 @enable_ki_protection
328 async def aclose(self) -> None:
329 """Close this send channel object asynchronously.
330
331 See `MemorySendChannel.close`."""
332 self.close()
333 await trio.lowlevel.checkpoint()
334
335
336 @final
337 @attrs.define(eq=False, repr=False, slots=False)
338 class MemoryReceiveChannel(ReceiveChannel[ReceiveType], metaclass=NoPublicConstructor):
339 """A memory channel endpoint for receiving Python objects.
340
341 Instances of this class are created by
342 :func:`open_memory_channel` and cannot be instantiated directly.
343 """
344
345 _state: MemoryChannelState[ReceiveType]
346 _closed: bool = False
347 _tasks: set[trio._core._run.Task] = attrs.Factory(set)
348
349 def __attrs_post_init__(self) -> None:
350 self._state.open_receive_channels += 1
351
352 def statistics(self) -> MemoryChannelStatistics:
353 """Returns a `MemoryChannelStatistics` for the memory channel this is
354 associated with."""
355 return self._state.statistics()
356
357 def __repr__(self) -> str:
358 return (
359 f"<receive channel at {id(self):#x}, using buffer at {id(self._state):#x}>"
360 )
361
362 @enable_ki_protection
363 def receive_nowait(self) -> ReceiveType:
364 """Like `~trio.abc.ReceiveChannel.receive`, but if there's nothing
365 ready to receive, raises `WouldBlock` instead of blocking.
366
367 """
368 if self._closed:
369 raise trio.ClosedResourceError
370 if self._state.send_tasks:
371 task, value = self._state.send_tasks.popitem(last=False)
372 task.custom_sleep_data._tasks.remove(task)
373 trio.lowlevel.reschedule(task)
374 self._state.data.append(value)
375 # Fall through
376 if self._state.data:
377 return self._state.data.popleft()
378 if not self._state.open_send_channels:
379 raise trio.EndOfChannel
380 raise trio.WouldBlock
381
382 @enable_ki_protection
383 async def receive(self) -> ReceiveType:
384 """See `ReceiveChannel.receive <trio.abc.ReceiveChannel.receive>`.
385
386 Memory channels allow multiple tasks to call `receive` at the same
387 time. The first task will get the first item sent, the second task
388 will get the second item sent, and so on.
389
390 """
391 await trio.lowlevel.checkpoint_if_cancelled()
392 try:
393 value = self.receive_nowait()
394 except trio.WouldBlock:
395 pass
396 else:
397 await trio.lowlevel.cancel_shielded_checkpoint()
398 return value
399
400 task = trio.lowlevel.current_task()
401 self._tasks.add(task)
402 self._state.receive_tasks[task] = None
403 task.custom_sleep_data = self
404
405 def abort_fn(_: RaiseCancelT) -> Abort:
406 self._tasks.remove(task)
407 del self._state.receive_tasks[task]
408 return trio.lowlevel.Abort.SUCCEEDED
409
410 # Not strictly guaranteed to return ReceiveType, but will do so unless
411 # you intentionally reschedule with a bad value.
412 return await trio.lowlevel.wait_task_rescheduled(abort_fn) # type: ignore[no-any-return]
413
414 @enable_ki_protection
415 def clone(self) -> MemoryReceiveChannel[ReceiveType]:
416 """Clone this receive channel object.
417
418 This returns a new `MemoryReceiveChannel` object, which acts as a
419 duplicate of the original: receiving on the new object does exactly
420 the same thing as receiving on the old object.
421
422 However, closing one of the objects does not close the other, and the
423 underlying channel is not closed until all clones are closed. (If
424 you're familiar with `os.dup`, then this is a similar idea.)
425
426 This is useful for communication patterns that involve multiple
427 consumers all receiving objects from the same underlying channel. See
428 :ref:`channel-mpmc` for examples.
429
430 .. warning:: The clones all share the same underlying channel.
431 Whenever a clone :meth:`receive`\\s a value, it is removed from the
432 channel and the other clones do *not* receive that value. If you
433 want to send multiple copies of the same stream of values to
434 multiple destinations, like :func:`itertools.tee`, then you need to
435 find some other solution; this method does *not* do that.
436
437 Raises:
438 trio.ClosedResourceError: if you already closed this
439 `MemoryReceiveChannel` object.
440
441 """
442 if self._closed:
443 raise trio.ClosedResourceError
444 return MemoryReceiveChannel._create(self._state)
445
446 def __enter__(self) -> Self:
447 return self
448
449 def __exit__(
450 self,
451 exc_type: type[BaseException] | None,
452 exc_value: BaseException | None,
453 traceback: TracebackType | None,
454 ) -> None:
455 self.close()
456
457 @enable_ki_protection
458 def close(self) -> None:
459 """Close this receive channel object synchronously.
460
461 All channel objects have an asynchronous `~.AsyncResource.aclose` method.
462 Memory channels can also be closed synchronously. This has the same
463 effect on the channel and other tasks using it, but `close` is not a
464 trio checkpoint. This simplifies cleaning up in cancelled tasks.
465
466 Using ``with receive_channel:`` will close the channel object on
467 leaving the with block.
468
469 """
470 if self._closed:
471 return
472 self._closed = True
473 for task in self._tasks:
474 trio.lowlevel.reschedule(task, Error(trio.ClosedResourceError()))
475 del self._state.receive_tasks[task]
476 self._tasks.clear()
477 self._state.open_receive_channels -= 1
478 if self._state.open_receive_channels == 0:
479 assert not self._state.receive_tasks
480 for task in self._state.send_tasks:
481 task.custom_sleep_data._tasks.remove(task)
482 trio.lowlevel.reschedule(task, Error(trio.BrokenResourceError()))
483 self._state.send_tasks.clear()
484 self._state.data.clear()
485
486 @enable_ki_protection
487 async def aclose(self) -> None:
488 """Close this receive channel object asynchronously.
489
490 See `MemoryReceiveChannel.close`."""
491 self.close()
492 await trio.lowlevel.checkpoint()
493
494
495 class RecvChanWrapper(ReceiveChannel[T]):
496 def __init__(
497 self, recv_chan: MemoryReceiveChannel[T], send_semaphore: trio.Semaphore
498 ) -> None:
499 self._recv_chan = recv_chan
500 self._send_semaphore = send_semaphore
501
502 async def receive(self) -> T:
503 self._send_semaphore.release()
504 return await self._recv_chan.receive()
505
506 async def aclose(self) -> None:
507 await self._recv_chan.aclose()
508
509 def __enter__(self) -> Self:
510 return self
511
512 def __exit__(
513 self,
514 exc_type: type[BaseException] | None,
515 exc_value: BaseException | None,
516 traceback: TracebackType | None,
517 ) -> None:
518 self._recv_chan.close()
519
520
521 def as_safe_channel(
522 fn: Callable[P, AsyncGenerator[T, None]],
523 ) -> Callable[P, AbstractAsyncContextManager[ReceiveChannel[T]]]:
524 """Decorate an async generator function to make it cancellation-safe.
525
526 The ``yield`` keyword offers a very convenient way to write iterators...
527 which makes it really unfortunate that async generators are so difficult
528 to call correctly. Yielding from the inside of a cancel scope or a nursery
529 to the outside `violates structured concurrency <https://xkcd.com/292/>`_
530 with consequences explained in :pep:`789`. Even then, resource cleanup
531 errors remain common (:pep:`533`) unless you wrap every call in
532 :func:`~contextlib.aclosing`.
533
534 This decorator gives you the best of both worlds: with careful exception
535 handling and a background task we preserve structured concurrency by
536 offering only the safe interface, and you can still write your iterables
537 with the convenience of ``yield``. For example::
538
539 @as_safe_channel
540 async def my_async_iterable(arg, *, kwarg=True):
541 while ...:
542 item = await ...
543 yield item
544
545 async with my_async_iterable(...) as recv_chan:
546 async for item in recv_chan:
547 ...
548
549 While the combined async-with-async-for can be inconvenient at first,
550 the context manager is indispensable for both correctness and for prompt
551 cleanup of resources.
552 """
553 # Perhaps a future PEP will adopt `async with for` syntax, like
554 # https://coconut.readthedocs.io/en/master/DOCS.html#async-with-for
555
556 @asynccontextmanager
557 @wraps(fn)
558 async def context_manager(
559 *args: P.args, **kwargs: P.kwargs
560 ) -> AsyncGenerator[trio._channel.RecvChanWrapper[T], None]:
561 send_chan, recv_chan = trio.open_memory_channel[T](0)
562 try:
563 async with trio.open_nursery(strict_exception_groups=True) as nursery:
564 agen = fn(*args, **kwargs)
565 send_semaphore = trio.Semaphore(0)
566 # `nursery.start` to make sure that we will clean up send_chan & agen
567 # If this errors we don't close `recv_chan`, but the caller
568 # never gets access to it, so that's not a problem.
569 await nursery.start(
570 _move_elems_to_channel, agen, send_chan, send_semaphore
571 )
572 # `async with recv_chan` could eat exceptions, so use sync cm
573 with RecvChanWrapper(recv_chan, send_semaphore) as wrapped_recv_chan:
574 yield wrapped_recv_chan
575 # User has exited context manager, cancel to immediately close the
576 # abandoned generator if it's still alive.
577 nursery.cancel_scope.cancel(
578 "exited trio.as_safe_channel context manager"
579 )
580 except BaseExceptionGroup as eg:
581 try:
582 raise_single_exception_from_group(eg)
583 except MultipleExceptionError:
584 # In case user has except* we make it possible for them to handle the
585 # exceptions.
586 if sys.version_info >= (3, 11):
587 eg.add_note(
588 "Encountered exception during cleanup of generator object, as "
589 "well as exception in the contextmanager body - unable to unwrap."
590 )
591
592 raise eg from None
593
594 async def _move_elems_to_channel(
595 agen: AsyncGenerator[T, None],
596 send_chan: trio.MemorySendChannel[T],
597 send_semaphore: trio.Semaphore,
598 task_status: trio.TaskStatus,
599 ) -> None:
600 # `async with send_chan` will eat exceptions,
601 # see https://github.com/python-trio/trio/issues/1559
602 with send_chan:
603 # replace try-finally with contextlib.aclosing once python39 is
604 # dropped:
605 try:
606 task_status.started()
607 while True:
608 # wait for receiver to call next on the aiter
609 await send_semaphore.acquire()
610 if not send_chan._state.open_receive_channels:
611 # skip the possibly-expensive computation in the generator,
612 # if we know it will be impossible to send the result.
613 break
614 try:
615 value = await agen.__anext__()
616 except StopAsyncIteration:
617 return
618 # Send the value to the channel
619 try:
620 await send_chan.send(value)
621 except BrokenResourceError:
622 break # closed since we checked above
623 finally:
624 # work around `.aclose()` not suppressing GeneratorExit in an
625 # ExceptionGroup:
626 # TODO: make an issue on CPython about this
627 try:
628 await agen.aclose()
629 except BaseExceptionGroup as exceptions:
630 removed, narrowed_exceptions = exceptions.split(GeneratorExit)
631
632 # TODO: extract a helper to flatten exception groups
633 removed_exceptions: list[BaseException | None] = [removed]
634 genexits_seen = 0
635 for e in removed_exceptions:
636 if isinstance(e, BaseExceptionGroup):
637 removed_exceptions.extend(e.exceptions) # noqa: B909
638 else:
639 genexits_seen += 1
640
641 if genexits_seen > 1:
642 exc = AssertionError("More than one GeneratorExit found.")
643 if narrowed_exceptions is None:
644 narrowed_exceptions = exceptions.derive([exc])
645 else:
646 narrowed_exceptions = narrowed_exceptions.derive(
647 [*narrowed_exceptions.exceptions, exc]
648 )
649 if narrowed_exceptions is not None:
650 raise narrowed_exceptions from None
651
652 return context_manager