Coverage for src / zmqtt / _internal / subscription_index.py: 97%
129 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-11-12 08:49 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-11-12 08:49 +0000
1import asyncio
2from collections.abc import Mapping
3from dataclasses import dataclass, field
5from zmqtt._internal.topic_matching import _segment_rank, _topic_matches
6from zmqtt._internal.types.message import Message
9@dataclass(slots=True, kw_only=True)
10class SubscriptionEntry:
11 queue: asyncio.Queue[Message]
12 auto_ack: bool = True
13 actual_filter: str = "" # filter with broker-stripped subscription decorators removed
14 subscription_identifier: int | None = None # v5; echoed by the broker on PUBLISH
15 detached: bool = False
18@dataclass(slots=True)
19class _Node:
20 children: dict[str, "_Node"] = field(default_factory=dict)
21 wildcard_children: dict[str, "_Node"] = field(default_factory=dict)
22 entries: list[tuple[str, SubscriptionEntry]] = field(default_factory=list)
25@dataclass(frozen=True, slots=True)
26class SubscriptionSelection:
27 recipient: tuple[str, SubscriptionEntry] | None
28 identifier_missing: bool = False
29 tied_filters: tuple[str, ...] = ()
32class SubscriptionIndex:
33 def __init__(self) -> None:
34 self._root = _Node()
35 self._entries: dict[str, SubscriptionEntry] = {}
36 self._by_identifier: dict[int, dict[str, SubscriptionEntry]] = {}
37 self._response_observers: set[str] = set()
39 def add(self, filter_: str, entry: SubscriptionEntry) -> None:
40 if filter_ in self._entries:
41 self.remove(filter_)
43 tree_filter = entry.actual_filter or filter_
44 node = self._root
45 for part in tree_filter.split("/"):
46 mapping = node.wildcard_children if part in {"+", "#"} else node.children
47 node = mapping.setdefault(part, _Node())
49 node.entries.append((filter_, entry))
50 self._entries[filter_] = entry
51 identifier = entry.subscription_identifier
52 if identifier is not None:
53 self._by_identifier.setdefault(identifier, {})[filter_] = entry
55 def contains(self, filter_: str) -> bool:
56 return filter_ in self._entries
58 def add_response_observer(self, topic: str) -> bool:
59 """Register an exact response-topic observer.
61 Returns ``True`` only for the first observer on this connection.
62 """
63 if topic in self._response_observers:
64 return False
65 self._response_observers.add(topic)
66 return True
68 def remove_response_observer(self, topic: str) -> bool:
69 if topic not in self._response_observers:
70 return False
71 self._response_observers.remove(topic)
72 return True
74 def has_response_observer(self, topic: str) -> bool:
75 return topic in self._response_observers
77 def get(self, filter_: str, default: SubscriptionEntry | None = None) -> SubscriptionEntry | None:
78 return self._entries.get(filter_, default)
80 def remove(self, filter_: str) -> SubscriptionEntry | None:
81 entry = self._entries.pop(filter_, None)
82 if entry is None:
83 return None
85 tree_filter = entry.actual_filter or filter_
86 self._remove_entry(tree_filter.split("/"), filter_, entry, self._root)
88 identifier = entry.subscription_identifier
89 if identifier is not None:
90 identified = self._by_identifier.get(identifier)
91 if identified is not None:
92 identified.pop(filter_, None)
93 if not identified:
94 self._by_identifier.pop(identifier)
95 return entry
97 def clear(self) -> None:
98 self._root = _Node()
99 self._entries.clear()
100 self._by_identifier.clear()
101 self._response_observers.clear()
103 def add_many(self, entries: Mapping[str, SubscriptionEntry]) -> None:
104 for filter_, entry in entries.items():
105 self.add(filter_, entry)
107 def match(self, topic: str) -> list[tuple[str, SubscriptionEntry]]:
108 matches: list[tuple[str, SubscriptionEntry]] = []
109 self._collect(
110 node=self._root,
111 parts=topic.split("/"),
112 collect_to=matches,
113 )
114 filtered = [item for item in matches if _topic_matches(self._actual_filter(*item), topic)]
115 return sorted(filtered, key=lambda item: self._specificity(self._actual_filter(*item)))
117 def best(self, topic: str) -> tuple[str, SubscriptionEntry] | None:
118 return self.select(topic).recipient
120 def by_identifier(self, identifier: int) -> list[tuple[str, SubscriptionEntry]]:
121 return list(self._by_identifier.get(identifier, {}).items())
123 def select(self, topic: str) -> SubscriptionSelection:
124 return self._select_from(self.match(topic))
126 def select_by_identifier(self, topic: str, identifier: int) -> SubscriptionSelection:
127 identified = self.by_identifier(identifier)
128 if identified:
129 matching = [item for item in identified if _topic_matches(self._actual_filter(*item), topic)]
130 return self._select_from(matching or identified)
132 fallback = self.select(topic)
133 return SubscriptionSelection(
134 recipient=fallback.recipient,
135 identifier_missing=True,
136 tied_filters=fallback.tied_filters,
137 )
139 def _select_from(
140 self,
141 candidates: list[tuple[str, SubscriptionEntry]],
142 ) -> SubscriptionSelection:
143 if not candidates:
144 return SubscriptionSelection(recipient=None)
146 best_key = min(self._specificity(self._actual_filter(*item)) for item in candidates)
147 winners = [item for item in candidates if self._specificity(self._actual_filter(*item)) == best_key]
148 tied_filters = tuple(filter_ for filter_, _ in winners) if len(winners) > 1 else ()
149 return SubscriptionSelection(
150 recipient=winners[0],
151 tied_filters=tied_filters,
152 )
154 def _remove_entry(
155 self,
156 parts: list[str],
157 filter_: str,
158 entry: SubscriptionEntry,
159 node: _Node,
160 ) -> None:
161 if not parts:
162 node.entries = [item for item in node.entries if not (item[0] == filter_ and item[1] is entry)]
163 return
165 part = parts[0]
166 mapping = node.wildcard_children if part in {"#", "+"} else node.children
168 child = mapping.get(part)
169 if child is None:
170 return
172 self._remove_entry(parts[1:], filter_, entry, child)
174 if not child.children and not child.wildcard_children and not child.entries:
175 mapping.pop(part)
177 def _collect(
178 self,
179 node: _Node,
180 parts: list[str],
181 collect_to: list[tuple[str, SubscriptionEntry]],
182 idx: int = 0,
183 ) -> None:
184 if "#" in node.wildcard_children:
185 collect_to.extend(node.wildcard_children["#"].entries)
186 if idx == len(parts):
187 collect_to.extend(node.entries)
188 return
190 part = parts[idx]
191 if part in node.children:
192 self._collect(
193 node=node.children[part],
194 parts=parts,
195 idx=idx + 1,
196 collect_to=collect_to,
197 )
198 if "+" in node.wildcard_children:
199 self._collect(
200 node=node.wildcard_children["+"],
201 parts=parts,
202 idx=idx + 1,
203 collect_to=collect_to,
204 )
206 def _actual_filter(self, filter_: str, entry: SubscriptionEntry) -> str:
207 return entry.actual_filter or filter_
209 def _specificity(self, filter_: str) -> tuple[int, ...]:
210 return tuple(_segment_rank(segment) for segment in filter_.split("/"))