-
Notifications
You must be signed in to change notification settings - Fork 10
Add the oneshot channel implementation #502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shsms
wants to merge
3
commits into
frequenz-floss:v1.x.x
Choose a base branch
from
shsms:oneshot
base: v1.x.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| # License: MIT | ||
| # Copyright © 2026 Frequenz Energy-as-a-Service GmbH | ||
|
|
||
| """A channel that can send a single message.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import typing | ||
|
|
||
| from ._generic import ChannelMessageT | ||
| from ._receiver import Receiver, ReceiverStoppedError | ||
| from ._sender import Sender, SenderClosedError | ||
|
|
||
|
|
||
| class _Empty: | ||
| """A sentinel indicating that no message has been sent.""" | ||
|
|
||
|
|
||
| _EMPTY = _Empty() | ||
|
|
||
|
|
||
| class _Oneshot(typing.Generic[ChannelMessageT]): | ||
| """Internal representation of a one-shot channel. | ||
|
|
||
| A one-shot channel is a channel that can only send one message. After the first | ||
| message is sent, the sender is closed and any further attempts to send a message | ||
| will raise a `SenderClosedError`. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| """Create a new one-shot channel.""" | ||
| self.message: ChannelMessageT | _Empty = _EMPTY | ||
| self.closed: bool = False | ||
| self.drained: bool = False | ||
| self.event: asyncio.Event = asyncio.Event() | ||
|
|
||
|
|
||
| class OneshotSender(Sender[ChannelMessageT]): | ||
| """A sender for a one-shot channel.""" | ||
|
|
||
| def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None: | ||
| """Initialize this sender.""" | ||
| self._channel = channel | ||
|
|
||
| async def send(self, message: ChannelMessageT, /) -> None: | ||
| """Send a message through this sender.""" | ||
| if self._channel.closed: | ||
| raise SenderClosedError(self) | ||
| self._channel.message = message | ||
| self._channel.closed = True | ||
| self._channel.event.set() | ||
|
|
||
| async def aclose(self) -> None: | ||
| """Close this sender.""" | ||
| self._channel.closed = True | ||
| if isinstance(self._channel.message, _Empty): | ||
| self._channel.drained = True | ||
| self._channel.event.set() | ||
|
|
||
|
|
||
| class OneshotReceiver(Receiver[ChannelMessageT]): | ||
| """A receiver for a one-shot channel.""" | ||
|
|
||
| def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None: | ||
| """Initialize this receiver.""" | ||
| self._channel = channel | ||
|
|
||
| async def ready(self) -> bool: | ||
| """Check if a message is ready to be received. | ||
|
|
||
| Returns: | ||
| `True` if a message is ready to be received, `False` if the sender | ||
| is closed and no message will be sent. | ||
| """ | ||
| if self._channel.drained: | ||
| return False | ||
| while not self._channel.closed: | ||
| await self._channel.event.wait() | ||
llucax marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if isinstance(self._channel.message, _Empty): | ||
| return False | ||
| return True | ||
|
|
||
| def consume(self) -> ChannelMessageT: | ||
| """Consume a message from this receiver. | ||
|
|
||
| Returns: | ||
| The message that was sent through this channel. | ||
|
|
||
| Raises: | ||
| ReceiverStoppedError: If the sender was closed without sending a message. | ||
| """ | ||
| if self._channel.drained: | ||
| raise ReceiverStoppedError(self) | ||
|
|
||
| assert not isinstance( | ||
| self._channel.message, _Empty | ||
| ), "`consume()` must be preceded by a call to `ready()`." | ||
|
|
||
| self._channel.drained = True | ||
| self._channel.event.clear() | ||
| return self._channel.message | ||
|
|
||
|
|
||
| class OneshotChannel( | ||
| tuple[OneshotSender[ChannelMessageT], OneshotReceiver[ChannelMessageT]] | ||
| ): | ||
| """A channel that can send a single message. | ||
|
|
||
| A one-shot channel is a channel that can only send one message. After the first | ||
| message is sent, the sender is closed and any further attempts to send a message | ||
| will raise a `SenderClosedError`. | ||
|
|
||
| # Example | ||
|
|
||
| This example demonstrates how to use a one-shot channel to send a message | ||
| from one task to another. | ||
|
|
||
| ```python | ||
| import asyncio | ||
|
|
||
| from frequenz.channels import OneshotChannel, OneshotSender | ||
|
|
||
| async def send(sender: OneshotSender[int]) -> None: | ||
| await sender.send(42) | ||
|
|
||
| async def main() -> None: | ||
| sender, receiver = OneshotChannel[int]() | ||
|
|
||
| async with asyncio.TaskGroup() as tg: | ||
| tg.create_task(send(sender)) | ||
| assert await receiver.receive() == 42 | ||
|
|
||
| asyncio.run(main()) | ||
| ``` | ||
| """ | ||
|
|
||
| def __new__(cls) -> OneshotChannel[ChannelMessageT]: | ||
| """Create a new one-shot channel.""" | ||
| channel = _Oneshot[ChannelMessageT]() | ||
|
|
||
| return tuple.__new__(cls, (OneshotSender(channel), OneshotReceiver(channel))) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.