diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 0f440753..d1eae7f2 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -50,7 +50,7 @@ body: - Documentation (part:docs) - Unit, integration and performance tests (part:tests) - Build script, CI, dependencies, etc. (part:tooling) - - Channels, `Broadcast`, `Anycast`, etc. (part:channels) + - Channels, `BroadcastChannel`, etc. (part:channels) - Core types (`Sender`, `Receiver`, exceptions, etc.) (part:core) - Experimental features (the `experimental` package) (part:experimental) - Utilities (`Event`, `FileWatcher`, `Timer`, etc.) (part:utilities) diff --git a/.github/labeler.yml b/.github/labeler.yml index b50ec0e3..313d999b 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -39,7 +39,6 @@ "part:channels": - changed-files: - any-glob-to-any-file: - - "src/frequenz/channels/_anycast.py" - "src/frequenz/channels/_broadcast.py" "part:core": diff --git a/README.md b/README.md index 1877d45e..a14fac07 100644 --- a/README.md +++ b/README.md @@ -67,13 +67,11 @@ python3 -m pip install frequenz-channels ```python import asyncio -from frequenz.channels import Anycast +from frequenz.channels import BroadcastChannel async def main() -> None: - hello_channel = Anycast[str](name="hello-world-channel") - sender = hello_channel.new_sender() - receiver = hello_channel.new_receiver() + sender, receiver = BroadcastChannel[str](name="hello-world-channel") await sender.send("Hello World!") message = await receiver.receive() @@ -100,8 +98,7 @@ from enum import Enum, auto from typing import assert_never from frequenz.channels import ( - Anycast, - Broadcast, + BroadcastChannel, Receiver, Sender, merge, @@ -151,6 +148,7 @@ async def send( await control_reply.send(Reply(ReplyCommand.PONG, str(sender))) case _ as unknown: assert_never(unknown) + await sender.aclose() print(f"{sender}: Finished") @@ -159,13 +157,16 @@ async def receive( control_command: Receiver[Command], control_reply: Sender[Reply], ) -> None: - """Receive data from multiple channels, until no more data is received for 2 seconds.""" + """Receive data from multiple channels, until they're closed or idle for 2 seconds.""" print("receive: Starting") timer = MonotonicTimer(timedelta(seconds=2.0), SkipMissedAndDrift()) print(f"{timer=}") merged = merge(*receivers) async for selected in select(merged, timer, control_command): if selected_from(selected, merged): + if selected.was_stopped: + print("receive: All data channels were closed") + break message = selected.message print(f"receive: Received {message=}") timer.reset() @@ -191,51 +192,41 @@ async def receive( async def main() -> None: - data_channel_1 = Anycast[str](name="data-channel-1") - data_channel_2 = Anycast[str](name="data-channel-2") - command_channel = Broadcast[Command](name="control-channel") # (1)! - reply_channel = Anycast[Reply](name="reply-channel") + data_sender_1, data_receiver_1 = BroadcastChannel[str](name="data-channel-1") + data_sender_2, data_receiver_2 = BroadcastChannel[str](name="data-channel-2") + command_sender, command_receiver = BroadcastChannel[Command]( + name="control-channel" + ) + reply_sender, reply_receiver = BroadcastChannel[Reply](name="reply-channel") async with asyncio.TaskGroup() as tasks: tasks.create_task( - send( - data_channel_1.new_sender(), - command_channel.new_receiver(), - reply_channel.new_sender(), - ), + send(data_sender_1, command_receiver, reply_sender.clone()), name="send-channel-1", ) tasks.create_task( - send( - data_channel_2.new_sender(), - command_channel.new_receiver(), - reply_channel.new_sender(), - ), + send(data_sender_2, command_sender.subscribe(), reply_sender.clone()), name="send-channel-2", ) tasks.create_task( receive( - [data_channel_1.new_receiver(), data_channel_2.new_receiver()], - command_channel.new_receiver(), - reply_channel.new_sender(), + [data_receiver_1, data_receiver_2], + command_sender.subscribe(), + reply_sender, ), name="receive", ) - control_sender = command_channel.new_sender() - reply_receiver = reply_channel.new_receiver() - # Send a ping command to all tasks and wait for the replies - await control_sender.send(Command.PING) + await command_sender.send(Command.PING) print(f"main: {await reply_receiver.receive()}") print(f"main: {await reply_receiver.receive()}") print(f"main: {await reply_receiver.receive()}") await asyncio.sleep(5.0) - # Stop senders, after 2 seconds not receiving any data, - # the receiver will stop too - await control_sender.send(Command.STOP_SENDER) + # Stop the senders. This closes the data channels, so the receiver stops too. + await command_sender.send(Command.STOP_SENDER) asyncio.run(main()) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index a3a0b4d3..80f627bb 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,38 +2,70 @@ ## Summary -This will probably be the last minor release of v1. It deprecates everything that will be removed in v2.0.0. + ## Upgrading -- `frequenz-core >= 1.6.0, < 2` is now a runtime dependency. It provides the utilities this project uses to deprecate symbols following the Frequenz deprecations guide. + -- The minimum `typing-extensions` version is now 4.16.0. `frequenz-core` requires 4.13.0, and the new `buffer_size` argument needs the `sentinel` type added in 4.16.0. +- `BroadcastChannel()` and `BroadcastSender.subscribe()` now take everything but the name by keyword: `resend_latest`, `buffer_size` and `warn_on_overflow`. A call that passed any of them by position fails with a `TypeError`. Pass them by keyword, as v1.13.0 recommends. -- `frequenz.channels.Anycast`, deprecated since v1.12.0, will be removed in a future version, not necessarily the next major one. Its deprecation warning now recommends copying its code into your project if you need it, or [opening an issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if you think it should stay in the library. +- The deprecated `limit` argument of `BroadcastChannel()` and `BroadcastSender.subscribe()` is removed. Use `buffer_size` instead, which exists since v1.13.0, so you can migrate before upgrading. `Broadcast.new_receiver()` still takes `limit`. -- `watchfiles` versions up to 1.3 are now allowed. +- The deprecated `frequenz.channels.timer.Timer` is removed. Use `MonotonicTimer` instead, which exists since v1.13.0, so you can migrate before upgrading. The name `Timer` will be used for a wall clock timer in a later version. -- `frequenz.channels.experimental.GroupingLatestValueCache` and its type variables `DefaultT`, `HashableT` and `ValueT_co`, and `frequenz.channels.experimental.RelaySender` are deprecated and will be removed in v2.0.0. There is no replacement in this library: copy their code into your project if you need them, or [open an issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if you think they should stay. +- `Anycast` is removed. There is no replacement: copy its code into your project if you still need it. -- `frequenz.channels.experimental.NopReceiver` and `frequenz.channels.experimental.WithPrevious` are deprecated. Import them from `frequenz.channels` instead; they are the same objects, so only the import changes. The old names will be removed in v2.0.0. +- `frequenz.channels.experimental.GroupingLatestValueCache` is removed, together with its type variables `DefaultT`, `HashableT` and `ValueT_co`. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. -- The deprecation warning of `frequenz.channels.experimental.OptionalReceiver` now points at `frequenz.channels.NopReceiver`. Use the receiver itself, or a `NopReceiver` when there is none. +- `frequenz.channels.experimental.RelaySender` is removed. Copy its code into your project if you still need it, or open an issue if you think it should stay in the library. -- `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. The change is mechanical: replace `Timer` with `MonotonicTimer` in imports and uses. +- `frequenz.channels.experimental.OptionalReceiver` is removed. Use the receiver itself, or `frequenz.channels.NopReceiver` when there is none. `NopReceiver` exists since v1.13.0, so you can migrate before upgrading. -- 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. `buffer_size` is keyword-only. A call that passes both `limit` and `buffer_size` raises a `TypeError`. Passing `warn_on_overflow` by position is deprecated too, because the new form only accepts it by keyword: pass it by keyword. v2.0.0 will also make `resend_latest` keyword-only, so pass it by keyword too. `Broadcast` and `Anycast` are not changed. +- `WithPrevious` and `NopReceiver` are no longer available from `frequenz.channels.experimental`. Import them from `frequenz.channels`, where they are available since v1.13.0, so you can migrate before upgrading. + +- The deprecated `async close()` method of `Broadcast` is removed. Use `aclose()` instead, which exists since v1.8.0, so you can migrate before upgrading. It also works with `contextlib.aclosing()`. + +- The `repr()` of a `BroadcastReceiver` shows its `buffer_size` instead of `limit`. + +- A `BroadcastChannel`, or a `Broadcast` created with `auto_close=True`, no longer closes when a message is sent while it has no receivers. `send()` now drops the message and raises a `SenderHasNoReceiversError`, a `SenderError` without a cause. The channel stays open: `subscribe()` keeps working, and sending works again once a new receiver is attached. + +- 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. + +- 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. + +- `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`. + +- `BroadcastSender.subscribe()` now uses the `buffer_size` and `warn_on_overflow` values the `BroadcastChannel` was created with as defaults, instead of `50` and `True`. Pass `buffer_size=50, warn_on_overflow=True` to keep the old values. + +- Call `BroadcastReceiver.close()` from the thread that runs the event loop of the channel's receivers. From another thread, tasks waiting on any receiver of the channel might not wake up. If asyncio debug mode is on and a task is waiting, `close()` also raises a `RuntimeError`, and the waiting tasks stay stuck. Use `loop.call_soon_threadsafe(receiver.close)` instead. + +- `Receiver.close()` is now an abstract method, so a custom `Receiver` subclass that doesn't implement it can't be instantiated anymore. Before, calling it raised a `NotImplementedError`. All the receivers in this library implement it already. Add a `close()` method to your own receivers; the same implementation works on v1, so your code can support both major versions. ## New Features -- `NopReceiver` and `WithPrevious` are now stable, and available from `frequenz.channels`. + + +- `TransientSenderError` is a new `SenderError` for errors after which the sender and its channel can still be used: only the message that failed wasn't sent. Catch it before `SenderError` to tell it apart from the errors that make a sender unusable. + +- `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. + +- `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 -- `BroadcastChannel()` no longer emits the deprecation warning of `Broadcast`, which it uses internally. You were getting a warning about a class you never used. + -- `OneshotReceiver.close()` no longer raises `NotImplementedError`. It now works like in the other receivers: a message sent before closing can still be received, and after that receiving raises `ReceiverStoppedError`. The sender can still send, but its message is discarded. +- Closing a broadcast receiver now wakes up tasks waiting for messages on it, instead of leaving them blocked until the next message arrived or the channel was closed. -- Creating a broadcast receiver with a `buffer_size` (or `limit`) of 0 now raises a `ValueError`, from `BroadcastChannel()` and `BroadcastSender.subscribe()`. Before, the first message sent to it raised an `IndexError`, after other receivers might have got the message already. +- Closing a broadcast receiver now drops the messages left in its buffer, so it is no longer reported as ready. So `select()` no longer reports it as stopped over and over, and no longer fails with a `SelectError` for a `filter()` on it. -- Docstrings now use absolute cross-references to public paths instead of relative ones. Relative cross-references are expanded from the module where an object is defined since mkdocstrings-python 2.0.9, which broke some links, and projects rendering docstrings inherited from this library needed `relative_crossrefs: true` for them to work at all. See [frequenz-repo-config-python#655](https://github.com/frequenz-floss/frequenz-repo-config-python/issues/655) for details. +- Sending to or closing a broadcast channel no longer raises `RuntimeError: Event loop is closed` when a receiver was left waiting on an event loop that has since been closed. diff --git a/benchmarks/benchmark_anycast.py b/benchmarks/benchmark_anycast.py deleted file mode 100644 index 68e4ae3b..00000000 --- a/benchmarks/benchmark_anycast.py +++ /dev/null @@ -1,127 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""Benchmark for Anycast channels.""" - -import asyncio -import csv -import timeit -from collections.abc import Coroutine -from typing import Any - -from frequenz.channels import Anycast, Receiver, Sender - - -async def send_msg(num_messages: int, chan: Sender[int]) -> None: - """Send messages to the channel continuously. - - Args: - num_messages: Number of messages to send. - chan: Channel sender to send the messages to. - """ - # send one message for each receiver - for ctr in range(num_messages): - await chan.send(ctr + 1) - - -async def benchmark_anycast( - num_channels: int, - num_messages: int, - num_receivers: int, - buffer_size: int, -) -> int: - """Ensure sent messages are received by one receiver. - - Args: - num_channels: Number of channels to create. - num_messages: Number of messages to send per channel. - num_receivers: Number of broadcast receivers per channel. - buffer_size: Buffer size of each channel. - - Returns: - Total number of messages received by all channels. - """ - channels: list[Anycast[int]] = [ - Anycast(name="test", limit=buffer_size) for _ in range(num_channels) - ] - senders = [ - asyncio.create_task(send_msg(num_messages, bcast.new_sender())) - for bcast in channels - ] - - # Even though we want just a single int, use a list, so that it can be - # updated from other methods. - recv_trackers = [0] - - async def update_tracker_on_receive(chan: Receiver[int]) -> None: - async for _ in chan: - recv_trackers[0] += 1 - - receivers = [] - for acast in channels: - for _ in range(num_receivers): - receivers.append(update_tracker_on_receive(acast.new_receiver())) - - receivers_runs = asyncio.gather(*receivers) - - await asyncio.gather(*senders) - for bcast in channels: - await bcast.aclose() - await receivers_runs - return recv_trackers[0] - - -def time_async_task(task: Coroutine[Any, Any, int]) -> tuple[float, Any]: - """Run a task and return the time taken and the result. - - Args: - task: Task to run. - - Returns: - Run time in fractional seconds, task return value. - """ - start = timeit.default_timer() - ret = asyncio.run(task) - return timeit.default_timer() - start, ret - - -def run_one( - num_channels: int, - num_messages: int, - num_receivers: int, - buffer_size: int, -) -> dict[str, Any]: - """Run a single benchmark.""" - runtime, total_msgs = time_async_task( - benchmark_anycast(num_channels, num_messages, num_receivers, buffer_size) - ) - ret = { - "channels": num_channels, - "messages_per_channel": num_messages, - "receivers": num_receivers, - "buffer_size": buffer_size, - "total_messages": total_msgs, - "runtime": f"{runtime:.3f}", - } - - return ret - - -def run() -> None: - """Run all benchmarks.""" - with open("/dev/stdout", "w", encoding="utf-8") as csvfile: - fields = run_one(1, 0, 1, 1) - out = csv.DictWriter(csvfile, fields.keys()) - out.writeheader() - out.writerow(run_one(1, 1000000, 1, 100)) - out.writerow(run_one(1, 1000000, 1, 1000)) - out.writerow(run_one(1, 1000000, 10, 100)) - out.writerow(run_one(1, 1000000, 10, 1000)) - out.writerow(run_one(1000, 1000, 1, 100)) - out.writerow(run_one(1000, 1000, 1, 1000)) - out.writerow(run_one(1000, 1000, 10, 100)) - out.writerow(run_one(1000, 1000, 10, 1000)) - - -if __name__ == "__main__": - run() diff --git a/docs/user-guide/channels/index.md b/docs/user-guide/channels/index.md index c6f2df64..55bd172c 100644 --- a/docs/user-guide/channels/index.md +++ b/docs/user-guide/channels/index.md @@ -35,7 +35,7 @@ various factors: Because these questions can have many answers, there are different types of channels. Frequenz Channels offers a few of them: -* [Anycast](anycast.md) * [Broadcast](broadcast.md) +* [Oneshot](oneshot.md) More might be added in the future, and you can also create your own. diff --git a/docs/user-guide/channels/anycast.md b/docs/user-guide/channels/oneshot.md similarity index 76% rename from docs/user-guide/channels/anycast.md rename to docs/user-guide/channels/oneshot.md index eca01889..9405ca72 100644 --- a/docs/user-guide/channels/anycast.md +++ b/docs/user-guide/channels/oneshot.md @@ -1,6 +1,6 @@ -# Anycast +# Oneshot -::: frequenz.channels._anycast.Anycast +::: frequenz.channels._oneshot.OneshotChannel options: inherited_members: [] members: [] diff --git a/docs/user-guide/receiving/synchronization/index.md b/docs/user-guide/receiving/synchronization/index.md index 60d70d86..050847fb 100644 --- a/docs/user-guide/receiving/synchronization/index.md +++ b/docs/user-guide/receiving/synchronization/index.md @@ -6,8 +6,8 @@ as soon as it is available in one single task. A naive approach like this will not work: ```python show_lines="4:" -receiver1: Receiver[int] = channel1.new_receiver() -receiver2: Receiver[int] = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[int](name="channel2") message = await receiver1.receive() print(f"Received from channel1: {message}") @@ -16,9 +16,9 @@ message = await receiver2.receive() print(f"Received from channel2: {message}") ``` -The problem is that if the first message is not available in `channel1` but in -`channel2`, the program will be blocked until a message is available in -`channel1`, but you probably want to receive the first message from `channel2` +The problem is that if the first message is not available in `receiver1` but in +`receiver2`, the program will be blocked until a message is available in +`receiver1`, but you probably want to receive the first message from `receiver2` as soon as it is available. Frequenz Channels provides two tools to solve this issue: diff --git a/pyproject.toml b/pyproject.toml index b44eac0a..c1a1c365 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [build-system] requires = [ - "setuptools == 84.1.0", + "setuptools == 84.2.1", "setuptools_scm[toml] == 10.3.4", "frequenz-repo-config[lib] == 0.19.0", ] @@ -38,7 +38,7 @@ email = "floss@frequenz.com" [project.optional-dependencies] dev-flake8 = [ - "flake8 == 7.4.1", + "flake8 == 7.5.0", "flake8-datetimez == 26.8.1", "flake8-docstrings == 1.7.0", "flake8-pyproject == 1.2.4", # For reading the flake8 config from pyproject.toml @@ -57,31 +57,31 @@ dev-mkdocs = [ "mkdocs-include-markdown-plugin == 7.3.0", "mkdocs-literate-nav == 0.6.3", "mkdocs-macros-plugin == 1.5.0", - "mkdocs-material == 9.7.7", + "mkdocs-material == 9.8.1", "mkdocstrings[python] == 1.0.8", "mkdocstrings-python == 2.0.10", - "pymdownx-superfence-filter-lines == 0.1.0", - "griffe==2.3.0", + "pymdownx-superfence-filter-lines == 1.0.0", + "griffe==2.4.1", ] dev-mypy = [ # For checking the noxfile, docs/ script, and tests "frequenz-channels[dev-mkdocs,dev-noxfile,dev-pytest]", "mypy == 2.4.1", - "types-Markdown == 3.10.2.20260712", + "types-Markdown == 3.11.3.20261108", ] -dev-noxfile = ["nox == 2026.8.17", "frequenz-repo-config[lib] == 0.19.0"] +dev-noxfile = ["nox == 2026.10.20", "frequenz-repo-config[lib] == 0.19.0"] dev-pylint = [ # For checking the noxfile, docs/ script, and tests "frequenz-channels[dev-mkdocs,dev-noxfile,dev-pytest]", - "pylint == 4.0.9", + "pylint == 4.1.4", ] dev-pytest = [ "async-solipsism == 0.10", "frequenz-repo-config[extra-lint-examples] == 0.19.0", - "hypothesis == 6.168.3", - "pytest == 9.1.1", + "hypothesis == 6.170.15", + "pytest == 9.2.0", "pytest-asyncio == 1.4.1", - "pytest-mock == 3.16.0", + "pytest-mock == 3.17.0", ] dev = [ "frequenz-channels[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]", diff --git a/src/frequenz/channels/__init__.py b/src/frequenz/channels/__init__.py index c263124b..09075fa0 100644 --- a/src/frequenz/channels/__init__.py +++ b/src/frequenz/channels/__init__.py @@ -17,15 +17,25 @@ * [`Sender`][frequenz.channels.Sender]: An object that can send messages to a channel. +* [`CloneableSender`][frequenz.channels.CloneableSender], + [`SubscribableSender`][frequenz.channels.SubscribableSender] and + [`CloneableSubscribableSender`][frequenz.channels.CloneableSubscribableSender]: + Senders that can create more senders, or receivers, attached to the same channel. + Channels: -* [`Anycast`][frequenz.channels.Anycast] (deprecated): A channel that supports - multiple senders and multiple receivers. A message sent through a sender will - be received by exactly one receiver. +* [`BroadcastChannel`][frequenz.channels.BroadcastChannel]: A channel to broadcast + messages from multiple senders to multiple receivers. Each message sent through any + of the senders is received by all of the receivers. The channel closes itself when + all its senders are closed. A `send()` while it has no receivers raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. + +* [`OneshotChannel`][frequenz.channels.OneshotChannel]: A channel that can send a + single message from one sender to one receiver. -* [`Broadcast`][frequenz.channels.Broadcast]: A channel to broadcast messages - from multiple senders to multiple receivers. Each message sent through any of - the senders is received by all of the receivers. +* [`Broadcast`][frequenz.channels.Broadcast] (deprecated): The predecessor of + [`BroadcastChannel`][frequenz.channels.BroadcastChannel]. Unless it is created with + `auto_close=True`, it must be closed with `aclose()`. Utilities to work with channels: @@ -60,6 +70,13 @@ * [`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. + +* [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]: Error + raised when sending a message to a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] that has no receivers. + * [`ReceiverError`][frequenz.channels.ReceiverError]: Base class for all errors related to receivers. @@ -85,7 +102,6 @@ generates a message after a given amount of time. """ -from ._anycast import Anycast from ._broadcast import Broadcast, BroadcastChannel, BroadcastReceiver, BroadcastSender from ._exceptions import ChannelClosedError, ChannelError, Error from ._generic import ( @@ -114,12 +130,13 @@ Sender, SenderClosedError, SenderError, + SenderHasNoReceiversError, SubscribableSender, + TransientSenderError, ) from ._with_previous import WithPrevious __all__ = [ - "Anycast", "Broadcast", "BroadcastChannel", "BroadcastReceiver", @@ -134,6 +151,7 @@ "LatestValueCache", "MappedMessageT_co", "Merger", + "SenderHasNoReceiversError", "NopReceiver", "OneshotChannel", "OneshotReceiver", @@ -150,6 +168,7 @@ "SenderMessageT_co", "SenderMessageT_contra", "SubscribableSender", + "TransientSenderError", "UnhandledSelectedError", "WithPrevious", "merge", diff --git a/src/frequenz/channels/_anycast.py b/src/frequenz/channels/_anycast.py deleted file mode 100644 index e2ec0dca..00000000 --- a/src/frequenz/channels/_anycast.py +++ /dev/null @@ -1,513 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""A channel for sending data across async tasks.""" - -from __future__ import annotations - -import logging -from asyncio import Condition -from collections import deque -from typing import Generic, TypeVar - -from typing_extensions import deprecated, override - -from ._exceptions import ChannelClosedError -from ._generic import ChannelMessageT -from ._receiver import Receiver, ReceiverStoppedError -from ._sender import Sender, SenderClosedError, SenderError - -_logger = logging.getLogger(__name__) - - -@deprecated( - "frequenz.channels.Anycast is deprecated and will be removed in a future " - "version. Copy its code into your project if you need it, or open an issue at " - "https://github.com/frequenz-floss/frequenz-channels-python/issues if you think " - "it should stay in frequenz-channels." -) -class Anycast(Generic[ChannelMessageT]): - """A channel that delivers each message to exactly one receiver. - - Deprecated: - Deprecated since v1.12.0, and will be removed in a future version. Copy its - code into your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - # Description - - !!! Tip inline end - - [`Anycast`][frequenz.channels.Anycast] channels behave like the - [Golang](https://golang.org/) [channels](https://go.dev/ref/spec#Channel_types). - - [`Anycast`][frequenz.channels.Anycast] channels support multiple - [senders][frequenz.channels.Sender] and multiple - [receivers][frequenz.channels.Receiver]. Each message sent through any of the - senders will be received by exactly one receiver (but **any** receiver). - -
- ```bob - .---------. msg1 msg1 .-----------. - | Sender +------. .------>| Receiver | - '---------' | .----------. | '-----------' - +----->| Channel +-----+ - .---------. | '----------' | .-----------. - | Sender +------' '------>| Receiver | - '---------' msg2 msg2 '-----------' - ``` -
- - !!! Note inline end "Characteristics" - - * **Buffered:** Yes, with a global channel buffer - * **Buffer full policy:** Block senders - * **Multiple receivers:** Yes - * **Multiple senders:** Yes - * **Thread-safe:** No - - This channel is buffered, and if the senders are faster than the receivers, then the - channel's buffer will fill up. In that case, the senders will block at the - [`send()`][frequenz.channels.Sender.send] method until the receivers consume the - messages in the channel's buffer. The channel's buffer size can be configured at - creation time via the `limit` argument. - - The first receiver that is awaited will get the next message. When multiple - receivers are waiting, the [asyncio][] loop scheduler picks a receiver for each next - message. - - This means that, in practice, there might be only one receiver receiving all the - messages, depending on how tasks are scheduled. - - If you need to ensure some delivery policy (like round-robin or uniformly random), - then you will have to implement it yourself. - - To create a new [senders][frequenz.channels.Sender] and - [receivers][frequenz.channels.Receiver] you can use the - [`.new_sender()`][frequenz.channels.Anycast.new_sender] and - [`.new_receiver()`][frequenz.channels.Anycast.new_receiver] methods - respectively. - - When the channel is not needed anymore, it should be closed with the - [`.aclose()`][frequenz.channels.Anycast.aclose] method. This will prevent further - attempts to [`send()`][frequenz.channels.Sender.send] data. Receivers will still be - able to drain the pending messages on the channel, but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] exception. - - This channel is useful, for example, to distribute work across multiple workers. - - In cases where each message needs to be received by every receiver, a - [broadcast][frequenz.channels.Broadcast] channel may be used. - - # Examples - - Example: Send a few numbers to a receiver - This is a very simple example that sends a few numbers from a single sender to - a single receiver. - - ```python - import asyncio - - from frequenz.channels import Anycast, Sender - - - async def send(sender: Sender[int]) -> None: - for message in range(3): - print(f"sending {message}") - await sender.send(message) - - - async def main() -> None: - channel = Anycast[int](name="numbers") - - sender = channel.new_sender() - receiver = channel.new_receiver() - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - - - asyncio.run(main()) - ``` - - The output should look something like (although the sending and received might - appear more interleaved): - - ``` - sending 0 - sending 1 - sending 2 - received 0 - received 1 - received 2 - ``` - - Example: Send a few number from multiple senders to multiple receivers - This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. - - ```python - import asyncio - - from frequenz.channels import Anycast, Receiver, ReceiverStoppedError, Sender - - - async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: - for message in range(start, stop): - print(f"{name} sending {message}") - await sender.send(message) - - - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass - - - async def main() -> None: - acast = Anycast[int](name="numbers", limit=2) - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send("sender_1", acast.new_sender(), 10, 13)) - task_group.create_task(send("sender_2", acast.new_sender(), 20, 22)) - task_group.create_task(recv("receiver_1", acast.new_receiver())) - task_group.create_task(recv("receiver_2", acast.new_receiver())) - - - asyncio.run(main()) - ``` - - The output should look something like this(although the sending and received - might appear interleaved in a different way): - - ``` - sender_1 sending 10 - sender_1 sending 11 - sender_1 sending 12 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - sender_2 sending 20 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - receiver_1 received 10 - receiver_1 received 11 - sender_2 sending 21 - Anycast channel [Anycast:numbers:_Sender] is full, blocking sender until a receiver - consumes a message - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 - ``` - """ - - def __init__(self, *, name: str, limit: int = 10) -> None: - """Initialize this channel. - - Args: - name: The name of the channel. This is for logging purposes, and it will be - shown in the string representation of the channel. - limit: The size of the internal buffer in number of messages. If the buffer - is full, then the senders will block until the receivers consume the - messages in the buffer. - """ - self._name: str = name - """The name of the channel. - - This is for logging purposes, and it will be shown in the string representation - of the channel. - """ - - self._deque: deque[ChannelMessageT] = deque(maxlen=limit) - """The channel's buffer.""" - - self._send_cv: Condition = Condition() - """The condition to wait for free space in the channel's buffer. - - If the channel's buffer is full, then the sender waits for messages to - get consumed using this condition until there's some free space - available in the channel's buffer. - """ - - self._recv_cv: Condition = Condition() - """The condition to wait for messages in the channel's buffer. - - If the channel's buffer is empty, then the receiver waits for messages - using this condition until there's a message available in the channel's - buffer. - """ - - self._closed: bool = False - """Whether the channel is closed.""" - - @property - def name(self) -> str: - """The name of this channel. - - This is for debugging purposes, it will be shown in the string representation - of this channel. - """ - return self._name - - @property - def is_closed(self) -> bool: - """Whether this channel is closed. - - Any further attempts to use this channel after it is closed will result in an - exception. - """ - return self._closed - - @property - def limit(self) -> int: - """The maximum number of messages that can be stored in the channel's buffer. - - If the length of channel's buffer reaches the limit, then the sender - blocks at the [`send()`][frequenz.channels.Sender.send] method until - a message is consumed. - """ - maxlen = self._deque.maxlen - assert maxlen is not None - return maxlen - - async def aclose(self) -> None: - """Close the channel. - - Any further attempts to [`send()`][frequenz.channels.Sender.send] data - will raise a [`SenderError`][frequenz.channels.SenderError]. - - Receivers will still be able to drain the pending messages on the channel, - but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will return `None` - immediately. - """ - self._closed = True - async with self._send_cv: - self._send_cv.notify_all() - async with self._recv_cv: - self._recv_cv.notify_all() - - @deprecated("The close() method is deprecated, use aclose() instead") - async def close(self) -> None: - """Close the channel. - - Deprecated alias for [`.aclose()`][frequenz.channels.Anycast.aclose]. - """ - return await self.aclose() - - def new_sender(self) -> Sender[ChannelMessageT]: - """Return a new sender attached to this channel.""" - return _Sender(self) - - def new_receiver(self) -> Receiver[ChannelMessageT]: - """Return a new receiver attached to this channel.""" - return _Receiver(self) - - def __str__(self) -> str: - """Return a string representation of this channel.""" - return f"{type(self).__name__}:{self._name}" - - def __repr__(self) -> str: - """Return a string representation of this channel.""" - return ( - f"{type(self).__name__}(name={self._name!r}, limit={self.limit!r}):<" - f"current={len(self._deque)!r}, closed={self._closed!r}>" - ) - - -_T = TypeVar("_T") - - -class _Sender(Sender[_T]): - """A sender to send messages to an Anycast channel. - - Should not be created directly, but through the - [`Anycast.new_sender()`][frequenz.channels.Anycast.new_sender] - method. - """ - - def __init__(self, channel: Anycast[_T], /) -> None: - """Initialize this sender. - - Args: - channel: A reference to the channel that this sender belongs to. - """ - self._channel: Anycast[_T] = channel - """The channel that this sender belongs to.""" - - self._closed: bool = False - """Whether the sender is closed.""" - - @override - async def send(self, message: _T, /) -> None: - """Send a message across the channel. - - To send, this method inserts the message into the Anycast channel's - buffer. If the channel's buffer is full, waits for messages to get - consumed, until there's some free space available in the buffer. Each - message will be received by exactly one receiver. - - Args: - message: The message to be sent. - - Raises: - SenderError: If the underlying channel was closed. - A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is - set as the cause. - SenderClosedError: If this sender was closed. - """ - if self._closed: - raise SenderClosedError(self) - - # pylint: disable=protected-access - if self._channel._closed: - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) - if len(self._channel._deque) == self._channel._deque.maxlen: - _logger.warning( - "Anycast channel [%s] is full, blocking sender until a receiver " - "consumes a message", - self, - ) - while len(self._channel._deque) == self._channel._deque.maxlen: - async with self._channel._send_cv: - await self._channel._send_cv.wait() - _logger.info( - "Anycast channel [%s] has space again, resuming the blocked sender", - self, - ) - self._channel._deque.append(message) - async with self._channel._recv_cv: - self._channel._recv_cv.notify(1) - # pylint: enable=protected-access - - @override - async def aclose(self) -> None: - """Close this sender. - - After closing, the sender will not be able to send any more messages. Any - attempt to send a message through a closed sender will raise a - [`SenderError`][frequenz.channels.SenderError]. - """ - self._closed = True - - def __str__(self) -> str: - """Return a string representation of this sender.""" - return f"{self._channel}:{type(self).__name__}" - - def __repr__(self) -> str: - """Return a string representation of this sender.""" - return f"{type(self).__name__}({self._channel!r})" - - -class _Empty: - """A sentinel to indicate that a message has not been set.""" - - -class _Receiver(Receiver[_T]): - """A receiver to receive messages from an Anycast channel. - - Should not be created directly, but through the - [`Anycast.new_receiver()`][frequenz.channels.Anycast.new_receiver] - method. - """ - - def __init__(self, channel: Anycast[_T], /) -> None: - """Initialize this receiver. - - Args: - channel: A reference to the channel that this receiver belongs to. - """ - self._channel: Anycast[_T] = channel - """The channel that this receiver belongs to.""" - - self._closed: bool = False - """Whether the receiver is closed.""" - - self._next: _T | type[_Empty] = _Empty - - @override - async def ready(self) -> bool: - """Wait until the receiver is ready with a message or an error. - - Once a call to [`.ready()`][frequenz.channels.Receiver.ready] has finished, the - message should be read with a call to - [`.consume()`][frequenz.channels.Receiver.consume] - ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The - receiver will remain ready (this method will return immediately) until it is - consumed. - - Returns: - Whether the receiver is still active. - """ - # if a message is already ready, then return immediately. - if self._next is not _Empty: - return True - - if self._closed: - return False - - # pylint: disable=protected-access - while len(self._channel._deque) == 0: - if self._channel._closed: - return False - async with self._channel._recv_cv: - await self._channel._recv_cv.wait() - self._next = self._channel._deque.popleft() - async with self._channel._send_cv: - self._channel._send_cv.notify(1) - # pylint: enable=protected-access - return True - - @override - def consume(self) -> _T: - """Return the latest message once [`ready()`][frequenz.channels.Receiver.ready] is complete. - - Returns: - The next message that was received. - - Raises: - ReceiverStoppedError: If the receiver stopped producing messages. - """ - if ( # pylint: disable=protected-access - self._next is _Empty and self._channel._closed - ): - raise ReceiverStoppedError(self) from ChannelClosedError(self._channel) - - if self._next is _Empty and self._closed: - raise ReceiverStoppedError(self) - - assert ( - self._next is not _Empty - ), "`consume()` must be preceded by a call to `ready()`" - # mypy doesn't understand that the assert above ensures that self._next is not - # _Sentinel. So we have to use a type ignore here. - next_val: _T = self._next # type: ignore[assignment] - self._next = _Empty - - return next_val - - @override - def close(self) -> None: - """Close this receiver. - - After closing, the receiver will not be able to receive any more messages. - """ - self._closed = True - - def __str__(self) -> str: - """Return a string representation of this receiver.""" - return f"{self._channel}:{type(self).__name__}" - - def __repr__(self) -> str: - """Return a string representation of this receiver.""" - return f"{type(self).__name__}({self._channel!r})" diff --git a/src/frequenz/channels/_broadcast.py b/src/frequenz/channels/_broadcast.py index 0aefd390..fe3116b6 100644 --- a/src/frequenz/channels/_broadcast.py +++ b/src/frequenz/channels/_broadcast.py @@ -6,238 +6,67 @@ from __future__ import annotations import logging -import warnings import weakref -from asyncio import Condition +from asyncio import AbstractEventLoop, Event, get_running_loop from collections import deque -from typing import Generic, TypeVar, overload +from typing import Generic, TypeVar from frequenz.core.warnings import ignoring_deprecations -from typing_extensions import deprecated, override, sentinel +from typing_extensions import deprecated, override from ._exceptions import ChannelClosedError from ._generic import ChannelMessageT from ._receiver import Receiver, ReceiverStoppedError -from ._sender import CloneableSubscribableSender, SenderClosedError, SenderError +from ._sender import ( + CloneableSubscribableSender, + SenderClosedError, + SenderError, + SenderHasNoReceiversError, +) _logger = logging.getLogger(__name__) -_NOT_GIVEN = sentinel("_NOT_GIVEN") -"""A marker for the arguments of the broadcast channel that were not passed.""" - _DEFAULT_BUFFER_SIZE = 50 """The default buffer size of broadcast receivers.""" -_LIMIT_DEPRECATION = ( - "The argument limit in {function} is deprecated and will be removed in " - "v2.0.0. Use buffer_size instead." -) -"""The warning of the deprecated `limit` argument, for a function's full name.""" - -def _resolve_buffer_size( - function: str, *, limit: int | _NOT_GIVEN, buffer_size: int | _NOT_GIVEN -) -> int: - """Return the buffer size to use out of `limit` and `buffer_size`. +def _check_buffer_size(buffer_size: int) -> int: + """Return the buffer size, after checking that it is valid. Args: - function: The name of the function that got the arguments, for the error - messages. - limit: The `limit` argument the function got, or `_NOT_GIVEN`. - buffer_size: The `buffer_size` argument the function got, or `_NOT_GIVEN`. + buffer_size: The buffer size to check. Returns: - The buffer size to use. + The buffer size. Raises: - TypeError: If both `limit` and `buffer_size` were given. ValueError: If the buffer size is smaller than 1. """ - if limit is not _NOT_GIVEN and buffer_size is not _NOT_GIVEN: - raise TypeError( - f"{function}() got both `limit` and `buffer_size`, " - "pass only `buffer_size`" - ) - if limit is not _NOT_GIVEN: - warnings.warn( - _LIMIT_DEPRECATION.format(function=f"frequenz.channels.{function}"), - category=DeprecationWarning, - # The caller of the function that got the argument - stacklevel=3, + if buffer_size < 1: + raise ValueError( + f"The receiver's buffer_size must be at least 1, not {buffer_size}" ) - argument = "limit" if limit is not _NOT_GIVEN else "buffer_size" - size = limit if limit is not _NOT_GIVEN else buffer_size - if size is _NOT_GIVEN: - return _DEFAULT_BUFFER_SIZE - if size < 1: - raise ValueError(f"The receiver's {argument} must be at least 1, not {size}") - return size + return buffer_size -@deprecated("Please use BroadcastChannel instead.") +@deprecated( + "frequenz.channels.Broadcast is deprecated. " + "Use frequenz.channels.BroadcastChannel instead." +) class Broadcast( # pylint: disable=too-many-instance-attributes Generic[ChannelMessageT] ): """A channel that delivers all messages to all receivers. - # Description - - [`Broadcast`][frequenz.channels.Broadcast] channels can have multiple - [senders][frequenz.channels.Sender] and multiple - [receivers][frequenz.channels.Receiver]. Each message sent through any of the - senders will be received by all receivers. - -
- ```bob - .---------. msg1 msg1,msg2 .-----------. - | Sender +------. .---------->| Receiver | - '---------' | .----------. | '-----------' - +----->| Channel +-----+ - .---------. | '----------' | .-----------. - | Sender +------' '----------->| Receiver | - '---------' msg2 msg1,msg2 '-----------' - ``` -
- - !!! Note inline end "Characteristics" - - * **Buffered:** Yes, with one buffer per receiver - * **Buffer full policy:** Drop oldest message - * **Multiple receivers:** Yes - * **Multiple senders:** Yes - * **Thread-safe:** No - - This channel is buffered, and when messages are not being consumed fast - enough and the buffer fills up, old messages will get dropped. - - Each receiver has its own buffer, so messages will only be dropped for - receivers that can't keep up with the senders, and not for the whole - channel. + Deprecated: + Deprecated since v1.12.0. Use + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] instead. - To create a new [senders][frequenz.channels.Sender] and - [receivers][frequenz.channels.Receiver] you can use the + Senders and receivers are created with [`.new_sender()`][frequenz.channels.Broadcast.new_sender] and - [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver] methods - respectively. - - When a channel is not needed anymore, it should be closed with - [`.aclose()`][frequenz.channels.Broadcast.aclose]. This will prevent further - attempts to [`send()`][frequenz.channels.Sender.send] data, and will allow - receivers to drain the pending items on their queues, but after that, - subsequent [`receive()`][frequenz.channels.Receiver.receive] calls will - raise a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. - - This channel is useful, for example, to implement a pub/sub pattern, where - multiple receivers can subscribe to a channel to receive all messages. - - In cases where each message needs to be delivered only to one receiver, an - [anycast][frequenz.channels.Anycast] channel may be used. - - # Examples - - Example: Send a few numbers to a receiver - This is a very simple example that sends a few numbers from a single sender to - a single receiver. - - ```python - import asyncio - - from frequenz.channels import Broadcast, Sender - - - async def send(sender: Sender[int]) -> None: - for message in range(3): - print(f"sending {message}") - await sender.send(message) - - - async def main() -> None: - channel = Broadcast[int](name="numbers") - - sender = channel.new_sender() - receiver = channel.new_receiver() - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - - - asyncio.run(main()) - ``` - - The output should look something like (although the sending and received might - appear more interleaved): - - ``` - sending 0 - sending 1 - sending 2 - received 0 - received 1 - received 2 - ``` - - Example: Send a few number from multiple senders to multiple receivers - This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. - - ```python - import asyncio - - from frequenz.channels import Broadcast, Receiver, ReceiverStoppedError, Sender - - - async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: - for message in range(start, stop): - print(f"{name} sending {message}") - await sender.send(message) - - - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass - - - async def main() -> None: - acast = Broadcast[int](name="numbers") - - async with asyncio.TaskGroup() as task_group: - task_group.create_task(send("sender_1", acast.new_sender(), 10, 13)) - task_group.create_task(send("sender_2", acast.new_sender(), 20, 22)) - task_group.create_task(recv("receiver_1", acast.new_receiver())) - task_group.create_task(recv("receiver_2", acast.new_receiver())) - - - asyncio.run(main()) - ``` - - The output should look something like this(although the sending and received - might appear interleaved in a different way): - - ``` - sender_1 sending 10 - sender_1 sending 11 - sender_1 sending 12 - sender_2 sending 20 - sender_2 sending 21 - receiver_1 received 10 - receiver_1 received 11 - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 - receiver_2 received 10 - receiver_2 received 11 - receiver_2 received 12 - receiver_2 received 20 - receiver_2 received 21 - ``` + [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver]. Unless it is + created with `auto_close=True`, the channel stays open until it is closed with + [`.aclose()`][frequenz.channels.Broadcast.aclose]. """ def __init__( @@ -254,14 +83,17 @@ def __init__( shown in the string representation of the channel. resend_latest: When True, every time a new receiver is created with [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], the last - message seen by the channel will be sent to the new receiver - automatically. This allows new receivers on slow streams to get the - latest message as soon as they are created, without having to wait for - the next message on the channel to arrive. It is safe to be set in - data/reporting channels, but is not recommended for use in channels that - stream control instructions. - auto_close: If True, the channel will be closed when all senders or all - receivers are closed. + message sent to the channel will be sent to the new receiver + automatically, unless it was `None` or the channel was closed. A + message sent while the channel had no receivers counts too. This allows + new receivers on slow streams to get the latest message as soon as they + are created, without having to wait for the next message on the channel + to arrive. It is safe to be set in data/reporting channels, but is not + recommended for use in channels that stream control instructions. + auto_close: If True, the channel is closed when its last sender is + closed, or when a receiver waits for messages while the channel has + no senders. A `send()` while it has no receivers raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. """ self._name: str = name """The name of the broadcast channel. @@ -269,8 +101,17 @@ def __init__( Only used for debugging purposes. """ - self._recv_cv: Condition = Condition() - """The condition to wait for data in the channel's buffer.""" + self._wakeup: Event = Event() + """The event receivers wait on for new messages or state changes. + + Each wake-up replaces it with a fresh event, then sets the old one, which wakes + up all receivers waiting on it. It can be set from synchronous code running on + the receivers' event loop, like + [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. + """ + + self._wakeup_loop: AbstractEventLoop | None = None + """The loop of the receivers waiting on `_wakeup`, cleared on each wake-up.""" self._sender_count: int = 0 """The number of senders attached to this channel.""" @@ -287,19 +128,22 @@ def __init__( """The latest message sent to the channel.""" self._auto_close_enabled: bool = auto_close - """Whether to close the channel when all senders or all receivers are closed.""" + """Whether the channel closes itself when it has no senders left. + + If `True`, `send()` also raises while the channel has no receivers. See the + `auto_close` argument. + """ + + self._default_buffer_size: int = _DEFAULT_BUFFER_SIZE + """The default buffer size of receivers created with `BroadcastSender.subscribe()`.""" + + self._default_warn_on_overflow: bool = True + """The default overflow warning setting of subscribed receivers.""" self.resend_latest: bool = resend_latest """Whether to resend the latest message to new receivers. - When `True`, every time a new receiver is created with - [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], it will - automatically get sent the latest message on the channel. This allows new - receivers on slow streams to get the latest message as soon as they are created, - without having to wait for the next message on the channel to arrive. - - It is safe to be set in data/reporting channels, but is not recommended for use - in channels that stream control instructions. + See the `resend_latest` argument of the constructor. """ @property @@ -328,21 +172,22 @@ async def aclose(self) -> None: Receivers will still be able to drain the pending items on their queues, but after that, subsequent - [`receive()`][frequenz.channels.Receiver.receive] calls will return `None` - immediately. + [`receive()`][frequenz.channels.Receiver.receive] calls will raise a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. """ self._latest = None self._closed = True - async with self._recv_cv: - self._recv_cv.notify_all() - - @deprecated("The close() method is deprecated, use aclose() instead") - async def close(self) -> None: - """Close the channel. - - Deprecated alias for [`.aclose()`][frequenz.channels.Broadcast.aclose]. - """ - return await self.aclose() + self._wake_receivers() + + def _wake_receivers(self) -> None: + """Wake up all receivers waiting for new messages.""" + wakeup, self._wakeup = self._wakeup, Event() + loop, self._wakeup_loop = self._wakeup_loop, None + # Receivers can't be woken up once their loop is closed, and `set()` would + # raise. Any other error from `set()` is raised. + if loop is not None and loop.is_closed(): + return + wakeup.set() def new_sender(self) -> BroadcastSender[ChannelMessageT]: """Return a new sender attached to this channel.""" @@ -367,7 +212,7 @@ def new_receiver( A new receiver attached to this channel. """ recv: BroadcastReceiver[ChannelMessageT] = BroadcastReceiver( - self, name=name, limit=limit, warn_on_overflow=warn_on_overflow + self, name=name, buffer_size=limit, warn_on_overflow=warn_on_overflow ) self._receivers[hash(recv)] = weakref.ref(recv) if self.resend_latest and self._latest is not None: @@ -395,9 +240,9 @@ def __repr__(self) -> str: class BroadcastSender(CloneableSubscribableSender[_T]): """A sender to send messages to the broadcast channel. - Should not be created directly, but through the - [`.clone()`][frequenz.channels.BroadcastSender.clone] - method of an existing sender. + Should not be created directly, but through + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the + [`.clone()`][frequenz.channels.BroadcastSender.clone] method of an existing sender. """ def __init__(self, channel: Broadcast[_T], /) -> None: @@ -419,8 +264,26 @@ def sender_count(self) -> int: """The number of open senders attached to this sender's channel.""" return self._channel._sender_count # pylint: disable=protected-access + @property + def has_receivers(self) -> bool: + """Whether this sender's channel is open and has any receivers. + + Producers can check this to stop producing messages that nobody would + receive. While this is `False`, an open sender of an open + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError] + from [`send()`][frequenz.channels.BroadcastSender.send] until a new receiver is + created with [`subscribe()`][frequenz.channels.BroadcastSender.subscribe]. + + This doesn't check whether this sender itself is closed. + """ + # pylint: disable=protected-access + return not self._channel._closed and any( + recv_ref() is not None for recv_ref in self._channel._receivers.values() + ) + @override - async def send(self, message: _T, /) -> None: + async def send(self, message: _T, /) -> None: # noqa: DOC503 (raised indirectly) """Send a message to all broadcast receivers. Args: @@ -431,14 +294,13 @@ async def send(self, message: _T, /) -> None: A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is set as the cause. SenderClosedError: If this sender was closed. + SenderHasNoReceiversError: If this sender and its channel are open, but the + channel has no receivers, and it is a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a + `Broadcast` created with `auto_close=True`. """ - if self._closed: - raise SenderClosedError(self) + self._check_open() # pylint: disable=protected-access - if self._channel._closed: - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) stale_refs = [] for _hash, recv_ref in self._channel._receivers.items(): recv = recv_ref() @@ -448,14 +310,10 @@ async def send(self, message: _T, /) -> None: recv._enqueue(message) for _hash in stale_refs: del self._channel._receivers[_hash] - if self._channel._auto_close_enabled and len(self._channel._receivers) == 0: - await self._channel.aclose() - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) self._channel._latest = message - async with self._channel._recv_cv: - self._channel._recv_cv.notify_all() + if self._channel._auto_close_enabled and len(self._channel._receivers) == 0: + raise SenderHasNoReceiversError(self) + self._channel._wake_receivers() # pylint: enable=protected-access @override @@ -477,56 +335,54 @@ async def aclose(self) -> None: ): await self._channel.aclose() + def _check_open(self) -> None: + """Check that this sender and its channel are open. + + Raises: + SenderError: If the underlying channel is closed. + SenderClosedError: If this sender is closed. + """ + if self._closed: + raise SenderClosedError(self) + if self._channel._closed: # pylint: disable=protected-access + raise SenderError("The channel was closed", self) from ChannelClosedError( + self._channel + ) + @override - def clone(self) -> BroadcastSender[_T]: - """Return a clone of this sender.""" - return BroadcastSender(self._channel) + def clone(self) -> BroadcastSender[_T]: # noqa: DOC502 (raised indirectly) + """Return a clone of this sender. - @overload - def subscribe( - self, - name: str | None = None, - *, - buffer_size: int = 50, - warn_on_overflow: bool = True, - ) -> BroadcastReceiver[_T]: ... - - @overload - @deprecated( - "The argument limit in frequenz.channels.BroadcastSender.subscribe is " - "deprecated and will be removed in v2.0.0. Use buffer_size instead." - ) - def subscribe( - self, - name: str | None = None, - limit: int = 50, - warn_on_overflow: bool = True, - ) -> BroadcastReceiver[_T]: ... + Returns: + A new sender attached to this sender's channel. + + Raises: + SenderError: If the underlying channel is closed. + SenderClosedError: If this sender is closed. + """ + self._check_open() + return BroadcastSender(self._channel) @override - def subscribe( # noqa: DOC503 (raised indirectly) + def subscribe( # noqa: DOC502 (raised indirectly) self, name: str | None = None, - limit: int | _NOT_GIVEN = _NOT_GIVEN, - warn_on_overflow: bool = True, *, - buffer_size: int | _NOT_GIVEN = _NOT_GIVEN, + buffer_size: int | None = None, + warn_on_overflow: bool | None = None, ) -> BroadcastReceiver[_T]: """Return a new receiver attached to this sender's channel. - Deprecated: - The `limit` argument is deprecated since v1.13.0. Use `buffer_size` - instead. - Args: name: A name to identify the receiver in the logs. - limit: Deprecated, use `buffer_size` instead. Passing both `limit` - and `buffer_size` raises a `TypeError`. + buffer_size: Number of messages the receiver can hold in its buffer. If + `None` or not given, the buffer size the `BroadcastChannel` was + created with is used, or `50` for a `Broadcast`. It must be at + least 1. warn_on_overflow: Whether to log a warning when the receiver's buffer is - full and a message is dropped. Pass it by keyword: passing it by - position requires passing the deprecated `limit` too. - buffer_size: Number of messages the receiver can hold in its buffer (50 - if neither this nor `limit` is given). It must be at least 1. + full and a message is dropped. If `None`, the `warn_on_overflow` + setting the `BroadcastChannel` was created with is used, or `True` + for a `Broadcast`. Returns: A new receiver attached to this sender's channel. @@ -534,21 +390,24 @@ def subscribe( # noqa: DOC503 (raised indirectly) Raises: SenderError: If the underlying channel is closed. SenderClosedError: If this sender is closed. - TypeError: If both `limit` and `buffer_size` are given. ValueError: If the buffer size is smaller than 1. """ - if self._closed: - raise SenderClosedError(self) - if self._channel._closed: # pylint: disable=protected-access - raise SenderError("The channel was closed", self) from ChannelClosedError( - self._channel - ) - buffer_size = _resolve_buffer_size( - "BroadcastSender.subscribe", limit=limit, buffer_size=buffer_size - ) + self._check_open() + # pylint: disable=protected-access return self._channel.new_receiver( - name=name, limit=buffer_size, warn_on_overflow=warn_on_overflow + name=name, + limit=( + self._channel._default_buffer_size + if buffer_size is None + else _check_buffer_size(buffer_size) + ), + warn_on_overflow=( + self._channel._default_warn_on_overflow + if warn_on_overflow is None + else warn_on_overflow + ), ) + # pylint: enable=protected-access def __str__(self) -> str: """Return a string representation of this sender.""" @@ -562,7 +421,8 @@ def __repr__(self) -> str: class BroadcastReceiver(Receiver[_T]): """A receiver to receive messages from the broadcast channel. - Should not be created directly, but through the + Should not be created directly, but through + [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] method of an existing sender. """ @@ -573,7 +433,7 @@ def __init__( /, *, name: str | None, - limit: int, + buffer_size: int, warn_on_overflow: bool, ) -> None: """Initialize this receiver. @@ -583,13 +443,12 @@ def __init__( get dropped just in this receiver. Args: - channel: A reference to the [`Broadcast`][frequenz.channels.Broadcast] - channel that this receiver belongs to. + channel: A reference to the broadcast channel this receiver belongs to. name: A name to identify the receiver in the logs. If `None` an `id(self)`-based name will be used. This is only for debugging purposes, it will be shown in the string representation of the receiver. - limit: Number of messages the receiver can hold in its buffer. + buffer_size: Number of messages the receiver can hold in its buffer. warn_on_overflow: Whether to log a warning when the receiver's buffer is full and a message is dropped. """ @@ -604,7 +463,7 @@ def __init__( self._channel: Broadcast[_T] = channel """The broadcast channel that this receiver belongs to.""" - self._q: deque[_T] = deque(maxlen=limit) + self._q: deque[_T] = deque(maxlen=buffer_size) """The receiver's internal message queue.""" self._closed: bool = False @@ -629,6 +488,23 @@ def _enqueue(self, message: _T, /) -> None: ) self._q.append(message) + @property + def has_senders(self) -> bool: + """Whether this receiver's channel is open and has any senders. + + A [`BroadcastChannel`][frequenz.channels.BroadcastChannel] is closed as soon + as its last sender is closed. So once this is `False` on a + `BroadcastChannel`, it stays `False`, and no new messages will arrive. The + messages already in this receiver's buffer can still be received, unless this + receiver is closed. + + A sender that was garbage-collected without being closed still counts. + + This doesn't check whether this receiver itself is closed. + """ + # pylint: disable=protected-access + return not self._channel._closed and self._channel._sender_count > 0 + def __len__(self) -> int: """Return the number of unconsumed messages in the broadcast receiver. @@ -655,10 +531,8 @@ async def ready(self) -> bool: if self._q: return True - # Use a while loop here, to handle spurious wakeups of condition variables. - # - # The condition also makes sure that if there are already messages ready to be - # consumed, then we return immediately. + # Use a while loop here, because receivers are woken up on every channel + # state change, not only when a message for this receiver arrives. # pylint: disable=protected-access while len(self._q) == 0: if self._channel._closed or self._closed: @@ -666,8 +540,9 @@ async def ready(self) -> bool: if self._channel._auto_close_enabled and self._channel._sender_count == 0: await self._channel.aclose() return False - async with self._channel._recv_cv: - await self._channel._recv_cv.wait() + if self._channel._wakeup_loop is None: + self._channel._wakeup_loop = get_running_loop() + await self._channel._wakeup.wait() return True # pylint: enable=protected-access @@ -697,14 +572,21 @@ def consume(self) -> _T: def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a + After calling this method, the messages left in the receiver's buffer are + dropped, and trying to receive a message raises a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + + Call this only from the thread that runs the event loop of the channel's + receivers. From another thread, tasks waiting on any receiver of the channel + might not wake up. If asyncio debug mode is on and a task is waiting, this also + raises a `RuntimeError`, and the waiting tasks stay stuck. """ self._closed = True - self._channel._receivers.pop( # pylint: disable=protected-access - hash(self), None - ) + self._q.clear() + # pylint: disable=protected-access + self._channel._receivers.pop(hash(self), None) + self._channel._wake_receivers() + # pylint: enable=protected-access def __str__(self) -> str: """Return a string representation of this receiver.""" @@ -712,10 +594,10 @@ def __str__(self) -> str: def __repr__(self) -> str: """Return a string representation of this receiver.""" - limit = self._q.maxlen - assert limit is not None + buffer_size = self._q.maxlen + assert buffer_size is not None return ( - f"{type(self).__name__}(name={self._name!r}, limit={limit!r}, " + f"{type(self).__name__}(name={self._name!r}, buffer_size={buffer_size!r}, " f"{self._channel!r}):" ) @@ -759,24 +641,50 @@ class BroadcastChannel( receivers that can't keep up with the senders, and not for the whole channel. - Instantiating this class will create a new broadcast channel, and return an - initial sender and a receiver. Further senders and receivers can be created - with the [`BroadcastSender.clone()`][frequenz.channels.BroadcastSender.clone], + Instantiating this class creates a new broadcast channel, and returns an + initial sender and receiver. Further senders and receivers can be created + with the [`BroadcastSender.clone()`][frequenz.channels.BroadcastSender.clone] and [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe] methods respectively. When a sender or a receiver is not needed anymore, it should be closed with [`BroadcastSender.aclose()`][frequenz.channels.BroadcastSender.aclose] or - [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. This will prevent - further attempts to [`send()`][frequenz.channels.BroadcastSender.send] data, - and will allow receivers to drain the pending items on their queues, but - after that, subsequent [`receive()`][frequenz.channels.Receiver.receive] calls - will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. - - When all senders of a channel are closed, all its receivers will be - automatically closed, and vice versa. + [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close]. + + The channel closes itself when all its senders are closed. This is what each side + sees: + + * As soon as all senders are closed, the channel is closed. Receivers can still + drain the messages pending in their buffers, but after that, + [`receive()`][frequenz.channels.Receiver.receive] raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], and `async + for` loops over them end. + + * While all receivers are closed or garbage-collected, + [`send()`][frequenz.channels.BroadcastSender.send] drops the message and raises a + [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]. The + channel stays open, so once + [`subscribe()`][frequenz.channels.BroadcastSender.subscribe] creates a new + receiver, sending works again. With `resend_latest=True`, that receiver first + gets the last message sent, unless it was `None`, even if `send()` raised. + + Senders can check + [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] to stop + producing messages that nobody would receive, and receivers can check + [`has_senders`][frequenz.channels.BroadcastReceiver.has_senders] to find out + whether new messages can still arrive. + + Tip: + Close every sender, also when a task fails, for example with + `async with contextlib.aclosing(sender):`. A sender that is never closed keeps + the channel open, even if it was garbage-collected, and its receivers keep + waiting for messages. + + Close the initial receiver if it isn't needed, instead of binding it to `_`. + Until `_` is reassigned or goes out of scope, that receiver stays attached: + [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] stays + `True`, and the receiver's buffer fills up. This channel is useful, for example, to implement a pub/sub pattern, where multiple consumers can subscribe to a channel to receive all messages. @@ -785,12 +693,12 @@ class BroadcastChannel( Example: Send a few numbers to a receiver This is a very simple example that sends a few numbers from a single sender to - a single receiver. + a single receiver. The receiver stops when the sender is closed. ```python import asyncio - from frequenz.channels import BroadcastChannel, Sender + from frequenz.channels import BroadcastChannel, Receiver, Sender async def send(sender: Sender[int]) -> None: @@ -800,15 +708,18 @@ async def send(sender: Sender[int]) -> None: await sender.aclose() + async def receive(receiver: Receiver[int]) -> None: + async for message in receiver: + print(f"received {message}") + print("all senders are closed") + + async def main() -> None: sender, receiver = BroadcastChannel[int](name="numbers") async with asyncio.TaskGroup() as task_group: task_group.create_task(send(sender)) - for _ in range(3): - message = await receiver.receive() - print(f"received {message}") - await asyncio.sleep(0.1) # sleep (or work) with the data + task_group.create_task(receive(receiver)) asyncio.run(main()) @@ -824,16 +735,17 @@ async def main() -> None: received 0 received 1 received 2 + all senders are closed ``` - Example: Send a few number from multiple senders to multiple receivers + Example: Send a few numbers from multiple senders to multiple receivers This is a more complex example that sends a few numbers from multiple senders to - multiple receivers, using a small buffer to force the senders to block. + multiple receivers. The receivers stop when all senders are closed. ```python import asyncio - from frequenz.channels import BroadcastChannel, Receiver, ReceiverStoppedError, Sender + from frequenz.channels import BroadcastChannel, Receiver, Sender async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: @@ -843,30 +755,28 @@ async def send(name: str, sender: Sender[int], start: int, stop: int) -> None: await sender.aclose() - async def recv(name: str, receiver: Receiver[int]) -> None: - try: - async for message in receiver: - print(f"{name} received {message}") + async def receive(name: str, receiver: Receiver[int]) -> None: + async for message in receiver: + print(f"{name} received {message}") await asyncio.sleep(0.1) # sleep (or work) with the data - except ReceiverStoppedError: - pass async def main() -> None: sender_1, receiver_1 = BroadcastChannel[int](name="numbers") sender_2 = sender_1.clone() receiver_2 = sender_1.subscribe() + async with asyncio.TaskGroup() as task_group: task_group.create_task(send("sender_1", sender_1, 10, 13)) task_group.create_task(send("sender_2", sender_2, 20, 22)) - task_group.create_task(recv("receiver_1", receiver_1)) - task_group.create_task(recv("receiver_2", receiver_2)) + task_group.create_task(receive("receiver_1", receiver_1)) + task_group.create_task(receive("receiver_2", receiver_2)) asyncio.run(main()) ``` - The output should look something like this(although the sending and received + The output should look something like this (although the sending and received might appear interleaved in a different way): ``` @@ -876,100 +786,111 @@ async def main() -> None: sender_2 sending 20 sender_2 sending 21 receiver_1 received 10 - receiver_1 received 11 - receiver_1 received 12 - receiver_1 received 20 - receiver_1 received 21 receiver_2 received 10 + receiver_1 received 11 receiver_2 received 11 + receiver_1 received 12 receiver_2 received 12 + receiver_1 received 20 receiver_2 received 20 + receiver_1 received 21 receiver_2 received 21 ``` + + Example: Stop producing messages when nobody is listening + This example produces messages only for as long as there are receivers to + receive them. + + ```python + import asyncio + + from frequenz.channels import BroadcastChannel, BroadcastSender, Receiver + + + async def produce(sender: BroadcastSender[int]) -> None: + counter = 0 + while sender.has_receivers: + await sender.send(counter) + counter += 1 + await asyncio.sleep(0.1) # wait for (or compute) the next message + print(f"no receivers left, stopping after {counter} messages") + await sender.aclose() + + + async def consume(receiver: Receiver[int]) -> None: + for _ in range(3): + print(f"received {await receiver.receive()}") + receiver.close() + + + async def main() -> None: + sender, receiver = BroadcastChannel[int](name="numbers") + + async with asyncio.TaskGroup() as task_group: + task_group.create_task(produce(sender)) + task_group.create_task(consume(receiver)) + + + asyncio.run(main()) + ``` + + The output should be: + + ``` + received 0 + received 1 + received 2 + no receivers left, stopping after 3 messages + ``` """ - @overload - def __new__( + def __new__( # noqa: DOC502 (raised indirectly) cls, name: str, - resend_latest: bool = False, *, - buffer_size: int = 50, - warn_on_overflow: bool = True, - ) -> BroadcastChannel[ChannelMessageT]: ... - - @overload - @deprecated( - "The argument limit in frequenz.channels.BroadcastChannel is deprecated and " - "will be removed in v2.0.0. Use buffer_size instead." - ) - def __new__( - cls, - name: str, - resend_latest: bool = False, - limit: int = 50, - warn_on_overflow: bool = True, - ) -> BroadcastChannel[ChannelMessageT]: ... - - def __new__( # noqa: DOC502 (raised indirectly), pylint: disable=too-many-arguments - cls, - name: str, resend_latest: bool = False, - limit: int | _NOT_GIVEN = _NOT_GIVEN, + buffer_size: int = 50, warn_on_overflow: bool = True, - *, - buffer_size: int | _NOT_GIVEN = _NOT_GIVEN, ) -> BroadcastChannel[ChannelMessageT]: """Create a new BroadcastChannel instance. - Deprecated: - The `limit` argument is deprecated since v1.13.0. Use `buffer_size` - instead. - Args: name: The name of the channel. This is for logging purposes, and it will be shown in the string representation of the channel. resend_latest: When True, every time a new receiver is created with - [`Broadcast.new_receiver()`][frequenz.channels.Broadcast.new_receiver], - the last message seen by the channel will be sent to the - new receiver automatically. This allows new receivers on slow streams to - get the latest message as soon as they are created, without having to - wait for the next message on the channel to arrive. It is safe to be - set in data/reporting channels, but is not recommended for use in + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe], + the last message sent to the channel will be sent to the new receiver + automatically, unless it was `None`. A message sent while the channel + had no receivers counts too. This allows new receivers on slow streams + to get the latest message as soon as they are created, without having + to wait for the next message on the channel to arrive. It is safe to + be set in data/reporting channels, but is not recommended for use in channels that stream control instructions. - limit: Deprecated, use `buffer_size` instead. Passing both `limit` - and `buffer_size` raises a `TypeError`. + buffer_size: Number of messages each receiver can hold in its buffer, for + the initial receiver and, by default, for receivers created with + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. + It must be at least 1. warn_on_overflow: Whether to log a warning when a receiver's buffer is full - and a message is dropped. Pass it by keyword: passing it by position - requires passing the deprecated `limit` too. - buffer_size: Number of messages the receivers can hold in their buffers - (50 if neither this nor `limit` is given). It must be at least 1. + and a message is dropped. Applies to the initial receiver and, by + default, to receivers created with + [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]. Returns: A new BroadcastChannel instance that can be destructured into an initial sender and receiver. Raises: - TypeError: If both `limit` and `buffer_size` are given. ValueError: If the buffer size is smaller than 1. """ - buffer_size = _resolve_buffer_size( - "BroadcastChannel", limit=limit, buffer_size=buffer_size - ) # Broadcast is deprecated, but it is an implementation detail of this # class, so users shouldn't be warned about it. with ignoring_deprecations(): channel = Broadcast[ChannelMessageT]( name=name, resend_latest=resend_latest, auto_close=True ) - return tuple.__new__( - cls, - ( - channel.new_sender(), - channel.new_receiver( - name=f"{name}_receiver", - limit=buffer_size, - warn_on_overflow=warn_on_overflow, - ), - ), - ) + # pylint: disable=protected-access + channel._default_buffer_size = _check_buffer_size(buffer_size) + channel._default_warn_on_overflow = warn_on_overflow + # pylint: enable=protected-access + sender = channel.new_sender() + return tuple.__new__(cls, (sender, sender.subscribe(name=f"{name}_receiver"))) diff --git a/src/frequenz/channels/_exceptions.py b/src/frequenz/channels/_exceptions.py index 191d83cc..9412fe1e 100644 --- a/src/frequenz/channels/_exceptions.py +++ b/src/frequenz/channels/_exceptions.py @@ -19,11 +19,10 @@ was closed while sending or receiving a message, the original exception will be available as the cause of the exception: -```python show_lines="6:" -from frequenz.channels import Anycast, ChannelClosedError, SenderError +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ChannelClosedError, SenderError -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[int](name="test-channel") try: await sender.send(42) @@ -44,11 +43,10 @@ explicitly calling [`receive()`][frequenz.channels.Receiver.receive] on the receiver after the iteration is done: - ```python show_lines="6:" - from frequenz.channels import Anycast, ChannelClosedError, ReceiverStoppedError + ```python show_lines="5:" + from frequenz.channels import BroadcastChannel, ChannelClosedError, ReceiverStoppedError - channel = Anycast[int](name="test-channel") - receiver = channel.new_receiver() + sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver: print(message) diff --git a/src/frequenz/channels/_latest_value_cache.py b/src/frequenz/channels/_latest_value_cache.py index 1e85786f..71774bdc 100644 --- a/src/frequenz/channels/_latest_value_cache.py +++ b/src/frequenz/channels/_latest_value_cache.py @@ -16,16 +16,18 @@ Example: ```python - from frequenz.channels import Broadcast, LatestValueCache + import asyncio - channel = Broadcast[int](name="lvc_test") + from frequenz.channels import BroadcastChannel, LatestValueCache - cache = LatestValueCache(channel.new_receiver()) - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="lvc_test") + + cache = LatestValueCache(receiver) assert not cache.has_value() await sender.send(5) + await asyncio.sleep(0) # Let the cache process the message assert cache.has_value() assert cache.get() == 5 diff --git a/src/frequenz/channels/_merge.py b/src/frequenz/channels/_merge.py index 68c1d134..ac5000a4 100644 --- a/src/frequenz/channels/_merge.py +++ b/src/frequenz/channels/_merge.py @@ -9,21 +9,19 @@ stream, you can use [`merge()`][frequenz.channels.merge] to create a new receiver that will receive messages from all the given receivers: -```python show_lines="8:" -from frequenz.channels import Anycast, Receiver, merge +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, Receiver, merge -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[int] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[int](name="channel2") async for message in merge(receiver1, receiver2): print(message) ``` -If the first message comes from `channel2` and the second message from `channel1`, the -first message will be received immediately, and the second message will be received as -soon as it is available. +If the first message comes from `receiver2` and the second message from `receiver1`, +the first message will be received immediately, and the second message will be +received as soon as it is available. This can be helpful when you just need to receive messages and don't care about where are they coming from specifically. If you need to know where the message came @@ -69,12 +67,10 @@ def merge(*receivers: Receiver[ReceiverMessageT_co]) -> Merger[ReceiverMessageT_ stream like this: ```python - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel, merge - channel1 = Broadcast[int](name="input-channel-1") - channel2 = Broadcast[int](name="input-channel-2") - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() + sender1, receiver1 = BroadcastChannel[int](name="input-channel-1") + sender2, receiver2 = BroadcastChannel[int](name="input-channel-2") async for message in merge(receiver1, receiver2): print(f"received {message}") diff --git a/src/frequenz/channels/_receiver.py b/src/frequenz/channels/_receiver.py index 32a02693..ee06460a 100644 --- a/src/frequenz/channels/_receiver.py +++ b/src/frequenz/channels/_receiver.py @@ -7,15 +7,15 @@ Messages are received from [channels](/user-guide/channels/index.md) through [`Receiver`][frequenz.channels.Receiver] objects. -[`Receiver`][frequenz.channels.Receiver]s are usually created by calling -`channel.new_receiver()` and are [async iterators][typing.AsyncIterator], so the easiest -way to receive messages from them as a stream is to use `async for`: +[`Receiver`][frequenz.channels.Receiver]s usually come from creating a channel, like a +[`BroadcastChannel`][frequenz.channels.BroadcastChannel], or from calling +`sender.subscribe()`. They are [async iterators][typing.AsyncIterator], so the +easiest way to receive messages from them as a stream is to use `async for`: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver: print(message) @@ -24,11 +24,10 @@ If you need to receive messages in different places or expecting a particular sequence, you can use the [`receive()`][frequenz.channels.Receiver.receive] method: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") first_message = await receiver.receive() print(f"First message: {first_message}") @@ -42,11 +41,10 @@ If you need to transform the received messages, receivers provide a [`map()`][frequenz.channels.Receiver.map] method to easily do so: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.map(lambda x: x + 1): print(message) @@ -60,11 +58,10 @@ If you need to filter the received messages, receivers provide a [`filter()`][frequenz.channels.Receiver.filter] method to easily do so: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.filter(lambda x: x % 2 == 0): print(message) # Only even numbers will be printed @@ -77,11 +74,10 @@ To filter messages based on the previous one, for example to skip repeated messages, use [`WithPrevious`][frequenz.channels.WithPrevious] to build the filter function: -```python show_lines="6:" -from frequenz.channels import Anycast, WithPrevious +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, WithPrevious -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") async for message in receiver.filter(WithPrevious(lambda old, new: old != new)): print(message) # Only messages different from the previous one will be printed @@ -121,11 +117,10 @@ async def process(data: Receiver[int], commands: Receiver[int] | None = None) -> closed), a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] exception is raised by [`receive()`][frequenz.channels.Receiver.receive] method. -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ReceiverError, ReceiverStoppedError -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") try: await receiver.receive() @@ -138,11 +133,10 @@ async def process(data: Receiver[int], commands: Receiver[int] | None = None) -> When used as an async iterator, the iteration will just stop without raising an exception: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, ReceiverError, ReceiverStoppedError -channel = Anycast[int](name="test-channel") -receiver = channel.new_receiver() +sender, receiver = BroadcastChannel[int](name="test-channel") try: async for message in receiver: @@ -162,10 +156,11 @@ async def process(data: Receiver[int], commands: Receiver[int] | None = None) -> [`Receiver.close()`][frequenz.channels.Receiver.close] method can be used for this purpose. -After [`Receiver.close()`][frequenz.channels.Receiver.close] is called, we can still -receive messages that are in the receiver's buffer, but as soon as the receiver's buffer -has been drained, trying to receive further messages from a *closed* receiver will raise -a [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. +After [`Receiver.close()`][frequenz.channels.Receiver.close] is called, some receivers +still deliver the messages in their buffer, and raise a +[`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError] once it is drained. +Others, like [`BroadcastReceiver`][frequenz.channels.BroadcastReceiver], raise it at +once. # Advanced Usage @@ -264,14 +259,16 @@ def consume(self) -> ReceiverMessageT_co: ReceiverError: If there is some problem with the receiver. """ + @abstractmethod def close(self) -> None: """Close the receiver. After calling this method, new messages will not be available from the receiver. - Once the receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + Trying to receive a message raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the receiver's buffer are received, depending on + the receiver. """ - raise NotImplementedError("close() must be implemented by subclasses") def __aiter__(self) -> Self: """Get an async iterator over the received messages. @@ -529,9 +526,11 @@ def consume(self) -> MappedMessageT_co: # noqa: DOC502 def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + After calling this method, new messages will not be received. Trying to + receive a message then raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the buffer are received, depending on the + input receiver. """ self._receiver.close() @@ -633,9 +632,11 @@ def consume(self) -> ReceiverMessageT_co: def close(self) -> None: """Close the receiver. - After calling this method, new messages will not be received. Once the - receiver's buffer is drained, trying to receive a message will raise a - [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError]. + After calling this method, new messages will not be received. Trying to + receive a message then raises a + [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once + or once the messages already in the buffer are received, depending on the + input receiver. """ self._receiver.close() diff --git a/src/frequenz/channels/_select.py b/src/frequenz/channels/_select.py index 677bd2fc..4493c2c9 100644 --- a/src/frequenz/channels/_select.py +++ b/src/frequenz/channels/_select.py @@ -18,13 +18,11 @@ function to check the source of the message, and the [`message`][frequenz.channels.Selected.message] attribute to access the message: -```python show_lines="8:" -from frequenz.channels import Anycast, ReceiverStoppedError, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, ReceiverStoppedError, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -46,13 +44,11 @@ If for some reason you want to ignore a received message, just add the receiver to the if-chain and do nothing with the message: - ```python show_lines="8:" - from frequenz.channels import Anycast, select, selected_from + ```python show_lines="6:" + from frequenz.channels import BroadcastChannel, select, selected_from - channel1: Anycast[int] = Anycast(name="channel1") - channel2: Anycast[str] = Anycast(name="channel2") - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() + sender1, receiver1 = BroadcastChannel[int](name="channel1") + sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -72,13 +68,11 @@ [`was_stopped`][frequenz.channels.Selected.was_stopped] method to check if the selected [`Receiver`][frequenz.channels.Receiver] was stopped: -```python show_lines="8:" -from frequenz.channels import Anycast, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): @@ -107,13 +101,11 @@ You can use a try-except block to handle exceptions as usual: -```python show_lines="8:" -from frequenz.channels import Anycast, ReceiverStoppedError, select, selected_from +```python show_lines="6:" +from frequenz.channels import BroadcastChannel, ReceiverStoppedError, select, selected_from -channel1: Anycast[int] = Anycast(name="channel1") -channel2: Anycast[str] = Anycast(name="channel2") -receiver1 = channel1.new_receiver() -receiver2 = channel2.new_receiver() +sender1, receiver1 = BroadcastChannel[int](name="channel1") +sender2, receiver2 = BroadcastChannel[str](name="channel2") async for selected in select(receiver1, receiver2): if selected_from(selected, receiver1): diff --git a/src/frequenz/channels/_sender.py b/src/frequenz/channels/_sender.py index 8a5a4445..4acf74a9 100644 --- a/src/frequenz/channels/_sender.py +++ b/src/frequenz/channels/_sender.py @@ -6,15 +6,16 @@ # Senders Messages are sent to a [channel](/user-guide/channels) through -[`Sender`][frequenz.channels.Sender] objects. [`Sender`][frequenz.channels.Sender]s are -usually created by calling `channel.new_sender()`, and are a very simple abstraction -that only provides a single [`send()`][frequenz.channels.Sender.send] method: +[`Sender`][frequenz.channels.Sender] objects. [`Sender`][frequenz.channels.Sender]s +usually come from creating a channel, like a +[`BroadcastChannel`][frequenz.channels.BroadcastChannel], or from calling +`sender.clone()`. They are a very simple abstraction that mainly provides a +[`send()`][frequenz.channels.Sender.send] method: -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[str](name="test-channel") await sender.send("Hello, world!") ``` @@ -36,17 +37,20 @@ If there is any failure sending a message, a [`SenderError`][frequenz.channels.SenderError] exception is raised. -```python show_lines="6:" -from frequenz.channels import Anycast +```python show_lines="5:" +from frequenz.channels import BroadcastChannel, SenderError -channel = Anycast[int](name="test-channel") -sender = channel.new_sender() +sender, receiver = BroadcastChannel[str](name="test-channel") try: await sender.send("Hello, world!") 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 @@ -114,6 +118,56 @@ 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 SenderHasNoReceiversError(TransientSenderError[SenderMessageT_co]): + """An error indicating that a message was sent to a channel without receivers. + + It is raised by the senders of a + [`BroadcastChannel`][frequenz.channels.BroadcastChannel], and of a `Broadcast` + created with `auto_close=True`. The message is dropped. With + `resend_latest=True`, new receivers still get it if it is the last message sent and + it isn't `None`. + + It is a [`TransientSenderError`][frequenz.channels.TransientSenderError]: the + sender and its channel stay open, so sending works again once a new receiver + subscribes. + """ + + def __init__(self, sender: Sender[SenderMessageT_co]): + """Initialize this error. + + Args: + sender: The [`Sender`][frequenz.channels.Sender] that tried to send the + message. + """ + super().__init__(f"Sender {sender} has no receivers", sender) + + class SubscribableSender(Sender[SenderMessageT_contra], ABC): """A [`Sender`][frequenz.channels.Sender] that can be subscribed to.""" diff --git a/src/frequenz/channels/_with_previous.py b/src/frequenz/channels/_with_previous.py index b676ec21..1c70bd05 100644 --- a/src/frequenz/channels/_with_previous.py +++ b/src/frequenz/channels/_with_previous.py @@ -30,42 +30,40 @@ class WithPrevious(Generic[ChannelMessageT]): Example: Receiving only messages that are different from the previous one. ```python - from frequenz.channels import Broadcast, WithPrevious + from frequenz.channels import BroadcastChannel, WithPrevious - channel = Broadcast[int](name="example") - receiver = channel.new_receiver().filter(WithPrevious(lambda old, new: old != new)) - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="example") + filtered = receiver.filter(WithPrevious(lambda old, new: old != new)) # This message will be received as it is the first message. await sender.send(1) - assert await receiver.receive() == 1 + assert await filtered.receive() == 1 - # This message will be skipped as it equals to the previous one. + # This message will be skipped as it equals the previous one. await sender.send(1) - # This message will be received as it is a different from the previous one. + # This message will be received as it is different from the previous one. await sender.send(0) - assert await receiver.receive() == 0 + assert await filtered.receive() == 0 ``` Example: Receiving only messages if they are bigger than the previous one. ```python - from frequenz.channels import Broadcast, WithPrevious + from frequenz.channels import BroadcastChannel, WithPrevious - channel = Broadcast[int](name="example") - receiver = channel.new_receiver().filter( + sender, receiver = BroadcastChannel[int](name="example") + filtered = receiver.filter( WithPrevious(lambda old, new: new > old, first_is_true=False) ) - sender = channel.new_sender() - # This message will skipped as first_is_true is False. + # This message will be skipped as first_is_true is False. await sender.send(1) # This message will be received as it is bigger than the previous one (1). await sender.send(2) - assert await receiver.receive() == 2 + assert await filtered.receive() == 2 - # This message will be skipped as it is smaller than the previous one (1). + # This message will be skipped as it is smaller than the previous one (2). await sender.send(0) # This message will be skipped as it is not bigger than the previous one (0). @@ -73,11 +71,11 @@ class WithPrevious(Generic[ChannelMessageT]): # This message will be received as it is bigger than the previous one (0). await sender.send(1) - assert await receiver.receive() == 1 + assert await filtered.receive() == 1 # This message will be received as it is bigger than the previous one (1). await sender.send(2) - assert await receiver.receive() == 2 + assert await filtered.receive() == 2 ``` """ diff --git a/src/frequenz/channels/event.py b/src/frequenz/channels/event.py index 87c58af5..6915435d 100644 --- a/src/frequenz/channels/event.py +++ b/src/frequenz/channels/event.py @@ -46,12 +46,10 @@ class Event(Receiver[None]): ```python import asyncio - from frequenz.channels import Anycast, select, selected_from + from frequenz.channels import BroadcastChannel, select, selected_from from frequenz.channels.event import Event - channel: Anycast[int] = Anycast(name="channel") - receiver = channel.new_receiver() - sender = channel.new_sender() + sender, receiver = BroadcastChannel[int](name="channel") stop_event = Event(name="stop") diff --git a/src/frequenz/channels/experimental/__init__.py b/src/frequenz/channels/experimental/__init__.py index 210cd02f..479ea50f 100644 --- a/src/frequenz/channels/experimental/__init__.py +++ b/src/frequenz/channels/experimental/__init__.py @@ -10,119 +10,8 @@ guidelines](https://github.com/frequenz-floss/docs/blob/v0.x.x/python/experimental-packages.md). """ -from typing import TYPE_CHECKING, TypeAlias, TypeVar - -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - -from ._grouping_latest_value_cache import GroupingLatestValueCache -from ._optional_receiver import OptionalReceiver from ._pipe import Pipe -from ._relay_sender import RelaySender __all__ = [ - "DefaultT", - "GroupingLatestValueCache", - "HashableT", - "NopReceiver", - "OptionalReceiver", "Pipe", - "RelaySender", - "ValueT_co", - "WithPrevious", ] - -# The type variables of `GroupingLatestValueCache` use a workaround: `@deprecated` -# only works on classes and functions, so it can't mark them. `deprecated_aliases()` -# is meant for symbols that moved or were renamed, but its `__getattr__` is the only -# way to warn when they are reached from here, so their aliases point at the private -# module that defines them, which is not a move. That's also why they need a custom -# `message` and hand-written notices: the generated ones would point at the private -# module. See https://github.com/frequenz-floss/frequenz-core-python/issues/222. -if TYPE_CHECKING: - from collections.abc import Hashable - - from .._nop_receiver import NopReceiver as _NopReceiver - from .._with_previous import WithPrevious as _WithPrevious - - NopReceiver: TypeAlias = _NopReceiver - """A place-holder receiver that will never receive a message. - - Deprecated: - Deprecated since v1.13.0. Use - [`frequenz.channels.NopReceiver`][frequenz.channels.NopReceiver] instead. - """ - - WithPrevious: TypeAlias = _WithPrevious - """A composable predicate to build predicates that can also use the previous message. - - Deprecated: - Deprecated since v1.13.0. Use - [`frequenz.channels.WithPrevious`][frequenz.channels.WithPrevious] instead. - """ - - # Type variables can't be aliased, so type checkers get new ones, equivalent to - # the ones in `_grouping_latest_value_cache`. - DefaultT = TypeVar("DefaultT") - """Type variable for the default value returned by - [`GroupingLatestValueCache.get`][frequenz.channels.experimental.GroupingLatestValueCache.get]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ - - HashableT = TypeVar("HashableT", bound=Hashable) - """Type variable for the keys used to group values in the - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ - - ValueT_co = TypeVar("ValueT_co", covariant=True) - """Covariant type variable for the values cached by the - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0 together with - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. - """ -else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "NopReceiver", - new_module="frequenz.channels", - since="v1.13.0", - ), - DeprecatedAlias( - "WithPrevious", - new_module="frequenz.channels", - since="v1.13.0", - ), - DeprecatedAlias( - "DefaultT", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - DeprecatedAlias( - "HashableT", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - DeprecatedAlias( - "ValueT_co", - new_module="frequenz.channels.experimental._grouping_latest_value_cache", - since="v1.13.0", - message="{old} is deprecated and will be removed in v2.0.0, together with " - "frequenz.channels.experimental.GroupingLatestValueCache. Copy it into " - "your project if you need it.", - ), - ) diff --git a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py b/src/frequenz/channels/experimental/_grouping_latest_value_cache.py deleted file mode 100644 index 2c57f3da..00000000 --- a/src/frequenz/channels/experimental/_grouping_latest_value_cache.py +++ /dev/null @@ -1,329 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""Caches the latest values in a receiver, grouped by key.""" - -import asyncio -from collections.abc import ( - Callable, - Hashable, - ItemsView, - Iterator, - KeysView, - Mapping, - ValuesView, -) -from typing import TypeVar, overload - -from typing_extensions import deprecated, override - -from .._receiver import Receiver - -ValueT_co = TypeVar("ValueT_co", covariant=True) -"""Covariant type variable for the values cached by the -[`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. -""" - -DefaultT = TypeVar("DefaultT") -"""Type variable for the default value returned by -[`GroupingLatestValueCache.get`][frequenz.channels.experimental.GroupingLatestValueCache.get]. -""" - -HashableT = TypeVar("HashableT", bound=Hashable) -"""Type variable for the keys used to group values in the -[`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache]. -""" - - -class _NotSpecified: - """A sentinel value to indicate that no default value was provided.""" - - def __repr__(self) -> str: - """Return a string representation of this sentinel.""" - return "<_NotSpecified>" - - -@deprecated( - "frequenz.channels.experimental.GroupingLatestValueCache is deprecated and will " - "be removed in v2.0.0. Copy its code into your project if you need it, or open " - "an issue at https://github.com/frequenz-floss/frequenz-channels-python/issues " - "if you think it should stay in frequenz-channels." -) -class GroupingLatestValueCache(Mapping[HashableT, ValueT_co]): - """A cache that stores the latest value in a receiver, grouped by key. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0. Copy its code into - your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - It provides a way to look up on demand, the latest value in a stream for any key, as - long as there has been at least one value received for that key. - - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache] - takes a [`Receiver`][frequenz.channels.Receiver] and a `key` function as arguments - and stores the latest value received by that receiver for each key separately. - - The - [`GroupingLatestValueCache`][frequenz.channels.experimental.GroupingLatestValueCache] - implements the [`Mapping`][collections.abc.Mapping] interface, so it can be used - like a dictionary. Additionally other methods from - [`MutableMapping`][collections.abc.MutableMapping] are implemented, but only methods - removing items from the cache are allowed, such as - [`pop()`][frequenz.channels.experimental.GroupingLatestValueCache.pop], - [`popitem()`][frequenz.channels.experimental.GroupingLatestValueCache.popitem], - [`clear()`][frequenz.channels.experimental.GroupingLatestValueCache.clear], and - [`__delitem__()`][frequenz.channels.experimental.GroupingLatestValueCache.__delitem__]. - Other update methods are not provided because the user should not update the cache - values directly. - - Example: - ```python - from frequenz.channels import Broadcast - from frequenz.channels.experimental import GroupingLatestValueCache - - channel = Broadcast[tuple[int, str]](name="lvc_test") - - cache = GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - sender = channel.new_sender() - - assert cache.get(6) is None - assert 6 not in cache - - await sender.send((6, "twenty-six")) - - assert 6 in cache - assert cache.get(6) == (6, "twenty-six") - - del cache[6] - - assert cache.get(6) is None - assert 6 not in cache - - await cache.stop() - ``` - """ - - def __init__( - self, - receiver: Receiver[ValueT_co], - *, - key: Callable[[ValueT_co], HashableT], - unique_id: str | None = None, - ) -> None: - """Create a new cache. - - Args: - receiver: The receiver to cache values from. - key: A function that takes a value and returns a key to group the values - by. - unique_id: A string to help uniquely identify this instance. If not - provided, a unique identifier will be generated from the object's - [`id()`][id]. It is used mostly for debugging purposes. - """ - self._receiver: Receiver[ValueT_co] = receiver - self._key: Callable[[ValueT_co], HashableT] = key - self._unique_id: str = hex(id(self)) if unique_id is None else unique_id - self._latest_value_by_key: dict[HashableT, ValueT_co] = {} - self._task: asyncio.Task[None] = asyncio.create_task( - self._run(), name=f"LatestValueCache«{self._unique_id}»" - ) - - @property - def unique_id(self) -> str: - """The unique identifier of this instance.""" - return self._unique_id - - @override - def keys(self) -> KeysView[HashableT]: - """Return the keys for which values have been received.""" - return self._latest_value_by_key.keys() - - @override - def items(self) -> ItemsView[HashableT, ValueT_co]: - """Return an iterator over the key-value pairs of the latest values received.""" - return self._latest_value_by_key.items() - - @override - def values(self) -> ValuesView[ValueT_co]: - """Return an iterator over the latest values received.""" - return self._latest_value_by_key.values() - - @overload - def get(self, key: HashableT, default: None = None) -> ValueT_co | None: - """Return the latest value that has been received for a specific key.""" - - # MyPy passes this overload as a valid signature, but pylint does not like it. - @overload - def get( # pylint: disable=signature-differs - self, key: HashableT, default: DefaultT - ) -> ValueT_co | DefaultT: - """Return the latest value that has been received for a specific key.""" - - @override - def get( - self, key: HashableT, default: DefaultT | None = None - ) -> ValueT_co | DefaultT | None: - """Return the latest value that has been received. - - Args: - key: The key to retrieve the latest value for. - default: The default value to return if no value has been received yet for - the specified key. If not provided, it defaults to `None`. - - Returns: - The latest value that has been received. - """ - return self._latest_value_by_key.get(key, default) - - @override - def __iter__(self) -> Iterator[HashableT]: - """Return an iterator over the keys for which values have been received.""" - return iter(self._latest_value_by_key) - - @override - def __len__(self) -> int: - """Return the number of keys for which values have been received.""" - return len(self._latest_value_by_key) - - @override - def __getitem__(self, key: HashableT) -> ValueT_co: # noqa: DOC502 - """Return the latest value that has been received for a specific key. - - Args: - key: The key to retrieve the latest value for. - - Returns: - The latest value that has been received for that key. - - Raises: - KeyError: If no value has been received for `key` yet. - """ - return self._latest_value_by_key[key] - - @override - def __contains__(self, key: object, /) -> bool: - """Return whether a value has been received for a specific key. - - Args: - key: The key to check for. - - Returns: - `True` if a value has been received for that key, `False` otherwise. - """ - return key in self._latest_value_by_key - - @override - def __eq__(self, other: object, /) -> bool: - """Return whether this cache is equal to another object. - - Two caches are considered equal if they have the same keys and values. - - Args: - other: The object to compare with. - - Returns: - `True` if the caches are equal, `False` otherwise. - """ - match other: - case GroupingLatestValueCache(): - return self._latest_value_by_key == other._latest_value_by_key - case Mapping(): - return self._latest_value_by_key == other - case _: - return NotImplemented - - @override - def __ne__(self, value: object, /) -> bool: - """Return whether this cache is not equal to another object. - - Args: - value: The object to compare with. - - Returns: - `True` if the caches are not equal, `False` otherwise. - """ - return not self.__eq__(value) - - def __delitem__(self, key: HashableT) -> None: # noqa: DOC502 - """Clear the latest value for a specific key. - - Args: - key: The key for which to clear the latest value. - - Raises: - KeyError: If no value has been received for `key` yet. - """ - del self._latest_value_by_key[key] - - @overload - def pop(self, key: HashableT, /) -> ValueT_co | None: - """Remove the latest value for a specific key and return it.""" - - @overload - def pop(self, key: HashableT, /, default: DefaultT) -> ValueT_co | DefaultT: - """Remove the latest value for a specific key and return it.""" - - def pop( # noqa: DOC502 - self, key: HashableT, /, default: DefaultT | _NotSpecified = _NotSpecified() - ) -> ValueT_co | DefaultT | None: - """Remove the latest value for a specific key and return it. - - If no value has been received yet for that key, it returns the default value or - raises a [`KeyError`][] if no default value is provided. - - Args: - key: The key for which to remove the latest value. - default: The default value to return if no value has been received yet for - the specified key. - - Returns: - The latest value that has been received for that key, or the default value if - no value has been received yet and a default value is provided. - - Raises: - KeyError: If no value has been received for `key` and no `default` was provided. - """ - if isinstance(default, _NotSpecified): - return self._latest_value_by_key.pop(key) - return self._latest_value_by_key.pop(key, default) - - def popitem(self) -> tuple[HashableT, ValueT_co]: # noqa: DOC502 - """Remove and return a (key, value) pair from the cache. - - Pairs are returned in LIFO (last-in, first-out) order. - - Returns: - A tuple containing the key and the latest value that has been received for - that key. - - Raises: - KeyError: If the cache is empty. - """ - return self._latest_value_by_key.popitem() - - def clear(self) -> None: - """Clear all entries from the cache.""" - self._latest_value_by_key.clear() - - async def stop(self) -> None: - """Stop the cache.""" - if not self._task.done(): - self._task.cancel() - try: - await self._task - except asyncio.CancelledError: - pass - - def __repr__(self) -> str: - """Return a string representation of this cache.""" - return ( - f"" - ) - - async def _run(self) -> None: - async for value in self._receiver: - key = self._key(value) - self._latest_value_by_key[key] = value diff --git a/src/frequenz/channels/experimental/_optional_receiver.py b/src/frequenz/channels/experimental/_optional_receiver.py deleted file mode 100644 index c878b641..00000000 --- a/src/frequenz/channels/experimental/_optional_receiver.py +++ /dev/null @@ -1,94 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""A receiver that will wait indefinitely if there is no underlying receiver. - -The [`OptionalReceiver`][frequenz.channels.experimental.OptionalReceiver] is useful when -the underlying receiver is not set initially. Instead of making `if-else` branches to -check if the receiver is set, you can use this receiver to wait indefinitely if it is -not set. -""" - -import asyncio - -from typing_extensions import deprecated, override - -from frequenz.channels import Receiver, ReceiverError, ReceiverMessageT_co - - -@deprecated( - "frequenz.channels.experimental.OptionalReceiver is deprecated. " - "Use the receiver itself, or frequenz.channels.NopReceiver when there is none." -) -class OptionalReceiver(Receiver[ReceiverMessageT_co]): - """A receiver that will wait indefinitely if there is no underlying receiver. - - Deprecated: - Deprecated since v1.9.0. Use the receiver itself, or a - [`frequenz.channels.NopReceiver`][frequenz.channels.NopReceiver] when there - is none. - - This receiver is useful when the underlying receiver is not set initially. - Instead of making `if-else` branches to check if the receiver is set, you can use - this receiver to wait indefinitely if it is not set. - """ - - def __init__(self, receiver: Receiver[ReceiverMessageT_co] | None): - """Initialize this instance. - - Args: - receiver: The underlying receiver, or `None` if there is no receiver. - """ - self._receiver: Receiver[ReceiverMessageT_co] | None = receiver - - @override - async def ready(self) -> bool: - """Wait until the receiver is ready with a message or an error. - - Once a call to - [`ready()`][frequenz.channels.experimental.OptionalReceiver.ready] has finished, - the message should be read with a call to - [`consume()`][frequenz.channels.experimental.OptionalReceiver.consume] - ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The - receiver will remain ready (this method will return immediately) until it is - consumed. - - Returns: - Whether the receiver is still active. - """ - if self._receiver is not None: - return await self._receiver.ready() - - # If there's no receiver, wait forever - await asyncio.Event().wait() - return False - - @override - def consume(self) -> ReceiverMessageT_co: # noqa: DOC503 (raised indirectly) - """Return the latest message once the receiver is ready. - - [`ready()`][frequenz.channels.experimental.OptionalReceiver.ready] must be - called before each call to - [`consume()`][frequenz.channels.experimental.OptionalReceiver.consume]. - - Returns: - The next message received. - - Raises: - ReceiverStoppedError: If the receiver stopped producing messages. - ReceiverError: If there is some problem with the underlying receiver. - """ - if self._receiver is None: - raise ReceiverError( - "`consume()` must be preceded by a call to `ready()`", self - ) - return self._receiver.consume() - - def is_set(self) -> bool: - """Return whether the receiver is set.""" - return self._receiver is not None - - def close(self) -> None: - """Stop the receiver.""" - if self._receiver is not None: - self._receiver.close() diff --git a/src/frequenz/channels/experimental/_pipe.py b/src/frequenz/channels/experimental/_pipe.py index 3c4ceea1..331c0fbf 100644 --- a/src/frequenz/channels/experimental/_pipe.py +++ b/src/frequenz/channels/experimental/_pipe.py @@ -11,11 +11,14 @@ from __future__ import annotations import asyncio +import logging import typing from .._generic import ChannelMessageT from .._receiver import Receiver -from .._sender import Sender +from .._sender import Sender, SenderError, SenderHasNoReceiversError + +_logger = logging.getLogger(__name__) class Pipe(typing.Generic[ChannelMessageT]): @@ -25,33 +28,53 @@ class Pipe(typing.Generic[ChannelMessageT]): 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. + Example: ```python import asyncio - from contextlib import closing, aclosing, AsyncExitStack + from contextlib import closing, AsyncExitStack - from frequenz.channels import Broadcast + from frequenz.channels import BroadcastChannel from frequenz.channels.experimental import Pipe async def main() -> None: - # 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_sender, source_receiver = BroadcastChannel[int]( + name="source channel" ) - source_receiver = stack.enter_context(closing(source_channel.new_receiver())) + 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(Pipe(source_receiver, forwarding_sender)) - source_sender = source_channel.new_sender() await source_sender.send(10) assert await receiver.receive() == 10 @@ -60,16 +83,25 @@ async def main() -> None: """ def __init__( - self, receiver: Receiver[ChannelMessageT], sender: Sender[ChannelMessageT] + 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` 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]: @@ -101,5 +133,36 @@ 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: - await self._sender.send(value) + 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() diff --git a/src/frequenz/channels/experimental/_relay_sender.py b/src/frequenz/channels/experimental/_relay_sender.py deleted file mode 100644 index f4d9ba6e..00000000 --- a/src/frequenz/channels/experimental/_relay_sender.py +++ /dev/null @@ -1,77 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""A Sender for sending messages to multiple senders. - -The [`RelaySender`][frequenz.channels.experimental.RelaySender] class takes multiple -senders and forwards all the messages sent to it, to the senders it was created with. -""" - -import asyncio - -from typing_extensions import deprecated, override - -from .._generic import SenderMessageT_contra -from .._sender import Sender - - -@deprecated( - "frequenz.channels.experimental.RelaySender is deprecated and will be removed in " - "v2.0.0. Copy its code into your project if you need it, or open an issue at " - "https://github.com/frequenz-floss/frequenz-channels-python/issues if you think " - "it should stay in frequenz-channels." -) -class RelaySender(Sender[SenderMessageT_contra]): - """A [`Sender`][frequenz.channels.Sender] for sending messages to multiple senders. - - Deprecated: - Deprecated since v1.13.0, and will be removed in v2.0.0. Copy its code into - your project if you need it, or [open an - issue](https://github.com/frequenz-floss/frequenz-channels-python/issues) if - you think it should stay in this library. - - The [`RelaySender`][frequenz.channels.experimental.RelaySender] class takes multiple - senders and forwards all the messages sent to it, to the senders it was created - with. - - Example: - ```python - from frequenz.channels import Broadcast - from frequenz.channels.experimental import RelaySender - - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") - - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() - - tee_sender = RelaySender(channel1.new_sender(), channel2.new_sender()) - - await tee_sender.send(5) - assert await receiver1.receive() == 5 - assert await receiver2.receive() == 5 - ``` - """ - - def __init__(self, *senders: Sender[SenderMessageT_contra]) -> None: - """Create a new [`RelaySender`][frequenz.channels.experimental.RelaySender]. - - Args: - *senders: The senders to send messages to. - """ - self._senders = senders - - @override - async def send(self, message: SenderMessageT_contra, /) -> None: - """Send a message. - - Args: - message: The message to be sent. - """ - for sender in self._senders: - await sender.send(message) - - @override - async def aclose(self) -> None: - """Close this sender.""" - await asyncio.gather(*(sender.aclose() for sender in self._senders)) diff --git a/src/frequenz/channels/timer.py b/src/frequenz/channels/timer.py index 2ebd2dbb..0a55ce8a 100644 --- a/src/frequenz/channels/timer.py +++ b/src/frequenz/channels/timer.py @@ -21,7 +21,7 @@ import asyncio from datetime import datetime, timedelta - from frequenz.channels.timer import MonotonicTimer + from frequenz.channels.timer import MonotonicTimer, TriggerAllMissed async def main() -> None: @@ -46,13 +46,12 @@ async def main() -> None: import asyncio from datetime import timedelta - from frequenz.channels import Anycast, select, selected_from - from frequenz.channels.timer import MonotonicTimer + from frequenz.channels import BroadcastChannel, select, selected_from + from frequenz.channels.timer import MonotonicTimer, SkipMissedAndDrift async def main() -> None: - channel = Anycast[int](name="data-channel") - data_receiver = channel.new_receiver() + sender, data_receiver = BroadcastChannel[int](name="data-channel") timer = MonotonicTimer(timedelta(seconds=1.0), SkipMissedAndDrift()) @@ -101,9 +100,7 @@ async def main() -> None: import abc import asyncio from datetime import timedelta -from typing import TYPE_CHECKING, TypeAlias -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases from typing_extensions import override from ._receiver import Receiver, ReceiverStoppedError @@ -113,7 +110,6 @@ async def main() -> None: "MonotonicTimer", "SkipMissedAndDrift", "SkipMissedAndResync", - "Timer", "TriggerAllMissed", ] @@ -814,28 +810,3 @@ def __repr__(self) -> str: f"{type(self).__name__}<{self.interval=}, {self.missed_tick_policy=}, " f"{self.loop=}, {self.is_running=}>" ) - - -if TYPE_CHECKING: - Timer: TypeAlias = MonotonicTimer - """A receiver that sends a message regularly. - - Deprecated: - Deprecated since v1.13.0. Use - [`MonotonicTimer`][frequenz.channels.timer.MonotonicTimer] instead. - - The name `Timer` will be used for a wall clock timer in a later version. - """ -else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "Timer", - new_name="MonotonicTimer", - since="v1.13.0", - message=( - "{old} is deprecated. Use {new} instead. The name Timer will be " - "used for a wall clock timer in a later version." - ), - ), - ) diff --git a/tests/experimental/test_deprecated_aliases.py b/tests/experimental/test_deprecated_aliases.py deleted file mode 100644 index 077e51cd..00000000 --- a/tests/experimental/test_deprecated_aliases.py +++ /dev/null @@ -1,30 +0,0 @@ -# License: MIT -# Copyright © 2026 Frequenz Energy-as-a-Service GmbH - -"""Tests for the deprecated aliases of symbols promoted out of `experimental`.""" - -import pytest -from frequenz.core.warnings import asserting_no_deprecations - -import frequenz.channels -from frequenz.channels import experimental - -_PROMOTED = ["NopReceiver", "WithPrevious"] - - -@pytest.mark.parametrize("name", _PROMOTED) -def test_old_name_warns(name: str) -> None: - """Ensure the old `experimental` name warns and is the very same object.""" - with pytest.deprecated_call( - match=rf"^frequenz\.channels\.experimental\.{name} is deprecated\. " - rf"Use frequenz\.channels\.{name} instead\.$" - ): - old = getattr(experimental, name) - assert old is getattr(frequenz.channels, name) - - -@pytest.mark.parametrize("name", _PROMOTED) -def test_new_name_does_not_warn(name: str) -> None: - """Ensure the new top-level name doesn't warn.""" - with asserting_no_deprecations(): - _ = getattr(frequenz.channels, name) diff --git a/tests/experimental/test_optional_receiver.py b/tests/experimental/test_optional_receiver.py deleted file mode 100644 index 82f1e967..00000000 --- a/tests/experimental/test_optional_receiver.py +++ /dev/null @@ -1,80 +0,0 @@ -# License: MIT -# Copyright © 2025 Frequenz Energy-as-a-Service GmbH - -"""Tests for the OptionalReceiver class.""" - -import asyncio -from contextlib import aclosing, closing - -import pytest - -from frequenz.channels import Broadcast, ReceiverError, ReceiverStoppedError -from frequenz.channels.experimental import OptionalReceiver - -# Every test here uses the deprecated OptionalReceiver on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") - - -async def test_receiver_with_none_does_not_end() -> None: - """Test that the receiver with None does not end.""" - with closing(OptionalReceiver[int](None)) as receiver: - assert not receiver.is_set() - - with pytest.raises(TimeoutError): - await asyncio.wait_for(receiver.ready(), timeout=0.3) - - -async def test_receiver_with_none_raises_error_when_consuming() -> None: - """Test that the receiver with None raises an error when consuming.""" - with closing(OptionalReceiver[int](None)) as receiver: - assert not receiver.is_set() - - with pytest.raises(ReceiverError): - receiver.consume() - - -async def test_receiver_with_underlying_receiver_forwards_messages() -> None: - """Test that the receiver forwards messages.""" - async with aclosing(Broadcast[int](name="test")) as channel: - with closing(OptionalReceiver[int](channel.new_receiver())) as receiver: - assert receiver.is_set() - - sender = channel.new_sender() - - await sender.send(5) - value = await asyncio.wait_for(receiver.receive(), timeout=0.1) - assert value == 5 - - await sender.send(100) - value = await asyncio.wait_for(receiver.receive(), timeout=0.1) - assert value == 100 - - -async def test_receiver_ends_when_underlying_receiver_ends() -> None: - """Test that the receiver ends when the underlying receiver ends.""" - async with aclosing(Broadcast[int](name="test")) as channel: - with ( - closing(channel.new_receiver()) as receiver, - closing(OptionalReceiver[int](receiver)) as optional_receiver, - ): - assert optional_receiver.is_set() - - receiver.close() - # First check if ready method returns False - is_active = await optional_receiver.ready() - assert is_active is False - - # Then check if `receive` method raises ReceiverStoppedError - with pytest.raises(ReceiverStoppedError): - await optional_receiver.receive() - - -def test_deprecation_warning() -> None: - """Test that the receiver warns it is deprecated.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.OptionalReceiver is deprecated\. " - r"Use the receiver itself, or frequenz\.channels\.NopReceiver when there is " - r"none\.$" - ): - receiver = OptionalReceiver[int](None) - receiver.close() diff --git a/tests/experimental/test_pipe.py b/tests/experimental/test_pipe.py index f0158e14..494c1ff7 100644 --- a/tests/experimental/test_pipe.py +++ b/tests/experimental/test_pipe.py @@ -4,14 +4,28 @@ """Tests for the Pipe class.""" import asyncio +import logging import typing from contextlib import AsyncExitStack, aclosing, closing -from frequenz.channels import Broadcast, Receiver +import pytest + +from frequenz.channels import ( + Broadcast, + BroadcastChannel, + Receiver, + Sender, + SenderClosedError, + SenderError, + SenderHasNoReceiversError, +) from frequenz.channels.experimental import Pipe T = typing.TypeVar("T") +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + class Timeout: """Sentinel for timeout.""" @@ -25,6 +39,13 @@ async def receive_timeout(recv: Receiver[T], timeout: float = 0.1) -> T | type[T 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) + + async def test_pipe() -> None: """Test pipe.""" channel1: Broadcast[int] = Broadcast(name="channel1") @@ -79,3 +100,245 @@ async def test_pipe_with_async_exit_stack() -> None: 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.""" + 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 + ) + 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 + + +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`.""" + + 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 + + +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_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_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() + + 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) + + +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") + + +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 diff --git a/tests/experimental/test_relay_sender.py b/tests/experimental/test_relay_sender.py deleted file mode 100644 index fa008966..00000000 --- a/tests/experimental/test_relay_sender.py +++ /dev/null @@ -1,49 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""Tests for the RelaySender class.""" - -import pytest - -from frequenz.channels import Broadcast -from frequenz.channels.experimental import RelaySender - - -async def test_tee_sender() -> None: - """Test tee sender.""" - channel1: Broadcast[int] = Broadcast(name="channel1") - channel2: Broadcast[int] = Broadcast(name="channel2") - channel3: Broadcast[int] = Broadcast(name="channel3") - - with pytest.deprecated_call(): - sender = RelaySender( - channel1.new_sender(), channel2.new_sender(), channel3.new_sender() - ) - receiver1 = channel1.new_receiver() - receiver2 = channel2.new_receiver() - receiver3 = channel3.new_receiver() - - await sender.send(42) - assert ( - await receiver1.receive() - == await receiver2.receive() - == await receiver3.receive() - == 42 - ) - - await sender.send(-2) - assert ( - await receiver1.receive() - == await receiver2.receive() - == await receiver3.receive() - == -2 - ) - - -def test_relay_sender_is_deprecated() -> None: - """Test that creating a RelaySender warns.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.RelaySender is deprecated and " - r"will be removed in v2\.0\.0\. Copy its code into your project" - ): - RelaySender() diff --git a/tests/test_anycast.py b/tests/test_anycast.py deleted file mode 100644 index 10f758bf..00000000 --- a/tests/test_anycast.py +++ /dev/null @@ -1,259 +0,0 @@ -# License: MIT -# Copyright © 2022 Frequenz Energy-as-a-Service GmbH - -"""Tests for the Channel implementation.""" - -import asyncio - -import pytest - -from frequenz.channels import ( - Anycast, - ChannelClosedError, - Receiver, - ReceiverStoppedError, - Sender, - SenderError, -) - -# Every test here uses the deprecated Anycast on purpose. -pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") - - -def test_deprecation_warning() -> None: - """Test that Anycast warns it is deprecated.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.Anycast is deprecated and will be removed in a " - r"future version\. Copy its code into your project if you need it, or open an " - r"issue at https://github\.com/frequenz-floss/frequenz-channels-python/issues " - r"if you think it should stay in frequenz-channels\.$" - ): - _ = Anycast[int](name="test") - - -async def test_anycast() -> None: - """Ensure sent messages are received by one receiver.""" - acast: Anycast[int] = Anycast(name="test") - - num_receivers = 5 - num_senders = 5 - expected_sum = num_senders * num_receivers * (num_receivers + 1) / 2 - - # a list of `num_receivers` elements, where each element with get - # incremented by values the corresponding receiver receives. Once the run - # finishes, we will check if their sum equals `expected_sum`. - recv_trackers = [0] * num_receivers - - async def send_msg(chan: Sender[int]) -> None: - # send one message for each receiver - for ctr in range(num_receivers): - await chan.send(ctr + 1) - - async def update_tracker_on_receive(receiver_id: int, recv: Receiver[int]) -> None: - while True: - try: - msg = await recv.receive() - except ReceiverStoppedError as err: - assert err.receiver is recv - assert isinstance(err.__cause__, ChannelClosedError) - return - recv_trackers[receiver_id] += msg - # without the sleep, decommissioning receivers temporarily, all - # messages go to the first receiver. - await asyncio.sleep(0) - - receivers = [] - for ctr in range(num_receivers): - receivers.append(update_tracker_on_receive(ctr, acast.new_receiver())) - - # get one more sender and receiver to test channel operations after the - # channel is closed. - after_close_receiver = acast.new_receiver() - after_close_sender = acast.new_sender() - - receivers_runs = asyncio.gather(*receivers) - senders = [] - for ctr in range(num_senders): - senders.append(send_msg(acast.new_sender())) - - await asyncio.gather(*senders) - await acast.aclose() - await receivers_runs - - with pytest.raises(SenderError): - await after_close_sender.send(5) - with pytest.raises(ReceiverStoppedError) as excinfo: - await after_close_receiver.receive() - assert excinfo.value.receiver is after_close_receiver - assert isinstance(excinfo.value.__cause__, ChannelClosedError) - assert excinfo.value.__cause__.channel is acast - - actual_sum = 0 - for ctr in recv_trackers: - # ensure all receivers have got messages - assert ctr > 0 - actual_sum += ctr - assert actual_sum == expected_sum - - -async def test_anycast_after_close() -> None: - """Ensure closed channels can't get new messages.""" - acast: Anycast[int] = Anycast(name="test") - - receiver = acast.new_receiver() - sender = acast.new_sender() - - await sender.send(2) - - await acast.aclose() - - with pytest.raises(SenderError): - await sender.send(5) - - assert await receiver.receive() == 2 - with pytest.raises(ReceiverStoppedError): - await receiver.receive() - - -async def test_anycast_full() -> None: - """Ensure send calls to a full channel are blocked.""" - buffer_size = 10 - timeout = 0.2 - acast: Anycast[int] = Anycast(name="test", limit=buffer_size) - - receiver = acast.new_receiver() - sender = acast.new_sender() - - timeout_at = 0 - for ctr in range(buffer_size + 1): - try: - await asyncio.wait_for(sender.send(ctr), timeout) - except asyncio.TimeoutError: - # expect timeout once the buffer is full - timeout_at = ctr - - assert timeout_at == buffer_size - - timeout_at = 0 - for ctr in range(buffer_size + 1): - try: - msg = await asyncio.wait_for(receiver.receive(), timeout) - assert ctr == msg - except asyncio.TimeoutError: - # expect timeout once the buffer is empty - timeout_at = ctr - - assert timeout_at == buffer_size - - try: - await asyncio.wait_for(sender.send(100), timeout) - except asyncio.TimeoutError: - # should not timeout now, because we've just drained the channel - assert False - - try: - msg = await asyncio.wait_for(receiver.receive(), timeout) - assert msg == 100 - except asyncio.TimeoutError: - # should not timeout now, because we've just sent a message to the - # channel. - assert False - - -async def test_anycast_none_messages() -> None: - """Ensure None messages can be sent and received.""" - acast: Anycast[int | None] = Anycast(name="test") - - sender = acast.new_sender() - receiver = acast.new_receiver() - - await sender.send(5) - assert await receiver.receive() == 5 - - await sender.send(None) - assert await receiver.receive() is None - - await sender.send(10) - assert await receiver.receive() == 10 - - -async def test_anycast_async_iterator() -> None: - """Check that the anycast receiver works as an async iterator.""" - acast: Anycast[str] = Anycast(name="test") - - sender = acast.new_sender() - receiver = acast.new_receiver() - - async def send_messages() -> None: - for val in ["one", "two", "three", "four", "five"]: - await sender.send(val) - await acast.aclose() - - sender_task = asyncio.create_task(send_messages()) - - received = [] - async for recv in receiver: - received.append(recv) - - assert received == ["one", "two", "three", "four", "five"] - - await sender_task - - -async def test_anycast_map() -> None: - """Ensure map runs on all incoming messages.""" - chan: Anycast[int] = Anycast(name="test") - sender = chan.new_sender() - - # transform int receiver into bool receiver. - receiver: Receiver[bool] = chan.new_receiver().map(lambda num: num > 10) - - await sender.send(8) - await sender.send(12) - - assert (await receiver.receive()) is False - assert (await receiver.receive()) is True - - -async def test_anycast_filter() -> None: - """Ensure filter keeps only the messages that pass the filter.""" - chan = Anycast[int](name="input-chan") - sender = chan.new_sender() - - # filter out all numbers less than 10. - receiver: Receiver[int] = chan.new_receiver().filter(lambda num: num > 10) - - await sender.send(8) - await sender.send(12) - await sender.send(5) - await sender.send(15) - - assert (await receiver.receive()) == 12 - assert (await receiver.receive()) == 15 - - -async def test_anycast_close_receiver() -> None: - """Ensure closing a receiver stops the receiver.""" - chan = Anycast[int](name="input-chan") - sender = chan.new_sender() - - receiver_1 = chan.new_receiver() - receiver_2 = chan.new_receiver() - - await sender.send(1) - - assert (await receiver_1.receive()) == 1 - - receiver_1.close() - - await sender.send(2) - - with pytest.raises(ReceiverStoppedError): - _ = await receiver_1.receive() - - assert (await receiver_2.receive()) == 2 - - receiver_2.close() - - with pytest.raises(ReceiverStoppedError): - _ = await receiver_2.receive() diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py index e94f3971..adf58975 100644 --- a/tests/test_broadcast.py +++ b/tests/test_broadcast.py @@ -4,6 +4,9 @@ """Tests for the Broadcast implementation.""" import asyncio +import gc +import re +import warnings from dataclasses import dataclass from typing import TypeGuard, assert_never @@ -17,9 +20,26 @@ Receiver, ReceiverStoppedError, Sender, + SenderClosedError, SenderError, + SenderHasNoReceiversError, + TransientSenderError, + select, + selected_from, ) +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + + +def test_broadcast_is_deprecated() -> None: + """Ensure `Broadcast` warns it is deprecated, and what to use instead.""" + with pytest.deprecated_call( + match=r"^frequenz\.channels\.Broadcast is deprecated\. " + r"Use frequenz\.channels\.BroadcastChannel instead\.$" + ): + _ = Broadcast[int](name="deprecation-test") + async def test_broadcast() -> None: """Ensure sent messages are received by all receivers.""" @@ -428,14 +448,126 @@ async def test_broadcast_close_receiver() -> None: _ = await receiver_2.receive() +async def test_broadcast_close_receiver_while_waiting() -> None: + """Ensure closing a receiver wakes up a task waiting on it.""" + chan = Broadcast[int](name="input-chan") + receiver = chan.new_receiver() + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + assert not waiter.done() + + receiver.close() + + assert await asyncio.wait_for(waiter, timeout=1.0) is False + + +async def test_broadcast_closed_receiver_drops_buffered_messages() -> None: + """Ensure closing a receiver drops its buffered messages and stops `select()`.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + filtered = chan.new_receiver().filter(lambda _: True) + await sender.send(1) + receiver.close() + filtered.close() + + assert len(receiver) == 0 + assert not await receiver.ready() + + async def stopped(recv: Receiver[int]) -> list[bool]: + return [ + selected.was_stopped + async for selected in select(recv) + if selected_from(selected, recv) + ] + + assert await asyncio.wait_for(stopped(receiver), timeout=1.0) == [True] + assert await asyncio.wait_for(stopped(filtered), timeout=1.0) == [True] + + +async def test_broadcast_receiver_closed_while_waking() -> None: + """Ensure a receiver closed while it wakes up isn't reported as ready.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + await sender.send(1) + receiver.close() + + assert await asyncio.wait_for(waiter, timeout=1.0) is False + + +def _leave_waiter_on_closed_loop(receiver: Receiver[int]) -> None: + """Leave a task waiting on the receiver in an event loop that is then closed.""" + + async def wait() -> None: + asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + + # The loop is closed without cancelling the waiting task. + loop = asyncio.new_event_loop() + try: + loop.run_until_complete(wait()) + finally: + loop.close() + + +def test_broadcast_wake_after_loop_closed() -> None: + """Ensure waking receivers works after a waiting receiver's loop closed.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + receiver = chan.new_receiver() + receiver_2 = chan.new_receiver() + + _leave_waiter_on_closed_loop(receiver) + receiver_2.close() + with pytest.raises(ReceiverStoppedError): + receiver_2.consume() + + _leave_waiter_on_closed_loop(receiver) + asyncio.run(sender.send(1)) + assert receiver.consume() == 1 + + _leave_waiter_on_closed_loop(receiver) + asyncio.run(chan.aclose()) + assert chan.is_closed + # pylint: disable-next=protected-access + assert chan._wakeup_loop is None + + +def test_broadcast_wake_from_other_thread_in_debug_mode() -> None: + """Ensure a wake-up from another thread still fails in debug mode.""" + + async def close_in_thread() -> None: + chan = Broadcast[int](name="input-chan") + receiver = chan.new_receiver() + receiver_2 = chan.new_receiver() + asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + with pytest.raises(RuntimeError, match="Non-thread-safe operation"): + await asyncio.to_thread(receiver_2.close) + + # The failed wake-up leaves the waiting task stuck, so this loop is closed + # without cancelling it. + loop = asyncio.new_event_loop() + loop.set_debug(True) + try: + loop.run_until_complete(close_in_thread()) + finally: + loop.close() + + async def test_broadcast_channel_does_not_warn() -> None: """Ensure creating a `BroadcastChannel` doesn't emit deprecation warnings.""" with asserting_no_deprecations(): _ = BroadcastChannel[int](name="no-deprecations-test") -async def test_broadcast_auto_close_1() -> None: - """Ensure broadcast auto close works when all receivers are closed.""" +async def test_broadcast_no_receivers_after_all_receivers_closed() -> None: + """Ensure sending fails once all receivers are closed.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") receiver_2 = sender.subscribe() @@ -453,12 +585,17 @@ async def test_broadcast_auto_close_1() -> None: receiver_2.close() - with pytest.raises(SenderError) as excinfo: + with pytest.raises( + SenderError, + match=f"^Sender {re.escape(str(sender))} has no receivers$", + ) as excinfo: await sender.send(3) - assert isinstance(excinfo.value.__cause__, ChannelClosedError) + assert isinstance(excinfo.value, SenderHasNoReceiversError) + assert isinstance(excinfo.value, TransientSenderError) + assert excinfo.value.__cause__ is None -async def test_broadcast_auto_close_2() -> None: +async def test_broadcast_auto_close_on_all_senders_closed() -> None: """Ensure broadcast auto close works when all senders are closed.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") @@ -481,11 +618,110 @@ async def test_broadcast_auto_close_2() -> None: assert isinstance(excinfo.value.__cause__, ChannelClosedError) -async def test_broadcast_closed_channels_remain_closed() -> None: - """Ensure that a closed channel can't be resurrected.""" +async def test_broadcast_subscribe_after_last_receiver_closed() -> None: + """Ensure a channel without receivers can get new ones after a failed send.""" sender, receiver = BroadcastChannel[int](name="auto-close-test") receiver.close() + with pytest.raises(SenderHasNoReceiversError): + await sender.send(0) + + receiver_2 = sender.subscribe() + await sender.send(1) + assert await receiver_2.receive() == 1 + + +async def test_broadcast_no_receivers_after_last_receiver_dropped() -> None: + """Ensure sending fails once the last receiver is garbage-collected.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + + del receiver + gc.collect() + + with pytest.raises(SenderHasNoReceiversError): + await sender.send(1) + + +async def test_broadcast_no_auto_close_send_without_receivers() -> None: + """Ensure a non-auto-closing `Broadcast` keeps a message sent without receivers. + + With `resend_latest=True`, a receiver created later gets it. + """ + chan = Broadcast[int](name="no-auto-close-test", resend_latest=True) + sender = chan.new_sender() + + await sender.send(1) + + receiver = chan.new_receiver() + assert await asyncio.wait_for(receiver.receive(), timeout=1.0) == 1 + + +async def test_broadcast_send_without_receivers_resent() -> None: + """Ensure a message sent without receivers is resent to new receivers.""" + sender, receiver = BroadcastChannel[int](name="resend-test", resend_latest=True) + await sender.send(1) + receiver.close() + + with pytest.raises(SenderHasNoReceiversError): + await sender.send(2) + + receiver_2 = sender.subscribe() + assert await asyncio.wait_for(receiver_2.receive(), timeout=1.0) == 2 + + +async def test_broadcast_no_receivers_deprecated_auto_close() -> None: + """Ensure an auto-closing `Broadcast` stays open when sending without receivers.""" + chan = Broadcast[int](name="auto-close-test", auto_close=True) + sender = chan.new_sender() + + with pytest.raises(SenderHasNoReceiversError): + await sender.send(1) + assert not chan.is_closed + + +async def test_broadcast_last_sender_aclose_wakes_receivers() -> None: + """Ensure closing the last sender wakes up a waiting receiver at once.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + + waiter = asyncio.create_task(receiver.ready()) + await asyncio.sleep(0) + assert not waiter.done() + + await sender.aclose() + await asyncio.sleep(0) + + assert waiter.done() + assert waiter.result() is False + + +async def test_broadcast_unclosed_sender_keeps_channel_open() -> None: + """Ensure a garbage-collected sender that wasn't closed keeps the channel open.""" + sender, receiver = BroadcastChannel[int](name="auto-close-test") + sender_2 = sender.clone() + + del sender + gc.collect() + await sender_2.aclose() + + assert receiver.has_senders + + +async def test_broadcast_auto_close_without_senders() -> None: + """Ensure an auto-closing `Broadcast` without senders closes when received from.""" + chan = Broadcast[int](name="auto-close-test", auto_close=True) + receiver = chan.new_receiver() + assert not chan.is_closed + + assert not await asyncio.wait_for(receiver.ready(), timeout=1.0) + assert chan.is_closed + + +async def test_broadcast_closed_channels_remain_closed() -> None: + """Ensure that a closed channel can't be resurrected.""" + chan = Broadcast[int](name="closed-test") + sender = chan.new_sender() + + await chan.aclose() with pytest.raises(SenderError) as excinfo: await sender.send(1) @@ -494,3 +730,160 @@ async def test_broadcast_closed_channels_remain_closed() -> None: with pytest.raises(SenderError) as excinfo: _ = sender.subscribe() assert isinstance(excinfo.value.__cause__, ChannelClosedError) + + with pytest.raises(SenderError) as excinfo: + _ = sender.clone() + assert isinstance(excinfo.value.__cause__, ChannelClosedError) + + +async def test_broadcast_closed_sender() -> None: + """Ensure a closed sender can't be used to send, clone or subscribe.""" + sender, _receiver = BroadcastChannel[int](name="closed-sender-test") + sender_2 = sender.clone() + await sender.aclose() + assert sender_2.sender_count == 1 + + with pytest.raises(SenderClosedError): + await sender.send(1) + with pytest.raises(SenderClosedError): + _ = sender.clone() + with pytest.raises(SenderClosedError): + _ = sender.subscribe() + + +async def test_broadcast_subscribe_default_options( + caplog: pytest.LogCaptureFixture, +) -> None: + """Ensure receivers subscribed to a `Broadcast` use the default options.""" + chan = Broadcast[int](name="subscribe-defaults-test") + sender = chan.new_sender() + receiver = sender.subscribe() + + with caplog.at_level("WARNING", logger="frequenz.channels._broadcast"): + for i in range(51): + await sender.send(i) + + assert len(receiver) == 50 + assert "is full. Oldest message was dropped." in caplog.text + + silent = sender.subscribe(warn_on_overflow=False) + assert not silent._warn_on_overflow # pylint: disable=protected-access + + +async def test_broadcast_subscribe_inherits_receiver_options() -> None: + """Ensure subscribed receivers default to the channel's receiver options.""" + sender, receiver = BroadcastChannel[int]( + name="options-test", buffer_size=2, warn_on_overflow=False + ) + subscribed = sender.subscribe() + overridden = sender.subscribe(buffer_size=3, warn_on_overflow=True) + + for i in range(4): + await sender.send(i) + + assert [len(receiver), len(subscribed), len(overridden)] == [2, 2, 3] + # pylint: disable=protected-access + assert not receiver._warn_on_overflow + assert not subscribed._warn_on_overflow + assert overridden._warn_on_overflow + # pylint: enable=protected-access + + +async def test_broadcast_has_receivers() -> None: + """Ensure senders report whether their channel has receivers.""" + sender, receiver = BroadcastChannel[int](name="has-receivers-test") + receiver_2 = sender.subscribe() + assert sender.has_receivers + + receiver.close() + assert sender.has_receivers + + receiver_2.close() + assert not sender.has_receivers + + +async def test_broadcast_has_receivers_after_last_receiver_dropped() -> None: + """Ensure `has_receivers` doesn't count garbage-collected receivers.""" + sender, receiver = BroadcastChannel[int](name="has-receivers-test") + + del receiver + gc.collect() + + assert not sender.has_receivers + + +async def test_broadcast_has_senders() -> None: + """Ensure receivers report whether their channel has senders.""" + sender, receiver = BroadcastChannel[int](name="has-senders-test") + sender_2 = sender.clone() + assert receiver.has_senders + + await sender.aclose() + assert receiver.has_senders + + await sender_2.send(1) + await sender_2.aclose() + assert not receiver.has_senders + assert await receiver.receive() == 1 + + +async def test_broadcast_closed_endpoints_still_report_other_side() -> None: + """Ensure `has_receivers` and `has_senders` ignore the endpoint's own state.""" + sender, receiver = BroadcastChannel[int](name="has-closed-test") + sender_2 = sender.clone() + receiver_2 = sender.subscribe() + + await sender.aclose() + receiver.close() + + assert sender.has_receivers and sender_2.has_receivers + assert receiver.has_senders and receiver_2.has_senders + + +async def test_broadcast_has_receivers_and_senders_no_auto_close() -> None: + """Ensure non-auto-closing channels report their senders and receivers.""" + chan = Broadcast[int](name="input-chan") + sender = chan.new_sender() + assert not sender.has_receivers + + receiver = chan.new_receiver() + assert sender.has_receivers + assert receiver.has_senders + + await sender.aclose() + assert not receiver.has_senders + + sender_2 = chan.new_sender() + assert receiver.has_senders + + await chan.aclose() + assert not receiver.has_senders + assert not sender_2.has_receivers + + +async def test_broadcast_channel_str() -> None: + """Ensure BroadcastChannel endpoints are named like Broadcast ones.""" + sender, receiver = BroadcastChannel[int](name="str-test") + + assert str(sender) == "Broadcast:str-test:BroadcastSender" + assert str(receiver) == "Broadcast:str-test:BroadcastReceiver:str-test_receiver" + assert repr(sender).startswith("BroadcastSender(Broadcast(name='str-test'") + + +async def test_broadcast_channel_closed_error_holds_broadcast() -> None: + """Ensure a closed `BroadcastChannel` reports a `Broadcast` in its error.""" + sender, receiver = BroadcastChannel[int](name="closed-error-test") + await sender.aclose() + + with pytest.raises(ReceiverStoppedError) as excinfo: + await receiver.receive() + + assert isinstance(excinfo.value.__cause__, ChannelClosedError) + assert isinstance(excinfo.value.__cause__.channel, Broadcast) + + +async def test_broadcast_channel_not_deprecated() -> None: + """Ensure creating a BroadcastChannel doesn't emit deprecation warnings.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + _ = BroadcastChannel[int](name="no-warnings-test") diff --git a/tests/test_broadcast_buffer_size.py b/tests/test_broadcast_buffer_size.py index d79e0972..65e7f9b0 100644 --- a/tests/test_broadcast_buffer_size.py +++ b/tests/test_broadcast_buffer_size.py @@ -3,12 +3,10 @@ """Tests for the `buffer_size` argument of broadcast channels.""" -from typing import get_overloads - import pytest from frequenz.core.warnings import asserting_no_deprecations -from frequenz.channels import BroadcastChannel, BroadcastReceiver, BroadcastSender +from frequenz.channels import BroadcastChannel, BroadcastReceiver def _drain(receiver: BroadcastReceiver[int]) -> list[int]: @@ -54,103 +52,53 @@ async def test_default_buffer_size() -> None: assert _drain(receiver_2) == list(range(10, 60)) -async def test_buffer_size_is_keyword_only() -> None: - """Ensure `buffer_size` can't be passed by position.""" +async def test_options_are_keyword_only() -> None: + """Ensure every option but the name has to be passed by keyword.""" sender, _receiver = BroadcastChannel[int](name="test") with pytest.raises(TypeError): # We want to test the runtime error. # pylint: disable-next=too-many-function-args - BroadcastChannel[int]("test", False, 5, True, 7) # type: ignore[call-overload] + BroadcastChannel[int]("test", False) # type: ignore[call-arg] with pytest.raises(TypeError): # We want to test the runtime error. - sender.subscribe("test", 5, True, 7) # type: ignore[call-overload] - - -@pytest.mark.parametrize("buffer_size", [0, -1]) -async def test_buffer_size_must_be_positive(buffer_size: int) -> None: - """Ensure the error of a buffer smaller than 1 names `buffer_size`.""" - with pytest.raises(ValueError, match="buffer_size must be at least 1"): - _ = BroadcastChannel[int](name="test", buffer_size=buffer_size) - - sender, _receiver = BroadcastChannel[int](name="test") - with pytest.raises(ValueError, match="buffer_size must be at least 1"): - _ = sender.subscribe(buffer_size=buffer_size) - - -async def test_limit_and_buffer_size_conflict() -> None: - """Ensure passing both `limit` and `buffer_size` raises a `TypeError`.""" - with pytest.raises(TypeError, match="both `limit` and `buffer_size`"): - # We want to test the runtime error. - BroadcastChannel[int](name="test", limit=2, buffer_size=2) # type: ignore[call-overload] - - sender, _receiver = BroadcastChannel[int](name="test") - with pytest.raises(TypeError, match="both `limit` and `buffer_size`"): + sender.subscribe("test", 5) # type: ignore[call-arg] + with pytest.raises(TypeError): # We want to test the runtime error. - sender.subscribe(limit=2, buffer_size=2) # type: ignore[call-overload] + sender.subscribe("test", None, True) # type: ignore[call-arg] -async def test_limit_keyword_is_deprecated() -> None: - """Ensure passing `limit` by keyword warns, but still sets the buffer size.""" - with pytest.deprecated_call( - match=r"^The argument limit in frequenz\.channels\.BroadcastChannel is deprecated\b" - ) as warnings_record: - sender, receiver_1 = BroadcastChannel[int]( - name="test", limit=2, warn_on_overflow=False - ) - assert warnings_record[0].filename == __file__ - - with pytest.deprecated_call( - match=( - r"^The argument limit in frequenz\.channels\.BroadcastSender\.subscribe " - r"is deprecated\b" - ) - ) as warnings_record: - receiver_2 = sender.subscribe(limit=3, warn_on_overflow=False) - assert warnings_record[0].filename == __file__ +async def test_subscribe_none_uses_the_channel_options() -> None: + """Ensure passing `None` to `subscribe()` is the same as not passing it.""" + sender, _receiver = BroadcastChannel[int]( + name="test", buffer_size=2, warn_on_overflow=False + ) + receiver = sender.subscribe(buffer_size=None, warn_on_overflow=None) for message in range(5): await sender.send(message) - assert _drain(receiver_1) == [3, 4] - assert _drain(receiver_2) == [2, 3, 4] - - -async def test_limit_position_is_deprecated() -> None: - """Ensure passing `limit` by position warns, but still sets the buffer size.""" - with pytest.deprecated_call( - match=r"^The argument limit in frequenz\.channels\.BroadcastChannel is deprecated\b" - ) as warnings_record: - sender, receiver_1 = BroadcastChannel[int]("test", False, 2, False) - assert warnings_record[0].filename == __file__ + assert _drain(receiver) == [3, 4] + assert not receiver._warn_on_overflow # pylint: disable=protected-access - with pytest.deprecated_call( - match=( - r"^The argument limit in frequenz\.channels\.BroadcastSender\.subscribe " - r"is deprecated\b" - ) - ) as warnings_record: - receiver_2 = sender.subscribe("test", 3, False) - assert warnings_record[0].filename == __file__ - for message in range(5): - await sender.send(message) +async def test_receiver_repr_shows_buffer_size() -> None: + """Ensure the receiver's `repr()` shows its buffer size as `buffer_size`.""" + _sender, receiver = BroadcastChannel[int](name="test", buffer_size=2) - assert _drain(receiver_1) == [3, 4] - assert _drain(receiver_2) == [2, 3, 4] + assert "buffer_size=2" in repr(receiver) + assert "limit" not in repr(receiver) -@pytest.mark.parametrize("limit", [0, -1]) -async def test_limit_must_be_positive(limit: int) -> None: - """Ensure the error of a deprecated `limit` smaller than 1 names `limit`.""" - with pytest.deprecated_call(): - with pytest.raises(ValueError, match="limit must be at least 1"): - _ = BroadcastChannel[int](name="test", limit=limit) +@pytest.mark.parametrize("buffer_size", [0, -1]) +async def test_buffer_size_must_be_positive(buffer_size: int) -> None: + """Ensure the error of a buffer smaller than 1 names `buffer_size`.""" + with pytest.raises(ValueError, match="buffer_size must be at least 1"): + _ = BroadcastChannel[int](name="test", buffer_size=buffer_size) sender, _receiver = BroadcastChannel[int](name="test") - with pytest.deprecated_call(): - with pytest.raises(ValueError, match="limit must be at least 1"): - _ = sender.subscribe(limit=limit) + with pytest.raises(ValueError, match="buffer_size must be at least 1"): + _ = sender.subscribe(buffer_size=buffer_size) async def test_buffer_size_is_not_deprecated() -> None: @@ -162,31 +110,4 @@ async def test_buffer_size_is_not_deprecated() -> None: _ = sender.subscribe(buffer_size=2, warn_on_overflow=False) _ = sender.subscribe() _ = sender.subscribe("name") - _ = BroadcastChannel[int]("name", True) - - -async def test_limit_and_buffer_size_conflict_does_not_warn() -> None: - """Ensure the error for passing both arguments comes without a warning.""" - with asserting_no_deprecations(): - with pytest.raises(TypeError): - # We want to test the runtime error. - BroadcastChannel[int]( # type: ignore[call-overload] - name="test", limit=2, buffer_size=2 - ) - - -def test_deprecated_overloads_have_the_runtime_message() -> None: - """Ensure `mypy` and the runtime report the same message for `limit`.""" - for function, name in ( - (BroadcastChannel.__new__, "BroadcastChannel"), - (BroadcastSender.subscribe, "BroadcastSender.subscribe"), - ): - deprecated_overloads = [ - message - for overload in get_overloads(function) - if (message := getattr(overload, "__deprecated__", None)) is not None - ] - assert deprecated_overloads == [ - f"The argument limit in frequenz.channels.{name} is deprecated and will " - "be removed in v2.0.0. Use buffer_size instead." - ] + _ = BroadcastChannel[int]("name", resend_latest=True) diff --git a/tests/test_grouping_latest_value_cache_integration.py b/tests/test_grouping_latest_value_cache_integration.py deleted file mode 100644 index 10d44fa3..00000000 --- a/tests/test_grouping_latest_value_cache_integration.py +++ /dev/null @@ -1,156 +0,0 @@ -# License: MIT -# Copyright © 2024 Frequenz Energy-as-a-Service GmbH - -"""Tests for the LatestValueCache implementation.""" - -import asyncio -import importlib - -import pytest - -from frequenz.channels import Broadcast -from frequenz.channels.experimental import GroupingLatestValueCache - - -@pytest.mark.integration -async def test_latest_value_cache_key() -> None: # pylint: disable=too-many-statements - """Ensure LatestValueCache works with keys.""" - channel = Broadcast[tuple[int, str]](name="lvc_test") - - with pytest.deprecated_call(): - cache: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - sender = channel.new_sender() - - assert 5 not in cache - assert cache.get(0) is None - - assert cache.keys() == set() - - await sender.send((5, "a")) - await sender.send((6, "b")) - await sender.send((5, "c")) - await asyncio.sleep(0) - - assert 5 in cache - assert 6 in cache - assert 7 not in cache - - assert cache.get(5) == (5, "c") - assert cache[5] == (5, "c") - assert cache.get(6) == (6, "b") - assert cache[6] == (6, "b") - - assert cache.keys() == {5, 6} - - assert cache.get(7, default=(7, "default")) == (7, "default") - - await sender.send((12, "d")) - await asyncio.sleep(0) - - assert cache.get(12) == (12, "d") - assert cache.get(12) == (12, "d") - assert cache.get(5) == (5, "c") - assert cache.get(6) == (6, "b") - - await sender.send((6, "e")) - await sender.send((6, "f")) - await sender.send((6, "g")) - await asyncio.sleep(0) - - assert cache.get(6) == (6, "g") - - assert cache.keys() == {5, 6, 12} - - del cache[5] - assert 5 not in cache - assert 6 in cache - - assert cache.get(5) is None - assert cache.keys() == {6, 12} - - assert cache.pop(6) == (6, "g") - assert 6 not in cache - assert cache.keys() == {12} - - assert cache.pop(8, default=True) is True - with pytest.raises(KeyError): - cache.pop(8) - - assert cache.popitem() == (12, (12, "d")) - assert 12 not in cache - assert not cache - - await sender.send((1, "h")) - await sender.send((2, "i")) - await asyncio.sleep(0) - - expected = {1: (1, "h"), 2: (2, "i")} - assert cache.keys() == expected.keys() - assert list(cache.values()) == list(expected.values()) - assert list(cache.items()) == list(expected.items()) - assert cache == expected - assert list(cache) == list(expected) - - cache.clear() - assert not cache - assert cache.keys() == set() - - await cache.stop() - - -@pytest.mark.integration -async def test_equality() -> None: - """Test that two caches with the same content are equal.""" - channel = Broadcast[tuple[int, str]](name="lvc_test") - - with pytest.deprecated_call(): - cache1: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - with pytest.deprecated_call(): - cache2: GroupingLatestValueCache[int, tuple[int, str]] = ( - GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x[0]) - ) - - sender = channel.new_sender() - await sender.send((1, "one")) - await sender.send((2, "two")) - await asyncio.sleep(0) - - assert cache1 == cache2 - - del cache1[1] - assert cache1 != cache2 - - await cache1.stop() - await cache2.stop() - - -@pytest.mark.integration -async def test_grouping_latest_value_cache_is_deprecated() -> None: - """Test that creating a GroupingLatestValueCache warns.""" - channel = Broadcast[int](name="lvc_test") - with pytest.deprecated_call( - match=r"^frequenz\.channels\.experimental\.GroupingLatestValueCache is " - r"deprecated and will be removed in v2\.0\.0\. Copy its code into your project" - ): - cache = GroupingLatestValueCache(channel.new_receiver(), key=lambda x: x) - await cache.stop() - - -@pytest.mark.parametrize("name", ["DefaultT", "HashableT", "ValueT_co"]) -def test_type_variables_are_deprecated(name: str) -> None: - """Test that reaching the type variables of GroupingLatestValueCache warns.""" - experimental = importlib.import_module("frequenz.channels.experimental") - private = importlib.import_module( - "frequenz.channels.experimental._grouping_latest_value_cache" - ) - with pytest.deprecated_call( - match=rf"^frequenz\.channels\.experimental\.{name} is deprecated and will be " - r"removed in v2\.0\.0, together with " - r"frequenz\.channels\.experimental\.GroupingLatestValueCache\." - ): - value = getattr(experimental, name) - assert value is getattr(private, name) diff --git a/tests/test_latest_value_cache_integration.py b/tests/test_latest_value_cache_integration.py index 0c39b21e..28aa4cd5 100644 --- a/tests/test_latest_value_cache_integration.py +++ b/tests/test_latest_value_cache_integration.py @@ -9,6 +9,9 @@ from frequenz.channels import Broadcast, LatestValueCache +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + @pytest.mark.integration async def test_latest_value_cache() -> None: diff --git a/tests/test_merge_integration.py b/tests/test_merge_integration.py index bad399a6..7ed2a1c3 100644 --- a/tests/test_merge_integration.py +++ b/tests/test_merge_integration.py @@ -7,31 +7,31 @@ import pytest -from frequenz.channels import Anycast, Sender, merge -from frequenz.channels._broadcast import Broadcast +from frequenz.channels import Broadcast, BroadcastChannel, Sender, merge from frequenz.channels._receiver import ReceiverStoppedError +# These tests use the deprecated Broadcast on purpose. +pytestmark = pytest.mark.filterwarnings("once::DeprecationWarning") + @pytest.mark.integration -# This test uses the deprecated Anycast on purpose. -@pytest.mark.filterwarnings("once::DeprecationWarning") async def test_merge() -> None: """Ensure merge() receives messages in order.""" - chan1 = Anycast[int](name="chan1") - chan2 = Anycast[int](name="chan2") + sender1, receiver1 = BroadcastChannel[int](name="chan1") + sender2, receiver2 = BroadcastChannel[int](name="chan2") async def send(ch1: Sender[int], ch2: Sender[int]) -> None: for ctr in range(5): await ch1.send(ctr + 1) await ch2.send(ctr + 101) - await chan1.aclose() + await ch1.aclose() await ch2.send(1000) - await chan2.aclose() + await ch2.aclose() - senders = asyncio.create_task(send(chan1.new_sender(), chan2.new_sender())) + senders = asyncio.create_task(send(sender1, sender2)) results: list[int] = [] - async for item in merge(chan1.new_receiver(), chan2.new_receiver()): + async for item in merge(receiver1, receiver2): results.append(item) await senders for ctr in range(5): diff --git a/tests/test_receiver.py b/tests/test_receiver.py new file mode 100644 index 00000000..f224033b --- /dev/null +++ b/tests/test_receiver.py @@ -0,0 +1,26 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the Receiver base class.""" + +import pytest + +from frequenz.channels import Receiver + + +def test_receiver_without_close_cannot_be_instantiated() -> None: + """Test that a receiver subclass has to implement `close()`.""" + + class NoCloseReceiver(Receiver[int]): # pylint: disable=abstract-method + """A receiver that doesn't implement `close()`.""" + + async def ready(self) -> bool: + """Return that the receiver is not ready.""" + return False + + def consume(self) -> int: + """Return a message.""" + return 0 + + with pytest.raises(TypeError, match=r"abstract method.*close"): + NoCloseReceiver() # type: ignore[abstract] # pylint: disable=abstract-class-instantiated diff --git a/tests/test_sender.py b/tests/test_sender.py new file mode 100644 index 00000000..7c5b635f --- /dev/null +++ b/tests/test_sender.py @@ -0,0 +1,34 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the sender errors.""" + +from frequenz.channels import ( + BroadcastChannel, + SenderClosedError, + SenderError, + SenderHasNoReceiversError, + TransientSenderError, +) + + +def test_transient_sender_error() -> None: + """Ensure transient errors are sender errors, and closed senders aren't transient.""" + sender, _receiver = BroadcastChannel[int](name="test") + error = TransientSenderError("Not sent", sender) + + assert isinstance(error, SenderError) + assert error.sender is sender + assert str(error) == "Not sent" + assert not issubclass(SenderClosedError, TransientSenderError) + + +def test_sender_has_no_receivers_error() -> None: + """Ensure having no receivers is a transient sender error.""" + sender, _receiver = BroadcastChannel[int](name="test") + error = SenderHasNoReceiversError(sender) + + assert isinstance(error, TransientSenderError) + assert isinstance(error, SenderError) + assert error.sender is sender + assert str(error) == f"Sender {sender} has no receivers" diff --git a/tests/test_timer.py b/tests/test_timer.py index 197e0a80..b618f861 100644 --- a/tests/test_timer.py +++ b/tests/test_timer.py @@ -767,34 +767,8 @@ async def receive_timer3() -> None: assert timer_trigger_order == [2, 1, 3] -def test_timer_is_deprecated_alias() -> None: - """Test that `Timer` warns and is the same class as `MonotonicTimer`.""" - with pytest.deprecated_call( - match=r"^frequenz\.channels\.timer\.Timer is deprecated\. " - r"Use frequenz\.channels\.timer\.MonotonicTimer instead\. " - r"The name Timer will be used for a wall clock timer in a later version\.$" - ): - from frequenz.channels.timer import ( # pylint: disable=import-outside-toplevel - Timer, - ) - - assert Timer is MonotonicTimer - - async def test_monotonic_timer_is_not_deprecated() -> None: """Test that creating a `MonotonicTimer` doesn't emit deprecation warnings.""" with asserting_no_deprecations(): timer = MonotonicTimer(timedelta(seconds=1.0), TriggerAllMissed()) timer.stop() - - -def test_timer_star_import_warns() -> None: - """Test that `from frequenz.channels.timer import *` still provides `Timer`.""" - namespace: dict[str, Any] = {} - with pytest.deprecated_call( - match=r"^frequenz\.channels\.timer\.Timer is deprecated\. " - ): - # pylint: disable-next=exec-used - exec("from frequenz.channels.timer import *", namespace) - assert namespace["Timer"] is MonotonicTimer - assert namespace["MonotonicTimer"] is MonotonicTimer