Skip to content
Closed
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: 16 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ This will probably be the last minor release of v1. It deprecates everything tha

- `frequenz.channels.experimental.OptionalReceiver` will be removed in v2.0.0. Its deprecation warning now points at `frequenz.channels.NopReceiver`: use the receiver itself, or a `NopReceiver` when there is none.

- `frequenz.channels.experimental.Pipe` is deprecated and will be removed in v3.0.0. Its behavior is unchanged. 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 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`, the new `Pipe` logs a warning, 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.

The deprecation warning says so too: `frequenz.channels.experimental.Pipe is deprecated and will be removed in v3.0.0. Use frequenz.channels.Pipe instead, but check how your code closes its sender and receiver first: the new one closes its sender when its receiver stops, and both ends when sending fails, while this one leaves them open.`

- `frequenz.channels.timer.Timer` was renamed to `MonotonicTimer`, to make clear it uses the event loop's monotonic clock and to free the name `Timer` for a wall clock timer in a later version. `Timer` still works as a deprecated alias and will be removed in v2.0.0, as its deprecation warning says. The change is mechanical: replace `Timer` with `MonotonicTimer` in imports and uses.

- The `limit` argument of `BroadcastChannel()` and `BroadcastSender.subscribe()` is deprecated and will be removed in v2.0.0. Use the new `buffer_size` argument instead. It does the same, but its name says what is limited: the number of messages each receiver can hold.
Expand All @@ -37,6 +47,12 @@ This will probably be the last minor release of v1. It deprecates everything tha

- `NopReceiver` and `WithPrevious` are now stable, and available from `frequenz.channels`.

- `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`, it logs a warning, 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.

A send to a `BroadcastChannel` without receivers closes the channel and raises a plain `SenderError` in v1, so a `Pipe` sending to one stops and closes its ends by default. A `Broadcast` created with the default `auto_close=False` drops the message instead, and the pipe keeps going. In v2.0.0, a `BroadcastChannel` without receivers stays open, so the pipe keeps going too.

- `TransientSenderError` is a new `SenderError` for errors after which the sender and its channel can still be used: only that message wasn't sent. No sender in this library raises it yet, but `Pipe` already handles it, and custom senders can raise it.

## Bug Fixes

- `BroadcastChannel()` no longer emits the deprecation warning of `Broadcast`, which it uses internally. You were getting a warning about a class you never used.
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
10 changes: 10 additions & 0 deletions src/frequenz/channels/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,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 All @@ -60,6 +63,9 @@
* [`SenderError`][frequenz.channels.SenderError]: Base class for all errors
related to senders.

* [`TransientSenderError`][frequenz.channels.TransientSenderError]: Base class for
sender errors after which the sender can still be used.

* [`ReceiverError`][frequenz.channels.ReceiverError]: Base class for all errors
related to receivers.

Expand Down Expand Up @@ -100,6 +106,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 All @@ -115,6 +122,7 @@
SenderClosedError,
SenderError,
SubscribableSender,
TransientSenderError,
)
from ._with_previous import WithPrevious

Expand All @@ -138,6 +146,7 @@
"OneshotChannel",
"OneshotReceiver",
"OneshotSender",
"Pipe",
"Receiver",
"ReceiverError",
"ReceiverMessageT_co",
Expand All @@ -150,6 +159,7 @@
"SenderMessageT_co",
"SenderMessageT_contra",
"SubscribableSender",
"TransientSenderError",
"UnhandledSelectedError",
"WithPrevious",
"merge",
Expand Down
176 changes: 176 additions & 0 deletions src/frequenz/channels/_pipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# 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, 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], the pipe logs it
as a warning, drops the message and keeps sending the messages that follow, as the
sender and its channel can still be used.

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.

Note:
A [`BroadcastChannel`][frequenz.channels.BroadcastChannel] closes itself when a
message is sent to it while it has no receivers, and that send raises a
[`SenderError`][frequenz.channels.SenderError]. So when the pipe's sender
belongs to a [`BroadcastChannel`][frequenz.channels.BroadcastChannel] without
receivers, the pipe stops and, by default, closes both its ends. With
`close_pipe_on_send_error=False` the pipe keeps running, but it drops every
message, as the channel is closed for good. A
[`Broadcast`][frequenz.channels.Broadcast] created with the default
`auto_close=False` doesn't close itself: it drops the message and the pipe keeps
sending the messages that follow.

[`stop()`][frequenz.channels.Pipe.stop] leaves its sender and its 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 a later `stop()` doesn't raise it.

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

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._task = asyncio.create_task(self._run())

async def stop(self) -> None:
"""Stop this pipe."""
if self._task and not self._task.done():
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass

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.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
try:
await self._sender.aclose()
finally:
self._receiver.close()
return
await self._sender.aclose()
30 changes: 30 additions & 0 deletions src/frequenz/channels/_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
except SenderError as error:
print(f"Error sending message: {error}")
```

Most errors mean that the sender, or its channel, can't be used anymore. A
[`TransientSenderError`][frequenz.channels.TransientSenderError] means that only
this message wasn't sent, and sending again later can work.
"""

from __future__ import annotations
Expand Down Expand Up @@ -114,6 +118,32 @@ def __init__(self, sender: Sender[SenderMessageT_co]):
super().__init__("Sender is closed", sender)


class TransientSenderError(SenderError[SenderMessageT_co]):
"""An error indicating that a message wasn't sent, but sending can still work.

The sender and its channel can still be used, so sending again later can
succeed. Any other [`SenderError`][frequenz.channels.SenderError] means the
sender or its channel can't be used anymore, so catch this error first to tell
them apart:

Example:
```python
from frequenz.channels import Sender, SenderError, TransientSenderError


async def try_send(sender: Sender[int], message: int) -> bool:
try:
await sender.send(message)
except TransientSenderError:
return False # Not sent this time, but the sender still works.
except SenderError:
await sender.aclose() # The sender can't be used anymore.
raise
return True
```
"""


class SubscribableSender(Sender[SenderMessageT_contra], ABC):
"""A [`Sender`][frequenz.channels.Sender] that can be subscribed to."""

Expand Down
Loading