Pipes¤
A pipe between two channels.
The Pipe class takes a receiver and a sender and
creates a pipe between them by forwarding all the messages received by the receiver
to the sender.
When its receiver stops, the pipe closes its sender and stops.
If sending fails with a
TransientSenderError, for example a
SenderHasNoReceiversError because
the sender's channel has no receivers, the pipe logs it, drops the message and keeps
sending the messages that follow, as the sender and its channel can still be used.
It logs a SenderHasNoReceiversError
at debug level and any other
TransientSenderError as a warning.
If sending fails with any other SenderError, the
pipe logs it with its traceback, closes both its sender and its receiver, and
stops. With close_pipe_on_send_error=False, it drops the message instead, and
keeps sending the messages that follow. That option has no effect on a
TransientSenderError, as the pipe never
stops for it.
stop() normally leaves its sender and receiver open.
So does any exception while receiving, other than the receiver stopping, and any
exception from sending that isn't a SenderError.
Such an exception ends the pipe's task and is logged with its traceback. A later
stop() doesn't raise it.
If automatic closing has already started, stop()
and context exit wait for it to finish. Cancelling the wait doesn't interrupt closing.
In any other case than the ones above where the pipe closes them, whoever created the sender and the receiver is still responsible for closing them. Give the pipe a clone of the sender if you still need to send after the pipe stops on its own.
Example
import asyncio
from contextlib import closing, AsyncExitStack
from frequenz.channels import BroadcastChannel, Pipe
async def main() -> None:
# Senders, receivers and Pipe are in AsyncExitStack
# to close and stop them at the end.
async with AsyncExitStack() as stack:
source_sender, source_receiver = BroadcastChannel[int](
name="source channel"
)
stack.push_async_callback(source_sender.aclose)
stack.enter_context(closing(source_receiver))
forwarding_sender, receiver = BroadcastChannel[int](
name="forwarding channel"
)
stack.push_async_callback(forwarding_sender.aclose)
stack.enter_context(closing(receiver))
await stack.enter_async_context(Pipe(source_receiver, forwarding_sender))
await source_sender.send(10)
assert await receiver.receive() == 10
asyncio.run(main())