diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 80f627bb..e19c87d6 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -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`. @@ -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 diff --git a/docs/user-guide/utilities/pipes.md b/docs/user-guide/utilities/pipes.md new file mode 100644 index 00000000..2fedd24d --- /dev/null +++ b/docs/user-guide/utilities/pipes.md @@ -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 diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index 09075fa0..71b81d45 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -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. @@ -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, @@ -156,6 +160,7 @@ "OneshotChannel", "OneshotReceiver", "OneshotSender", + "Pipe", "Receiver", "ReceiverError", "ReceiverMessageT_co", diff --git a/src/frequenz/channels/_pipe.py b/src/frequenz/channels/_pipe.py new file mode 100644 index 00000000..057e7963 --- /dev/null +++ b/src/frequenz/channels/_pipe.py @@ -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() diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 331c0fbf..b8a1cdf2 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -11,43 +11,56 @@ from __future__ import annotations import asyncio -import logging import typing +from typing_extensions import deprecated + from .._generic import ChannelMessageT from .._receiver import Receiver -from .._sender import Sender, SenderError, SenderHasNoReceiversError - -_logger = logging.getLogger(__name__) +from .._sender import Sender +@deprecated( + "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 ends: " + "where this pipe leaves them open, the new pipe closes its sender when its " + "receiver stops and both ends by default on a SenderError other than a " + "TransientSenderError; on a TransientSenderError, it drops the message and " + "keeps forwarding." +) class Pipe(typing.Generic[ChannelMessageT]): """A pipe between two channels. + Deprecated: + Deprecated since v2.0.0, and will be removed in v3.0.0. Use + [`frequenz.channels.Pipe`][] instead, after checking how your code closes the + sender and the receiver: the new class closes them in cases where this one + leaves them open, and drops messages that fail with a + [`TransientSenderError`][frequenz.channels.TransientSenderError]. + The [`Pipe`][frequenz.channels.experimental.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 [`SenderError`][frequenz.channels.SenderError], for example - because the sender's channel has no receivers, the pipe 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. - - The pipe logs a failed send: a - [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError] as a - warning, or at debug level with `close_pipe_on_send_error=False`, and any other - error with its traceback. - - [`stop()`][frequenz.channels.experimental.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. - - Give the pipe a clone of the sender if you still need to send after the pipe stops - on its own. + [`frequenz.channels.Pipe`][] is a separate implementation that treats its endpoints + differently, so moving to it can change how your code shuts down: + + * When its receiver stops, this pipe stops and leaves its sender open. + [`frequenz.channels.Pipe`][] closes its sender too. + * When sending fails with any [`SenderError`][frequenz.channels.SenderError], the + exception ends the task of this pipe and both ends stay open. + [`frequenz.channels.Pipe`][] logs the error and closes its sender and its + receiver by default, unless it is a + [`TransientSenderError`][frequenz.channels.TransientSenderError], like a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]: + then it logs it, drops the message and keeps forwarding. + * [`frequenz.channels.Pipe`][] also takes `close_pipe_on_send_error=False`, which + drops the message that failed with any other + [`SenderError`][frequenz.channels.SenderError] and keeps forwarding the next + ones. This doesn't bring back the behavior of this class, which stops on the + first send error. + * [`stop()`][frequenz.channels.experimental.Pipe.stop] leaves both ends open in + both. Example: ```python @@ -83,25 +96,16 @@ async def main() -> None: """ def __init__( - self, - receiver: Receiver[ChannelMessageT], - sender: Sender[ChannelMessageT], - *, - close_pipe_on_send_error: bool = True, + self, receiver: Receiver[ChannelMessageT], sender: Sender[ChannelMessageT] ) -> 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` from sending 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]: @@ -133,36 +137,5 @@ async def stop(self) -> None: pass async def _run(self) -> None: - if self._close_pipe_on_send_error: - no_receivers_level, outcome = logging.WARNING, "stopped" - else: - no_receivers_level, outcome = logging.DEBUG, "dropped a message" async for value in self._receiver: - try: - await self._sender.send(value) - except SenderHasNoReceiversError as error: - _logger.log( - no_receivers_level, - "Pipe from [%s] to [%s] %s: %s", - self._receiver, - self._sender, - outcome, - error, - ) - except SenderError: - _logger.exception( - "Pipe from [%s] to [%s] %s: sending failed", - self._receiver, - self._sender, - outcome, - ) - else: - continue - if not self._close_pipe_on_send_error: - continue - try: - await self._sender.aclose() - finally: - self._receiver.close() - return - await self._sender.aclose() + await self._sender.send(value) diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index 494c1ff7..1a5f7a2f 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -1,21 +1,18 @@ # License: MIT # Copyright © 2024 Frequenz Energy-as-a-Service GmbH -"""Tests for the Pipe class.""" +"""Tests for the deprecated experimental Pipe class.""" import asyncio -import logging import typing -from contextlib import AsyncExitStack, aclosing, closing +from contextlib import AsyncExitStack, closing import pytest from frequenz.channels import ( - Broadcast, BroadcastChannel, Receiver, Sender, - SenderClosedError, SenderError, SenderHasNoReceiversError, ) @@ -23,8 +20,14 @@ T = typing.TypeVar("T") -# These tests use the deprecated Broadcast on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") +DEPRECATION_MESSAGE = "frequenz.channels.experimental.Pipe is deprecated" +"""The start of the deprecation message, which the pytest filter matches.""" + + +def make_pipe(receiver: Receiver[T], sender: Sender[T]) -> Pipe[T]: + """Create a deprecated pipe, checking that it warns.""" + with pytest.deprecated_call(match=DEPRECATION_MESSAGE): + return Pipe(receiver, sender) class Timeout: @@ -46,17 +49,33 @@ async def wait_stopped(pipe: Pipe[int]) -> None: await asyncio.wait_for(task, timeout=1.0) +async def test_pipe_deprecation_message() -> None: + """Ensure the warning says what to use instead and what changes.""" + sender, receiver = BroadcastChannel[int](name="channel") + with pytest.deprecated_call() as record: + Pipe(receiver, sender) + + message = str(record[0].message) + assert message.startswith( + "frequenz.channels.experimental.Pipe is deprecated and will be removed in " + "v3.0.0. Use frequenz.channels.Pipe instead, " + ) + assert "closes its sender when its receiver stops" in message + assert ( + "both ends by default on a SenderError other than a TransientSenderError" + in message + ) + assert "on a TransientSenderError, it drops the message and keeps forwarding" in ( + message + ) + + async def test_pipe() -> None: """Test pipe.""" - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") - - sender_chan1 = channel1.new_sender() - sender_chan2 = channel2.new_sender() - receiver_chan1 = channel1.new_receiver() - receiver_chan2 = channel2.new_receiver() + sender_chan1, receiver_chan1 = BroadcastChannel[int](name="channel1") + sender_chan2, receiver_chan2 = BroadcastChannel[int](name="channel2") - async with Pipe(channel2.new_receiver(), channel1.new_sender()): + async with make_pipe(sender_chan2.subscribe(), sender_chan1.clone()): await sender_chan2.send(42) assert await receive_timeout(receiver_chan1) == 42 assert await receive_timeout(receiver_chan2) == 42 @@ -80,87 +99,29 @@ async def test_pipe() -> None: async def test_pipe_with_async_exit_stack() -> None: """Test how pipe should work with async exit stack.""" - # Channels, receivers and Pipe are in AsyncExitStack + # Senders, receivers and Pipe are in AsyncExitStack # to close and stop them at the end. async with AsyncExitStack() as stack: - source_channel = await stack.enter_async_context( - aclosing(Broadcast[int](name="source channel")) - ) - source_receiver = stack.enter_context(closing(source_channel.new_receiver())) + source_sender, source_receiver = BroadcastChannel[int](name="source channel") + stack.push_async_callback(source_sender.aclose) + stack.enter_context(closing(source_receiver)) - forwarding_channel = await stack.enter_async_context( - aclosing(Broadcast[int](name="forwarding channel")) - ) - await stack.enter_async_context( - Pipe(source_receiver, forwarding_channel.new_sender()) - ) + forwarding_sender, receiver = BroadcastChannel[int](name="forwarding channel") + stack.push_async_callback(forwarding_sender.aclose) + stack.enter_context(closing(receiver)) - receiver = stack.enter_context(closing(forwarding_channel.new_receiver())) + await stack.enter_async_context(make_pipe(source_receiver, forwarding_sender)) - source_sender = source_channel.new_sender() await source_sender.send(10) assert await receiver.receive() == 10 -async def test_pipe_closes_both_ends_when_sending_fails( - caplog: pytest.LogCaptureFixture, -) -> None: - """Ensure a pipe closes its sender and receiver when it can't send.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - receiver.close() - - pipe = Pipe(source_receiver, sender) - await pipe.start() - with pytest.raises(SenderHasNoReceiversError): - await sender.send(0) - - with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): - await source_sender.send(1) - await wait_stopped(pipe) - - assert not source_sender.has_receivers - with pytest.raises(SenderClosedError): - await sender.send(2) - assert [(r.levelno, r.exc_info) for r in caplog.records] == [ - (logging.WARNING, None) - ] - assert "stopped" in caplog.records[0].getMessage() - assert "has no receivers" in caplog.records[0].getMessage() - - -async def test_pipe_logs_send_failure(caplog: pytest.LogCaptureFixture) -> None: - """Ensure a pipe logs a failed send with its traceback.""" +async def test_pipe_leaves_sender_open_when_receiver_stops() -> None: + """Ensure the deprecated pipe stops, but leaves its sender open.""" source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - receiver.close() - await sender.aclose() - pipe = Pipe(source_receiver, sender) - await pipe.start() - with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): - await source_sender.send(1) - await wait_stopped(pipe) - - assert [r.levelno for r in caplog.records] == [logging.ERROR] - assert "stopped" in caplog.records[0].getMessage() - exc_info = caplog.records[0].exc_info - assert exc_info is not None and isinstance(exc_info[1], SenderClosedError) - assert not source_sender.has_receivers - - -@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) -async def test_pipe_closes_sender_when_receiver_stops( - close_pipe_on_send_error: bool, -) -> None: - """Ensure a pipe closes its sender when its receiver stops.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - - pipe = Pipe( - source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error - ) + pipe = make_pipe(source_receiver, sender) await pipe.start() await source_sender.send(1) assert await receive_timeout(receiver) == 1 @@ -168,48 +129,12 @@ async def test_pipe_closes_sender_when_receiver_stops( await source_sender.aclose() await wait_stopped(pipe) - with pytest.raises(SenderClosedError): - await sender.send(2) - assert not receiver.has_senders - - -async def test_pipe_stop_leaves_both_ends_open() -> None: - """Ensure stopping a pipe leaves its sender and receiver open.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - - pipe = Pipe(source_receiver, sender) - await pipe.start() - await asyncio.sleep(0) - await pipe.stop() - - await sender.send(1) - assert await receive_timeout(receiver) == 1 - await source_sender.send(2) - assert await receive_timeout(source_receiver) == 2 - - -async def test_pipe_leaves_both_ends_open_on_receive_exception() -> None: - """Ensure an exception while receiving leaves a pipe's ends open.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - - def fail(_: int) -> int: - raise ValueError("Mapping failed") - - pipe = Pipe(source_receiver.map(fail), sender) - await pipe.start() - await source_sender.send(1) - with pytest.raises(ValueError, match="Mapping failed"): - await wait_stopped(pipe) - - assert source_sender.has_receivers await sender.send(2) assert await receive_timeout(receiver) == 2 -class ValueErrorSender(Sender[int]): - """A sender whose sends raise an error that isn't a `SenderError`.""" +class FailingSender(Sender[int]): + """A sender whose sends fail with a `SenderError`.""" def __init__(self) -> None: """Initialize this sender.""" @@ -217,128 +142,63 @@ def __init__(self) -> None: async def send(self, message: int, /) -> None: """Fail to send.""" - raise ValueError("Sending failed") + raise SenderError("Sending failed", self) async def aclose(self) -> None: """Remember that this sender was closed.""" self.closed = True -async def test_pipe_leaves_both_ends_open_on_send_exception() -> None: - """Ensure an exception from sending that isn't a `SenderError` leaves both open.""" +async def test_pipe_leaves_both_ends_open_when_sending_fails() -> None: + """Ensure the deprecated pipe lets a send error end its task and closes nothing.""" source_sender, source_receiver = BroadcastChannel[int](name="source") - sender = ValueErrorSender() + sender = FailingSender() - pipe = Pipe(source_receiver, sender) + pipe = make_pipe(source_receiver, sender) await pipe.start() await source_sender.send(1) - with pytest.raises(ValueError, match="Sending failed"): + with pytest.raises(SenderError, match="Sending failed"): await wait_stopped(pipe) - assert source_sender.has_receivers assert not sender.closed + # The receiver is still open: the source channel still accepts messages. + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 -async def test_pipe_keeps_sending_after_no_receivers( - caplog: pytest.LogCaptureFixture, -) -> None: - """Ensure a pipe that doesn't close on send errors outlives missing receivers.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - sender, receiver = BroadcastChannel[int](name="forwarding") - receiver.close() - - pipe = Pipe(source_receiver, sender, close_pipe_on_send_error=False) - await pipe.start() - with caplog.at_level(logging.DEBUG, logger="frequenz.channels.experimental"): - await source_sender.send(1) - await asyncio.sleep(0) - - new_receiver = sender.subscribe() - await source_sender.send(2) - assert await receive_timeout(new_receiver) == 2 - - assert source_sender.has_receivers - assert [r.levelno for r in caplog.records] == [logging.DEBUG] - assert "dropped a message" in caplog.records[0].getMessage() - await pipe.stop() - - -async def test_pipe_keeps_sending_after_send_failure( - caplog: pytest.LogCaptureFixture, -) -> None: - """Ensure a pipe that doesn't close on send errors logs each failed send.""" - source_sender, source_receiver = BroadcastChannel[int](name="source") - - pipe = Pipe(source_receiver, FailingSender(), close_pipe_on_send_error=False) - await pipe.start() - with caplog.at_level(logging.WARNING, logger="frequenz.channels.experimental"): - await source_sender.send(1) - await asyncio.sleep(0) - await source_sender.send(2) - await asyncio.sleep(0) - - assert source_sender.has_receivers - assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] - assert "dropped a message" in caplog.records[0].getMessage() - await pipe.stop() - - -class UncloseableReceiver(Receiver[int]): - """A receiver whose `close()` fails.""" - - def __init__(self, receiver: Receiver[int]) -> None: - """Wrap the given receiver.""" - self._receiver = receiver - - async def ready(self) -> bool: - """Wait until the wrapped receiver is ready.""" - return await self._receiver.ready() - - def consume(self) -> int: - """Return the wrapped receiver's message.""" - return self._receiver.consume() - - def close(self) -> None: - """Fail to close.""" - raise NotImplementedError("close() is not supported") - +async def test_pipe_stops_when_sending_without_receivers() -> None: + """Ensure a send without receivers ends the task of the deprecated pipe. -async def test_pipe_closes_sender_when_receiver_cannot_close() -> None: - """Ensure a failed send closes the sender even if the receiver can't close.""" + The new `Pipe` drops the message and keeps forwarding instead. + """ source_sender, source_receiver = BroadcastChannel[int](name="source") sender, receiver = BroadcastChannel[int](name="forwarding") receiver.close() - pipe = Pipe(UncloseableReceiver(source_receiver), sender) + pipe = make_pipe(source_receiver, sender) await pipe.start() await source_sender.send(1) - with pytest.raises(NotImplementedError): + with pytest.raises(SenderHasNoReceiversError): await wait_stopped(pipe) - with pytest.raises(SenderClosedError): - await sender.send(2) - - -class FailingSender(Sender[int]): - """A sender whose sends and `aclose()` fail.""" - - async def send(self, message: int, /) -> None: - """Fail to send.""" - raise SenderError("Sending failed", self) - - async def aclose(self) -> None: - """Fail to close.""" - raise RuntimeError("Closing failed") + # Both ends are still open, but the pipe doesn't forward anything anymore. + new_receiver = sender.subscribe() + await source_sender.send(2) + assert await receive_timeout(new_receiver) is Timeout + assert await receive_timeout(source_receiver) == 2 -async def test_pipe_closes_receiver_when_sender_cannot_close() -> None: - """Ensure a failed send closes the receiver even if the sender can't close.""" +async def test_pipe_stop_leaves_both_ends_open() -> None: + """Ensure stopping the deprecated pipe leaves its sender and receiver open.""" source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") - pipe = Pipe(source_receiver, FailingSender()) + pipe = make_pipe(source_receiver, sender) await pipe.start() - await source_sender.send(1) - with pytest.raises(RuntimeError, match="Closing failed"): - await wait_stopped(pipe) + await asyncio.sleep(0) + await pipe.stop() - assert not source_sender.has_receivers + await sender.send(1) + assert await receive_timeout(receiver) == 1 + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 diff --git a/tests/test_pipe.py b/tests/test_pipe.py new file mode 100644 index 00000000..c3b0623f --- /dev/null +++ b/tests/test_pipe.py @@ -0,0 +1,510 @@ +# License: MIT +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH + +"""Tests for the Pipe class.""" + +import asyncio +import logging +import typing +from contextlib import AsyncExitStack, closing + +import pytest +from frequenz.core.warnings import asserting_no_deprecations + +from frequenz.channels import ( + BroadcastChannel, + Pipe, + Receiver, + Sender, + SenderClosedError, + SenderError, + TransientSenderError, +) + +T = typing.TypeVar("T") + + +class Timeout: + """Sentinel for timeout.""" + + +async def receive_timeout(recv: Receiver[T], timeout: float = 0.1) -> T | type[Timeout]: + """Receive message from receiver with timeout.""" + try: + return await asyncio.wait_for(recv.receive(), timeout=timeout) + except asyncio.TimeoutError: + return Timeout + + +async def wait_stopped(pipe: Pipe[int]) -> None: + """Wait until the task of a started pipe ends.""" + task = pipe._task # pylint: disable=protected-access + assert task is not None + await asyncio.wait_for(task, timeout=1.0) + + +class FailingSender(Sender[int]): + """A sender whose sends and `aclose()` fail.""" + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise SenderError("Sending failed", self) + + async def aclose(self) -> None: + """Fail to close.""" + raise RuntimeError("Closing failed") + + +class ValueErrorSender(Sender[int]): + """A sender whose sends raise an error that isn't a `SenderError`.""" + + def __init__(self) -> None: + """Initialize this sender.""" + self.closed = False + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise ValueError("Sending failed") + + async def aclose(self) -> None: + """Remember that this sender was closed.""" + self.closed = True + + +class BusySender(Sender[int]): + """A sender that fails with a `TransientSenderError` for the first messages.""" + + def __init__(self, busy_messages: int) -> None: + """Initialize this sender. + + Args: + busy_messages: How many messages to reject. + """ + self.busy_messages = busy_messages + self.sent: list[int] = [] + self.closed = False + + async def send(self, message: int, /) -> None: + """Reject the first messages and keep the rest.""" + if self.busy_messages > 0: + self.busy_messages -= 1 + raise TransientSenderError("Busy", self) + self.sent.append(message) + + async def aclose(self) -> None: + """Remember that this sender was closed.""" + self.closed = True + + +class UncloseableReceiver(Receiver[int]): + """A receiver whose `close()` fails.""" + + def __init__(self, receiver: Receiver[int]) -> None: + """Wrap the given receiver.""" + self._receiver = receiver + + async def ready(self) -> bool: + """Wait until the wrapped receiver is ready.""" + return await self._receiver.ready() + + def consume(self) -> int: + """Return the wrapped receiver's message.""" + return self._receiver.consume() + + def close(self) -> None: + """Fail to close.""" + raise NotImplementedError("close() is not supported") + + +def test_pipe_does_not_warn() -> None: + """Ensure creating a pipe doesn't emit a deprecation warning.""" + _, source_receiver = BroadcastChannel[int](name="source") + sender, _ = BroadcastChannel[int](name="forwarding") + with asserting_no_deprecations(): + Pipe(source_receiver, sender) + + +async def test_pipe() -> None: + """Test pipe.""" + sender_chan1, receiver_chan1 = BroadcastChannel[int](name="channel1") + sender_chan2, receiver_chan2 = BroadcastChannel[int](name="channel2") + + async with Pipe(sender_chan2.subscribe(), sender_chan1.clone()): + await sender_chan2.send(42) + assert await receive_timeout(receiver_chan1) == 42 + assert await receive_timeout(receiver_chan2) == 42 + + await sender_chan2.send(-2) + assert await receive_timeout(receiver_chan1) == -2 + assert await receive_timeout(receiver_chan2) == -2 + + await sender_chan1.send(43) + assert await receive_timeout(receiver_chan1) == 43 + assert await receive_timeout(receiver_chan2) is Timeout + + await sender_chan2.send(5) + assert await receive_timeout(receiver_chan1) == 5 + assert await receive_timeout(receiver_chan2) == 5 + + await sender_chan2.send(5) + assert await receive_timeout(receiver_chan1) is Timeout + assert await receive_timeout(receiver_chan2) == 5 + + +async def test_pipe_with_async_exit_stack() -> None: + """Test how pipe should work with async exit stack.""" + # 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 + + +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_keeps_sending_after_no_receivers( + close_pipe_on_send_error: bool, caplog: pytest.LogCaptureFixture +) -> None: + """Ensure a pipe drops messages while its channel has no receivers. + + A send without receivers is a `TransientSenderError`, so the pipe never stops for + it, whatever `close_pipe_on_send_error` says. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + caplog: The fixture to capture log records. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + + pipe = Pipe( + source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error + ) + await pipe.start() + with caplog.at_level(logging.DEBUG, logger="frequenz.channels"): + await source_sender.send(1) + await asyncio.sleep(0) + + new_receiver = sender.subscribe() + await source_sender.send(2) + assert await receive_timeout(new_receiver) == 2 + + assert source_sender.has_receivers + assert [(r.levelno, r.exc_info) for r in caplog.records] == [(logging.DEBUG, None)] + message = caplog.records[0].getMessage() + assert "dropped a message" in message + assert "has no receivers" in message + await pipe.stop() + + +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_keeps_sending_after_transient_error( + close_pipe_on_send_error: bool, caplog: pytest.LogCaptureFixture +) -> None: + """Ensure a pipe drops the message that failed with a `TransientSenderError`. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + caplog: The fixture to capture log records. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender = BusySender(busy_messages=2) + + pipe = Pipe( + source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error + ) + await pipe.start() + with caplog.at_level(logging.DEBUG, logger="frequenz.channels"): + for message in (1, 2, 3, 4): + await source_sender.send(message) + await asyncio.sleep(0) + + assert sender.sent == [3, 4] + assert not sender.closed + assert source_sender.has_receivers + assert [(r.levelno, r.exc_info) for r in caplog.records] == [ + (logging.WARNING, None), + (logging.WARNING, None), + ] + assert "dropped a message" in caplog.records[0].getMessage() + assert "Busy" in caplog.records[0].getMessage() + await pipe.stop() + + +async def test_pipe_closes_both_ends_when_sending_fails( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe closes its sender and receiver when it can't send.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + await sender.aclose() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + with caplog.at_level(logging.WARNING, logger="frequenz.channels"): + await source_sender.send(1) + await wait_stopped(pipe) + + assert not source_sender.has_receivers + with pytest.raises(SenderClosedError): + await sender.send(2) + assert [r.levelno for r in caplog.records] == [logging.ERROR] + assert "stopped" in caplog.records[0].getMessage() + exc_info = caplog.records[0].exc_info + assert exc_info is not None and isinstance(exc_info[1], SenderClosedError) + + +@pytest.mark.parametrize("close_pipe_on_send_error", [True, False]) +async def test_pipe_closes_sender_when_receiver_stops( + close_pipe_on_send_error: bool, +) -> None: + """Ensure a pipe closes its sender when its receiver stops. + + Args: + close_pipe_on_send_error: The pipe's `close_pipe_on_send_error` argument. + """ + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = Pipe( + source_receiver, sender, close_pipe_on_send_error=close_pipe_on_send_error + ) + await pipe.start() + await source_sender.send(1) + assert await receive_timeout(receiver) == 1 + + await source_sender.aclose() + await wait_stopped(pipe) + + with pytest.raises(SenderClosedError): + await sender.send(2) + assert not receiver.has_senders + + +async def test_pipe_stop_leaves_both_ends_open() -> None: + """Ensure stopping a pipe leaves its sender and receiver open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + pipe = Pipe(source_receiver, sender) + await pipe.start() + await asyncio.sleep(0) + await pipe.stop() + + await sender.send(1) + assert await receive_timeout(receiver) == 1 + await source_sender.send(2) + assert await receive_timeout(source_receiver) == 2 + + +@pytest.mark.parametrize( + "send_fails", [False, True], ids=["receiver-stops", "send-fails"] +) +@pytest.mark.parametrize("cancel_exit", [False, True], ids=["wait", "cancel-wait"]) +async def test_pipe_context_exit_does_not_interrupt_automatic_close( + send_fails: bool, cancel_exit: bool +) -> None: + """Ensure an automatic close finishes, even if context exit is cancelled. + + Args: + send_fails: Whether a send error triggers closing instead of the receiver + stopping. + cancel_exit: Whether to cancel context exit while it waits for closing. + """ + closing = asyncio.Event() + finish_closing = asyncio.Event() + closed = asyncio.Event() + exiting = asyncio.Event() + + class SlowClosingSender(Sender[int]): + """A sender that fails to send and waits before closing.""" + + async def send(self, message: int, /) -> None: + """Fail to send.""" + raise SenderError("Sending failed", self) + + async def aclose(self) -> None: + """Wait for permission to finish closing.""" + closing.set() + await finish_closing.wait() + closed.set() + + source_sender, source_receiver = BroadcastChannel[int](name="source") + pipe = Pipe(source_receiver, SlowClosingSender()) + + async def run_pipe() -> None: + async with pipe: + if send_fails: + await source_sender.send(1) + else: + source_receiver.close() + await closing.wait() + exiting.set() + + running = asyncio.create_task(run_pipe()) + try: + async with asyncio.timeout(1.0): + await exiting.wait() + assert not running.done() + if cancel_exit: + running.cancel() + with pytest.raises(asyncio.CancelledError): + await running + assert not closed.is_set() + finish_closing.set() + if not cancel_exit: + await running + assert closed.is_set() + await wait_stopped(pipe) + finally: + finish_closing.set() + + assert closed.is_set() + assert not source_sender.has_receivers + + +async def test_pipe_leaves_both_ends_open_on_receive_exception( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a receive error is logged promptly and leaves both ends open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + + def fail(_: int) -> int: + raise ValueError("Mapping failed") + + pipe = Pipe(source_receiver.map(fail), sender) + await pipe.start() + await source_sender.send(1) + task = pipe._task # pylint: disable=protected-access + assert task is not None + # Wait without retrieving the task's exception. + done, _ = await asyncio.wait({task}, timeout=1.0) + assert task in done + await pipe.stop() + + assert [record.levelno for record in caplog.records] == [logging.ERROR] + exc_info = caplog.records[0].exc_info + assert exc_info is not None and isinstance(exc_info[1], ValueError) + assert str(exc_info[1]) == "Mapping failed" + assert exc_info[2] is not None + + assert source_sender.has_receivers + await sender.send(2) + assert await receive_timeout(receiver) == 2 + + +async def test_pipe_stop_propagates_caller_cancellation() -> None: + """Ensure cancelling a task waiting in stop() cancels that task.""" + waiting = asyncio.Event() + cleaning_up = asyncio.Event() + + class SlowReceiver(Receiver[int]): + """A receiver that suspends again after cancellation.""" + + async def ready(self) -> bool: + """Wait for a message, then wait again during cleanup.""" + waiting.set() + try: + return await asyncio.Future[bool]() + finally: + cleaning_up.set() + await asyncio.Future[None]() + + def consume(self) -> int: + """Fail because this receiver never has a message to consume.""" + raise AssertionError("Receiver is not ready") + + def close(self) -> None: + """Fail because stopping the pipe should leave the receiver open.""" + raise AssertionError("Pipe should leave the receiver open") + + sender, _ = BroadcastChannel[int](name="forwarding") + pipe = Pipe(SlowReceiver(), sender) + await pipe.start() + await asyncio.wait_for(waiting.wait(), timeout=1.0) + + stopping = asyncio.create_task(pipe.stop()) + await asyncio.wait_for(cleaning_up.wait(), timeout=1.0) + stopping.cancel() + done, _ = await asyncio.wait({stopping}, timeout=1.0) + assert stopping in done + with pytest.raises(asyncio.CancelledError): + await stopping + + +async def test_pipe_leaves_both_ends_open_on_send_exception() -> None: + """Ensure an exception from sending that isn't a `SenderError` leaves both open.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender = ValueErrorSender() + + pipe = Pipe(source_receiver, sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(ValueError, match="Sending failed"): + await wait_stopped(pipe) + + assert source_sender.has_receivers + assert not sender.closed + + +async def test_pipe_keeps_sending_after_send_failure( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure a pipe that doesn't close on send errors logs each failed send.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + pipe = Pipe(source_receiver, FailingSender(), close_pipe_on_send_error=False) + await pipe.start() + with caplog.at_level(logging.WARNING, logger="frequenz.channels"): + await source_sender.send(1) + await asyncio.sleep(0) + await source_sender.send(2) + await asyncio.sleep(0) + + assert source_sender.has_receivers + assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] + assert "dropped a message" in caplog.records[0].getMessage() + await pipe.stop() + + +async def test_pipe_closes_sender_when_receiver_cannot_close() -> None: + """Ensure a failed send closes the sender even if the receiver can't close.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + sender, receiver = BroadcastChannel[int](name="forwarding") + receiver.close() + await sender.aclose() + + pipe = Pipe(UncloseableReceiver(source_receiver), sender) + await pipe.start() + await source_sender.send(1) + with pytest.raises(NotImplementedError): + await wait_stopped(pipe) + + with pytest.raises(SenderClosedError): + await sender.send(2) + + +async def test_pipe_closes_receiver_when_sender_cannot_close() -> None: + """Ensure a failed send closes the receiver even if the sender can't close.""" + source_sender, source_receiver = BroadcastChannel[int](name="source") + + pipe = Pipe(source_receiver, FailingSender()) + await pipe.start() + await source_sender.send(1) + with pytest.raises(RuntimeError, match="Closing failed"): + await wait_stopped(pipe) + + assert not source_sender.has_receivers