Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,13 @@

- Code that waited for such a channel to close after a send without receivers, for example by checking for a `ChannelClosedError` cause or for `is_closed`, should catch `SenderHasNoReceiversError` instead. It can then stop sending, or close all of the channel's senders to close the channel.

- An experimental `Pipe` now closes its sender when its receiver stops. Before, it left the sender open.
- `frequenz.channels.experimental.Pipe` is deprecated and will be removed in v3.0.0. Use the new `frequenz.channels.Pipe` instead, but check how your code closes the sender and the receiver of the pipe first, as the two behave differently:

- When sending fails with a `SenderError`, for example because the sender's `BroadcastChannel` has no receivers, a `Pipe` now closes both its sender and its receiver, and logs the error: a `SenderHasNoReceiversError` as a warning, and any other error with its traceback. Before, the pipe stopped but left both open.

- `Pipe.stop()` still leaves a pipe's 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`.

- To keep a `Pipe` running after a `SenderError`, pass `close_pipe_on_send_error=False`. It then drops the message, keeps sending the messages that follow, and logs a `SenderHasNoReceiversError` at debug level.

- Give a `Pipe` a clone of its sender if you still need to send after the pipe stops on its own.
- When its receiver stops, the new `Pipe` closes its sender. The experimental one stops and leaves the sender open.
- When sending fails with a `SenderError` that isn't a `TransientSenderError`, the new `Pipe` logs the error and closes both its sender and its receiver by default. The experimental one lets the exception end its task and leaves both open.
- When sending fails with a `TransientSenderError`, like a `SenderHasNoReceiversError`, the new `Pipe` logs it, drops the message and keeps forwarding. The experimental one lets the exception end its task.
- With `close_pipe_on_send_error=False`, the new `Pipe` also drops the message that failed with any other `SenderError` and keeps forwarding the next ones. This doesn't bring back the behavior of the experimental one.
- `stop()` leaves both ends open in both.

- `BroadcastSender.clone()` now raises a `SenderClosedError` if the sender is closed, and a `SenderError` if the channel is closed, like `send()` and `subscribe()` do. Clone a sender before closing it, or catch `SenderError`.

Expand All @@ -58,6 +56,8 @@

- `SenderHasNoReceiversError` is a new `TransientSenderError`. An open sender of a `BroadcastChannel`, or of a `Broadcast` created with `auto_close=True`, raises it from `send()` while the channel is open but has no receivers. The message is dropped, but with `resend_latest=True`, new receivers still get it if it is the last message sent and it isn't `None`. The channel stays open, so sending works again once a receiver subscribes.

- `Pipe` is now available in `frequenz.channels`. It forwards all the messages from a receiver to a sender, like `frequenz.channels.experimental.Pipe`, but it also closes its ends: when its receiver stops it closes its sender, and when sending fails with a `SenderError` that isn't a `TransientSenderError` it closes its sender and its receiver, unless you pass `close_pipe_on_send_error=False`, in which case it drops the message and keeps going. When sending fails with a `TransientSenderError`, like a `SenderHasNoReceiversError`, it logs it, drops the message and keeps forwarding, whatever `close_pipe_on_send_error` says. See the `Pipe` documentation for what the pipe leaves open and who has to close it.

- `BroadcastSender.has_receivers` and `BroadcastReceiver.has_senders` tell whether the other side of a broadcast channel is still there, so producers can stop producing messages that nobody would receive. A sender that was garbage-collected without being closed still counts.

## Bug Fixes
Expand Down
10 changes: 10 additions & 0 deletions docs/user-guide/utilities/pipes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Pipes

::: frequenz.channels._pipe.Pipe
options:
inherited_members: []
members: []
show_bases: false
show_root_heading: false
show_root_toc_entry: false
show_source: false
5 changes: 5 additions & 0 deletions src/frequenz/channels/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
* [`NopReceiver`][frequenz.channels.NopReceiver]: A place-holder receiver that
never receives a message.

* [`Pipe`][frequenz.channels.Pipe]: Forwards all the messages from a receiver to
a sender.

* [`WithPrevious`][frequenz.channels.WithPrevious]: A composable predicate to
filter messages based on the previous message received.

Expand Down Expand Up @@ -116,6 +119,7 @@
from ._merge import Merger, merge
from ._nop_receiver import NopReceiver
from ._oneshot import OneshotChannel, OneshotReceiver, OneshotSender
from ._pipe import Pipe
from ._receiver import Receiver, ReceiverError, ReceiverStoppedError
from ._select import (
Selected,
Expand Down Expand Up @@ -156,6 +160,7 @@
"OneshotChannel",
"OneshotReceiver",
"OneshotSender",
"Pipe",
"Receiver",
"ReceiverError",
"ReceiverMessageT_co",
Expand Down
201 changes: 201 additions & 0 deletions src/frequenz/channels/_pipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
# License: MIT
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH

"""Pipe between a receiver and a sender.

The [`Pipe`][frequenz.channels.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.
"""

from __future__ import annotations

import asyncio
import logging
import typing

from ._generic import ChannelMessageT
from ._receiver import Receiver
from ._sender import (
Sender,
SenderError,
SenderHasNoReceiversError,
TransientSenderError,
)

_logger = logging.getLogger(__name__)


class Pipe(typing.Generic[ChannelMessageT]):
"""A pipe between two channels.

The [`Pipe`][frequenz.channels.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`][frequenz.channels.TransientSenderError], for example a
[`SenderHasNoReceiversError`][frequenz.channels.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`][frequenz.channels.SenderHasNoReceiversError]
at debug level and any other
[`TransientSenderError`][frequenz.channels.TransientSenderError] as a warning.

If sending fails with any other [`SenderError`][frequenz.channels.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`][frequenz.channels.TransientSenderError], as the pipe never
stops for it.

[`stop()`][frequenz.channels.Pipe.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`][frequenz.channels.SenderError].
Such an exception ends the pipe's task and is logged with its traceback. A later
[`stop()`][frequenz.channels.Pipe.stop] doesn't raise it.

If automatic closing has already started, [`stop()`][frequenz.channels.Pipe.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:
```python
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())
```
"""

def __init__(
self,
receiver: Receiver[ChannelMessageT],
sender: Sender[ChannelMessageT],
*,
close_pipe_on_send_error: bool = True,
) -> None:
"""Create a new pipe between two channels.

Args:
receiver: The receiver channel.
sender: The sender channel.
close_pipe_on_send_error: Whether a
[`SenderError`][frequenz.channels.SenderError] from sending that isn't
a [`TransientSenderError`][frequenz.channels.TransientSenderError]
closes the sender and the receiver and stops the pipe. If `False`, the
pipe drops the message and keeps sending the messages that follow, even
if the sender is closed and every send fails.
"""
self._sender = sender
self._receiver = receiver
self._close_pipe_on_send_error = close_pipe_on_send_error
self._task: asyncio.Task[None] | None = None
self._closing = False

async def __aenter__(self) -> Pipe[ChannelMessageT]:
"""Enter the runtime context."""
await self.start()
return self

async def __aexit__(
self,
_exc_type: typing.Type[BaseException] | None,
_exc: BaseException | None,
_tb: typing.Any,
) -> None:
"""Exit the runtime context."""
await self.stop()

async def start(self) -> None:
"""Start this pipe if it is not already running."""
if not self._task or self._task.done():
self._closing = False
self._task = asyncio.create_task(self._run())
self._task.add_done_callback(self._log_task_failure)

async def stop(self) -> None:
"""Stop this pipe."""
task = self._task
if task and not task.done():
if not self._closing:
task.cancel()
# Only the pipe task's cancellation becomes a result. Cancellation of
# the caller still propagates, but must not interrupt automatic closing.
result = asyncio.gather(task, return_exceptions=True)
(error,) = await (asyncio.shield(result) if self._closing else result)
if error is not None and not isinstance(error, asyncio.CancelledError):
raise error

def _log_task_failure(self, task: asyncio.Task[None]) -> None:
"""Log a failure without waiting for the pipe task to be collected."""
if not task.cancelled() and (error := task.exception()) is not None:
_logger.error(
"Pipe from [%s] to [%s] stopped unexpectedly",
self._receiver,
self._sender,
exc_info=error,
)

async def _run(self) -> None:
outcome = "stopped" if self._close_pipe_on_send_error else "dropped a message"
async for value in self._receiver:
try:
await self._sender.send(value)
except TransientSenderError as error:
_logger.log(
(
logging.DEBUG
if isinstance(error, SenderHasNoReceiversError)
else logging.WARNING
),
"Pipe from [%s] to [%s] dropped a message: %s",
self._receiver,
self._sender,
error,
)
except SenderError:
_logger.exception(
"Pipe from [%s] to [%s] %s: sending failed",
self._receiver,
self._sender,
outcome,
)
if not self._close_pipe_on_send_error:
continue
self._closing = True
try:
await self._sender.aclose()
finally:
self._receiver.close()
return
self._closing = True
await self._sender.aclose()
Loading