|
3 | 3 |
|
4 | 4 | """A class that would dynamically create, own and provide access to channels."""
|
5 | 5 |
|
6 |
| -from __future__ import annotations |
| 6 | +import dataclasses |
| 7 | +import logging |
| 8 | +import traceback |
| 9 | +from typing import TypeVar, cast |
7 | 10 |
|
8 |
| -import typing |
| 11 | +from frequenz.channels import Broadcast |
9 | 12 |
|
10 |
| -from frequenz.channels import Broadcast, Receiver, Sender |
11 |
| - |
12 |
| -from .._internal._channels import ReceiverFetcher |
| 13 | +_T = TypeVar("_T") |
| 14 | +_logger = logging.getLogger(__name__) |
13 | 15 |
|
14 | 16 |
|
15 | 17 | class ChannelRegistry:
|
16 |
| - """Dynamically creates, own and provide access to channels. |
| 18 | + """Dynamically creates, own and provide access to broadcast channels. |
17 | 19 |
|
18 | 20 | It can be used by actors to dynamically establish a communication channel
|
19 |
| - between each other. Channels are identified by string names. |
| 21 | + between each other. |
| 22 | +
|
| 23 | + The registry is responsible for creating channels when they are first requested via |
| 24 | + the [`get_or_create()`][frequenz.sdk.actor.ChannelRegistry.get_or_create] method. |
| 25 | +
|
| 26 | + The registry also stores type information to make sure that the same channel is not |
| 27 | + used for different message types. |
| 28 | +
|
| 29 | + Since the registry owns the channels, it is also responsible for closing them when |
| 30 | + they are no longer needed. There is no way to remove a channel without closing it. |
| 31 | +
|
| 32 | + Note: |
| 33 | + This registry stores [`Broadcast`][frequenz.channels.Broadcast] channels. |
20 | 34 | """
|
21 | 35 |
|
22 | 36 | def __init__(self, *, name: str) -> None:
|
23 |
| - """Create a `ChannelRegistry` instance. |
| 37 | + """Initialize this registry. |
24 | 38 |
|
25 | 39 | Args:
|
26 |
| - name: A unique name for the registry. |
| 40 | + name: A name to identify the registry in the logs. This name is also used as |
| 41 | + a prefix for the channel names. |
27 | 42 | """
|
28 | 43 | self._name = name
|
29 |
| - self._channels: dict[str, Broadcast[typing.Any]] = {} |
| 44 | + self._channels: dict[str, _Entry] = {} |
30 | 45 |
|
31 |
| - def set_resend_latest(self, key: str, resend_latest: bool) -> None: |
32 |
| - """Set the `resend_latest` flag for a given channel. |
| 46 | + @property |
| 47 | + def name(self) -> str: |
| 48 | + """The name of this registry.""" |
| 49 | + return self._name |
33 | 50 |
|
34 |
| - This flag controls whether the latest value of the channel should be resent to |
35 |
| - new receivers, in slow streams. |
36 |
| -
|
37 |
| - `resend_latest` is `False` by default. It is safe to be set in data/reporting |
38 |
| - channels, but is not recommended for use in channels that stream control |
39 |
| - instructions. |
| 51 | + def message_type(self, key: str) -> type: |
| 52 | + """Get the message type of the channel for the given key. |
40 | 53 |
|
41 | 54 | Args:
|
42 | 55 | key: The key to identify the channel.
|
43 |
| - resend_latest: Whether to resend the latest value to new receivers, for the |
44 |
| - given channel. |
45 |
| - """ |
46 |
| - if key not in self._channels: |
47 |
| - self._channels[key] = Broadcast(f"{self._name}-{key}") |
48 |
| - # This attribute is protected in the current version of the channels library, |
49 |
| - # but that will change in the future. |
50 |
| - self._channels[key].resend_latest = resend_latest |
51 |
| - |
52 |
| - def new_sender(self, key: str) -> Sender[typing.Any]: |
53 |
| - """Get a sender to a dynamically created channel with the given key. |
54 |
| -
|
55 |
| - Args: |
56 |
| - key: A key to identify the channel. |
57 | 56 |
|
58 | 57 | Returns:
|
59 |
| - A sender to a dynamically created channel with the given key. |
60 |
| - """ |
61 |
| - if key not in self._channels: |
62 |
| - self._channels[key] = Broadcast(f"{self._name}-{key}") |
63 |
| - return self._channels[key].new_sender() |
64 |
| - |
65 |
| - def new_receiver(self, key: str, maxsize: int = 50) -> Receiver[typing.Any]: |
66 |
| - """Get a receiver to a dynamically created channel with the given key. |
| 58 | + The message type of the channel. |
67 | 59 |
|
68 |
| - Args: |
69 |
| - key: A key to identify the channel. |
70 |
| - maxsize: The maximum size of the receiver. |
71 |
| -
|
72 |
| - Returns: |
73 |
| - A receiver for a dynamically created channel with the given key. |
| 60 | + Raises: |
| 61 | + KeyError: If the channel does not exist. |
74 | 62 | """
|
75 |
| - if key not in self._channels: |
76 |
| - self._channels[key] = Broadcast(f"{self._name}-{key}") |
77 |
| - return self._channels[key].new_receiver(maxsize=maxsize) |
| 63 | + entry = self._channels.get(key) |
| 64 | + if entry is None: |
| 65 | + raise KeyError(f"No channel for key {key!r} exists.") |
| 66 | + return entry.message_type |
78 | 67 |
|
79 |
| - def new_receiver_fetcher(self, key: str) -> ReceiverFetcher[typing.Any]: |
80 |
| - """Get a receiver fetcher to a dynamically created channel with the given key. |
| 68 | + def __contains__(self, key: str) -> bool: |
| 69 | + """Check whether the channel for the given `key` exists.""" |
| 70 | + return key in self._channels |
81 | 71 |
|
82 |
| - Args: |
83 |
| - key: A key to identify the channel. |
84 |
| -
|
85 |
| - Returns: |
86 |
| - A receiver fetcher for a dynamically created channel with the given key. |
87 |
| - """ |
88 |
| - if key not in self._channels: |
89 |
| - self._channels[key] = Broadcast(f"{self._name}-{key}") |
90 |
| - return _RegistryReceiverFetcher(self, key) |
| 72 | + def get_or_create(self, message_type: type[_T], key: str) -> Broadcast[_T]: |
| 73 | + """Get or create a channel for the given key. |
91 | 74 |
|
92 |
| - async def _close_channel(self, key: str) -> None: |
93 |
| - """Close a channel with the given key. |
| 75 | + If a channel for the given key already exists, the message type of the existing |
| 76 | + channel is checked against the requested message type. If they do not match, |
| 77 | + a `ValueError` is raised. |
94 | 78 |
|
95 |
| - This method is private and should only be used in special cases. |
| 79 | + Note: |
| 80 | + The types have to match exactly, it doesn't do a subtype check due to |
| 81 | + technical limitations. In the future subtype checks might be supported. |
96 | 82 |
|
97 | 83 | Args:
|
98 |
| - key: A key to identify the channel. |
99 |
| - """ |
100 |
| - if key in self._channels: |
101 |
| - if channel := self._channels.pop(key, None): |
102 |
| - await channel.close() |
103 |
| - |
104 |
| - |
105 |
| -T = typing.TypeVar("T") |
106 |
| - |
107 |
| - |
108 |
| -class _RegistryReceiverFetcher(typing.Generic[T]): |
109 |
| - """A receiver fetcher that is bound to a channel registry and a key.""" |
| 84 | + message_type: The type of the message that is sent through the channel. |
| 85 | + key: The key to identify the channel. |
110 | 86 |
|
111 |
| - def __init__( |
112 |
| - self, |
113 |
| - registry: ChannelRegistry, |
114 |
| - key: str, |
115 |
| - ) -> None: |
116 |
| - """Create a new instance of a receiver fetcher. |
| 87 | + Returns: |
| 88 | + The channel for the given key. |
117 | 89 |
|
118 |
| - Args: |
119 |
| - registry: The channel registry. |
120 |
| - key: A key to identify the channel. |
| 90 | + Raises: |
| 91 | + ValueError: If the channel exists and the message type does not match. |
121 | 92 | """
|
122 |
| - self._registry = registry |
123 |
| - self._key = key |
124 |
| - |
125 |
| - def new_receiver(self, maxsize: int = 50) -> Receiver[T]: |
126 |
| - """Get a receiver from the channel. |
| 93 | + if key not in self._channels: |
| 94 | + if _logger.isEnabledFor(logging.DEBUG): |
| 95 | + _logger.debug( |
| 96 | + "Creating a new channel for key %r with type %s at:\n%s", |
| 97 | + key, |
| 98 | + message_type, |
| 99 | + "".join(traceback.format_stack(limit=10)[:9]), |
| 100 | + ) |
| 101 | + self._channels[key] = _Entry(message_type, Broadcast(f"{self._name}-{key}")) |
| 102 | + |
| 103 | + entry = self._channels[key] |
| 104 | + if entry.message_type is not message_type: |
| 105 | + exception = ValueError( |
| 106 | + f"Type mismatch, a channel for key {key!r} exists and the requested " |
| 107 | + f"message type {message_type} is not the same as the existing " |
| 108 | + f"message type {entry.message_type}." |
| 109 | + ) |
| 110 | + if _logger.isEnabledFor(logging.DEBUG): |
| 111 | + _logger.debug( |
| 112 | + "%s at:\n%s", |
| 113 | + str(exception), |
| 114 | + # We skip the last frame because it's this method, and limit the |
| 115 | + # stack to 9 frames to avoid adding too much noise. |
| 116 | + "".join(traceback.format_stack(limit=10)[:9]), |
| 117 | + ) |
| 118 | + raise exception |
| 119 | + |
| 120 | + return cast(Broadcast[_T], entry.channel) |
| 121 | + |
| 122 | + async def close_and_remove(self, key: str) -> None: |
| 123 | + """Remove the channel for the given key. |
127 | 124 |
|
128 | 125 | Args:
|
129 |
| - maxsize: The maximum size of the receiver. |
| 126 | + key: The key to identify the channel. |
130 | 127 |
|
131 |
| - Returns: |
132 |
| - A receiver instance. |
| 128 | + Raises: |
| 129 | + KeyError: If the channel does not exist. |
133 | 130 | """
|
134 |
| - return self._registry.new_receiver(self._key, maxsize) |
| 131 | + entry = self._channels.pop(key, None) |
| 132 | + if entry is None: |
| 133 | + raise KeyError(f"No channel for key {key!r} exists.") |
| 134 | + await entry.channel.close() |
| 135 | + |
| 136 | + |
| 137 | +@dataclasses.dataclass(frozen=True) |
| 138 | +class _Entry: |
| 139 | + """An entry in a channel registry.""" |
| 140 | + |
| 141 | + message_type: type |
| 142 | + """The type of the message that is sent through the channel in this entry.""" |
| 143 | + |
| 144 | + # We use object instead of Any to minimize the chances of hindering type checking. |
| 145 | + # If for some reason the channel is not casted to the proper underlaying type, when |
| 146 | + # using object at least accessing any member that's not part of the object base |
| 147 | + # class will yield a type error, while if we used Any, it would not and the issue |
| 148 | + # would be much harder to find. |
| 149 | + channel: Broadcast[object] |
| 150 | + """The channel in this entry.""" |
0 commit comments