|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2025 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""A receiver that will never receive a message. |
| 5 | +
|
| 6 | +It is useful as a place-holder receiver for use in contexts where a receiver is |
| 7 | +necessary, but one is not available. |
| 8 | +""" |
| 9 | + |
| 10 | +import asyncio |
| 11 | + |
| 12 | +from typing_extensions import override |
| 13 | + |
| 14 | +from frequenz.channels import Receiver, ReceiverError, ReceiverMessageT_co |
| 15 | +from frequenz.channels._receiver import ReceiverStoppedError |
| 16 | + |
| 17 | + |
| 18 | +class NopReceiver(Receiver[ReceiverMessageT_co]): |
| 19 | + """A place-holder receiver that will never receive a message.""" |
| 20 | + |
| 21 | + def __init__(self) -> None: |
| 22 | + """Initialize this instance.""" |
| 23 | + self._closed: bool = False |
| 24 | + |
| 25 | + @override |
| 26 | + async def ready(self) -> bool: |
| 27 | + """Wait for ever unless the receiver is closed. |
| 28 | +
|
| 29 | + Returns: |
| 30 | + Whether the receiver is still active. |
| 31 | + """ |
| 32 | + if self._closed: |
| 33 | + return False |
| 34 | + await asyncio.Future() |
| 35 | + return False |
| 36 | + |
| 37 | + @override |
| 38 | + def consume(self) -> ReceiverMessageT_co: # noqa: DOC503 (raised indirectly) |
| 39 | + """Raise `ReceiverError` unless the NopReceiver is closed. |
| 40 | +
|
| 41 | + If the receiver is closed, then raise `ReceiverStoppedError`. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + The next message received. |
| 45 | +
|
| 46 | + Raises: |
| 47 | + ReceiverStoppedError: If the receiver stopped producing messages. |
| 48 | + ReceiverError: If there is some problem with the underlying receiver. |
| 49 | + """ |
| 50 | + if self._closed: |
| 51 | + raise ReceiverStoppedError(self) |
| 52 | + raise ReceiverError("`consume()` must be preceded by a call to `ready()`", self) |
| 53 | + |
| 54 | + @override |
| 55 | + def close(self) -> None: |
| 56 | + """Stop the receiver.""" |
| 57 | + self._closed = True |
0 commit comments