|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""A channel that can send a single message.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import typing |
| 10 | + |
| 11 | +from ._generic import ChannelMessageT |
| 12 | +from ._receiver import Receiver, ReceiverStoppedError |
| 13 | +from ._sender import Sender, SenderClosedError |
| 14 | + |
| 15 | + |
| 16 | +class _Empty: |
| 17 | + """A sentinel indicating that no message has been sent.""" |
| 18 | + |
| 19 | + |
| 20 | +_EMPTY = _Empty() |
| 21 | + |
| 22 | + |
| 23 | +class _Oneshot(typing.Generic[ChannelMessageT]): |
| 24 | + """Internal representation of a one-shot channel. |
| 25 | +
|
| 26 | + A one-shot channel is a channel that can only send one message. After the first |
| 27 | + message is sent, the sender is closed and any further attempts to send a message |
| 28 | + will raise a `SenderClosedError`. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self) -> None: |
| 32 | + """Create a new one-shot channel.""" |
| 33 | + self.message: ChannelMessageT | _Empty = _EMPTY |
| 34 | + self.closed: bool = False |
| 35 | + self.drained: bool = False |
| 36 | + self.event: asyncio.Event = asyncio.Event() |
| 37 | + |
| 38 | + |
| 39 | +class OneshotSender(Sender[ChannelMessageT]): |
| 40 | + """A sender for a one-shot channel.""" |
| 41 | + |
| 42 | + def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None: |
| 43 | + """Initialize this sender.""" |
| 44 | + self._channel = channel |
| 45 | + |
| 46 | + async def send(self, message: ChannelMessageT, /) -> None: |
| 47 | + """Send a message through this sender.""" |
| 48 | + if self._channel.closed: |
| 49 | + raise SenderClosedError(self) |
| 50 | + self._channel.message = message |
| 51 | + self._channel.closed = True |
| 52 | + self._channel.event.set() |
| 53 | + |
| 54 | + async def aclose(self) -> None: |
| 55 | + """Close this sender.""" |
| 56 | + self._channel.closed = True |
| 57 | + if isinstance(self._channel.message, _Empty): |
| 58 | + self._channel.drained = True |
| 59 | + self._channel.event.set() |
| 60 | + |
| 61 | + |
| 62 | +class OneshotReceiver(Receiver[ChannelMessageT]): |
| 63 | + """A receiver for a one-shot channel.""" |
| 64 | + |
| 65 | + def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None: |
| 66 | + """Initialize this receiver.""" |
| 67 | + self._channel = channel |
| 68 | + |
| 69 | + async def ready(self) -> bool: |
| 70 | + """Check if a message is ready to be received. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + `True` if a message is ready to be received, `False` if the sender |
| 74 | + is closed and no message will be sent. |
| 75 | + """ |
| 76 | + if self._channel.drained: |
| 77 | + return False |
| 78 | + while not self._channel.closed: |
| 79 | + await self._channel.event.wait() |
| 80 | + if isinstance(self._channel.message, _Empty): |
| 81 | + return False |
| 82 | + return True |
| 83 | + |
| 84 | + def consume(self) -> ChannelMessageT: |
| 85 | + """Consume a message from this receiver. |
| 86 | +
|
| 87 | + Returns: |
| 88 | + The message that was sent through this channel. |
| 89 | +
|
| 90 | + Raises: |
| 91 | + ReceiverStoppedError: If the sender was closed without sending a message. |
| 92 | + """ |
| 93 | + if self._channel.drained: |
| 94 | + raise ReceiverStoppedError(self) |
| 95 | + |
| 96 | + assert not isinstance( |
| 97 | + self._channel.message, _Empty |
| 98 | + ), "`consume()` must be preceded by a call to `ready()`." |
| 99 | + |
| 100 | + self._channel.drained = True |
| 101 | + self._channel.event.clear() |
| 102 | + return self._channel.message |
| 103 | + |
| 104 | + |
| 105 | +class OneshotChannel( |
| 106 | + tuple[OneshotSender[ChannelMessageT], OneshotReceiver[ChannelMessageT]] |
| 107 | +): |
| 108 | + """A channel that can send a single message. |
| 109 | +
|
| 110 | + A one-shot channel is a channel that can only send one message. After the first |
| 111 | + message is sent, the sender is closed and any further attempts to send a message |
| 112 | + will raise a `SenderClosedError`. |
| 113 | +
|
| 114 | + # Example |
| 115 | +
|
| 116 | + This example demonstrates how to use a one-shot channel to send a message |
| 117 | + from one task to another. |
| 118 | +
|
| 119 | + ```python |
| 120 | + import asyncio |
| 121 | +
|
| 122 | + from frequenz.channels import OneshotChannel, OneshotSender |
| 123 | +
|
| 124 | + async def send(sender: OneshotSender[int]) -> None: |
| 125 | + await sender.send(42) |
| 126 | +
|
| 127 | + async def main() -> None: |
| 128 | + sender, receiver = OneshotChannel[int]() |
| 129 | +
|
| 130 | + async with asyncio.TaskGroup() as tg: |
| 131 | + tg.create_task(send(sender)) |
| 132 | + assert await receiver.receive() == 42 |
| 133 | +
|
| 134 | + asyncio.run(main()) |
| 135 | + ``` |
| 136 | + """ |
| 137 | + |
| 138 | + def __new__(cls) -> OneshotChannel[ChannelMessageT]: |
| 139 | + """Create a new one-shot channel.""" |
| 140 | + channel = _Oneshot[ChannelMessageT]() |
| 141 | + |
| 142 | + return tuple.__new__(cls, (OneshotSender(channel), OneshotReceiver(channel))) |
0 commit comments