matter_kit/dm/version.rs
1//! Cluster data versions (Core §7.10.3).
2//!
3//! > A cluster data version SHALL increment or be set (wrap) to zero if incrementing would
4//! > exceed its maximum value. **A cluster data version SHALL be maintained for each cluster
5//! > instance.** A cluster data version SHALL be initialized randomly when it is first
6//! > published. A cluster data version SHALL be incremented if any attribute data changes.
7//!
8//! It is a cache tag. A client that has read a cluster keeps the version it came with and sends
9//! it back in a `DataVersionFilter`; the server then omits everything that has not changed
10//! (§8.4.3.2), which is the difference between a subscription costing one datagram and costing
11//! twenty.
12//!
13//! # Why it is not optional in practice
14//!
15//! §10.6.4.1 permits an `AttributeDataIB` to omit its `DataVersion` — "it SHALL be interpreted
16//! as though a data version was not specified" — so a report without one is a legal report. The
17//! CHIP SDK does not keep such an attribute: its cluster-state cache is keyed by version, and an
18//! attribute that arrives without one is parsed, logged, and dropped. The visible symptom is a
19//! commissioner that reads `BasicCommissioningInfo`, `VendorID` and every other attribute it
20//! needs, receives all of them, and then fails with *Key not found* on each.
21//!
22//! So a device that omits the version is spec-legal and uncommissionable, which is the worst of
23//! both. This table exists so that the correct thing happens without a cluster having to
24//! implement anything: [`ClusterHandler::data_version`](crate::im::ClusterHandler::data_version)
25//! stays the authority for a cluster that tracks its own, and a [`Server`](crate::im::Server)
26//! given one of these falls back to it for every cluster that does not.
27//!
28//! ```
29//! use matter_kit::dm::{DataVersionSource, DataVersions};
30//!
31//! // Sized by the integrator: one entry per cluster instance the node serves.
32//! let versions = DataVersions::<16>::new(0x1234_5678);
33//! let first = versions.version(0, 0x0006);
34//! assert_eq!(versions.version(0, 0x0006), first, "stable until something changes");
35//!
36//! versions.touch(0, 0x0006);
37//! assert_ne!(versions.version(0, 0x0006), first, "and moves when it does");
38//! ```
39
40use core::cell::RefCell;
41
42use crate::im::{ClusterId, EndpointId};
43
44/// Where a [`Server`](crate::im::Server) gets a cluster's data version.
45///
46/// A trait rather than a concrete table so that `Server` does not take the table's capacity as a
47/// generic parameter — the capacity is the integrator's business and nothing in the server's
48/// signature should depend on it.
49pub trait DataVersionSource: core::fmt::Debug {
50 /// The current version of one cluster instance, allocating one if it has never been read.
51 fn version(&self, endpoint: EndpointId, cluster: ClusterId) -> u32;
52
53 /// Records that an attribute of this cluster instance changed.
54 ///
55 /// "A cluster data version SHALL be incremented if any attribute data changes" — *any*, so
56 /// a cluster that changes on its own (a sensor reading, a switch someone pressed) has to
57 /// call this too. Only writes that arrive through the interaction model are automatic.
58 fn touch(&self, endpoint: EndpointId, cluster: ClusterId);
59}
60
61/// One cluster instance's version.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63struct Entry {
64 endpoint: EndpointId,
65 cluster: ClusterId,
66 version: u32,
67}
68
69/// A fixed-capacity table of §7.10.3's cluster data versions.
70///
71/// `N` is how many cluster instances the node has — endpoints times the clusters on each, which
72/// is `const` data, so the number is known when the node is designed. A table that fills stops
73/// tracking new instances rather than evicting a live one: an evicted version would be handed
74/// out again later and tell a client its cache is current when it is not, which is worse than
75/// having no version at all.
76#[derive(Debug)]
77pub struct DataVersions<const N: usize> {
78 entries: RefCell<heapless::Vec<Entry, N>>,
79 /// The generator for a version's initial value.
80 seed: RefCell<u32>,
81 /// Cluster instances touched since [`DataVersions::drain_changes`] last ran.
82 ///
83 /// §7.10.3 already makes the data version the record of "an attribute of this cluster
84 /// changed" — "A cluster data version SHALL be incremented if any attribute data changes".
85 /// This makes that record *observable*, which is what a subscription needs: §8.5.3 dirties
86 /// a subscription on a change to a path it covers, and without somewhere to read changes
87 /// from, a node has to be told about each one by hand and will forget.
88 ///
89 /// Kept separately from `entries` rather than as a flag on one, because a change to an
90 /// instance nobody has read yet still has to be reported: `touch` deliberately does not
91 /// allocate a version for such an instance, and losing the change with it would make the
92 /// signal depend on whether anyone happened to have read the cluster first.
93 changed: RefCell<heapless::Vec<(EndpointId, ClusterId), N>>,
94}
95
96impl<const N: usize> DataVersions<N> {
97 /// An empty table whose first version is derived from `seed`.
98 ///
99 /// §7.10.3: "A cluster data version SHALL be initialized randomly when it is first
100 /// published." `seed` should come from [`Rng`](crate::platform::Rng). Starting every cluster
101 /// at zero on every boot is what lets a client keep a cache across a device's restart and be
102 /// wrong about it: the versions match, the data does not.
103 #[must_use]
104 pub fn new(seed: u32) -> Self {
105 Self {
106 entries: RefCell::new(heapless::Vec::new()),
107 seed: RefCell::new(seed),
108 changed: RefCell::new(heapless::Vec::new()),
109 }
110 }
111
112 /// The cluster instances whose data changed since this was last called, and clears them.
113 ///
114 /// Drained rather than read, because the caller is expected to hand each one to
115 /// [`SubscriptionTable::note_cluster_change`](crate::im::SubscriptionTable::note_cluster_change)
116 /// and a change reported twice is a report sent twice.
117 ///
118 /// This is the seam between "a cluster changed" and "a subscriber is owed a report". Writes
119 /// that arrive through the interaction model land here on their own; a cluster that changes
120 /// on its own — a sensor reading, a switch somebody pressed — is the one that has to call
121 /// [`DataVersionSource::touch`], which §7.10.3 requires of it regardless.
122 #[must_use]
123 pub fn drain_changes(&self) -> heapless::Vec<(EndpointId, ClusterId), N> {
124 core::mem::take(&mut self.changed.borrow_mut())
125 }
126
127 /// How many cluster instances are being tracked.
128 #[must_use]
129 pub fn len(&self) -> usize {
130 self.entries.borrow().len()
131 }
132
133 /// Whether nothing has been published yet.
134 #[must_use]
135 pub fn is_empty(&self) -> bool {
136 self.entries.borrow().is_empty()
137 }
138
139 /// The next initial version, advanced so that two instances do not start together.
140 fn next_seed(&self) -> u32 {
141 let mut seed = self.seed.borrow_mut();
142 // A Weyl sequence: every value distinct over the whole period, and no state but the
143 // counter. The values only have to differ and be unpredictable to a client that has not
144 // read them, which this achieves without a generator the node has to carry.
145 *seed = seed.wrapping_add(0x9E37_79B9);
146 *seed
147 }
148}
149
150impl<const N: usize> DataVersionSource for DataVersions<N> {
151 fn version(&self, endpoint: EndpointId, cluster: ClusterId) -> u32 {
152 if let Some(entry) = self
153 .entries
154 .borrow()
155 .iter()
156 .find(|e| e.endpoint == endpoint && e.cluster == cluster)
157 {
158 return entry.version;
159 }
160 let version = self.next_seed();
161 // A full table still answers — with a version that does not persist, which a client
162 // reads as "changed every time". Losing the cache is a cost; handing out a stale-looking
163 // match is a correctness bug.
164 let _ = self.entries.borrow_mut().push(Entry {
165 endpoint,
166 cluster,
167 version,
168 });
169 version
170 }
171
172 fn touch(&self, endpoint: EndpointId, cluster: ClusterId) {
173 {
174 // Recorded before the version moves, and deduplicated: a burst of writes to one
175 // cluster between two drains is one thing for a subscriber to hear about. A full
176 // list is not an error either — it means more changed than the node can name, and
177 // the drain reports what it has; nothing is lost that a re-prime would not cover.
178 let mut changed = self.changed.borrow_mut();
179 if !changed.contains(&(endpoint, cluster)) {
180 let _ = changed.push((endpoint, cluster));
181 }
182 }
183 let mut entries = self.entries.borrow_mut();
184 if let Some(entry) = entries
185 .iter_mut()
186 .find(|e| e.endpoint == endpoint && e.cluster == cluster)
187 {
188 // "SHALL increment or be set (wrap) to zero if incrementing would exceed its
189 // maximum value" — which is what wrapping addition is.
190 entry.version = entry.version.wrapping_add(1);
191 }
192 // An instance nobody has read has no version to move; the one it gets when it is first
193 // published will be new to every client by construction.
194 }
195}
196
197#[cfg(test)]
198#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
199mod tests {
200 use super::*;
201
202 #[test]
203 fn a_version_is_stable_until_something_changes() {
204 let versions = DataVersions::<8>::new(1);
205 let first = versions.version(0, 0x0006);
206 assert_eq!(versions.version(0, 0x0006), first);
207 versions.touch(0, 0x0006);
208 assert_eq!(versions.version(0, 0x0006), first.wrapping_add(1));
209 }
210
211 /// §7.10.3 keys the version by *instance*, so the same cluster on two endpoints is two
212 /// versions. Sharing one would make a client re-read an endpoint that had not changed.
213 #[test]
214 fn each_cluster_instance_has_its_own() {
215 let versions = DataVersions::<8>::new(1);
216 let a = versions.version(0, 0x0006);
217 let b = versions.version(1, 0x0006);
218 let c = versions.version(0, 0x0008);
219 assert_ne!(a, b);
220 assert_ne!(a, c);
221
222 versions.touch(0, 0x0006);
223 assert_eq!(versions.version(1, 0x0006), b, "the neighbour did not move");
224 assert_eq!(versions.version(0, 0x0008), c);
225 }
226
227 /// "A cluster data version SHALL be initialized randomly when it is first published." Two
228 /// nodes that started every cluster at zero would let a client keep a cache across a reboot
229 /// and be wrong about it.
230 #[test]
231 fn versions_do_not_start_at_zero_or_together() {
232 let versions = DataVersions::<8>::new(0xDEAD_BEEF);
233 let a = versions.version(0, 0x0006);
234 let b = versions.version(0, 0x0008);
235 assert_ne!(a, 0);
236 assert_ne!(b, 0);
237 assert_ne!(a, b);
238 }
239
240 /// "SHALL increment or be set (wrap) to zero if incrementing would exceed its maximum."
241 #[test]
242 fn the_version_wraps_rather_than_overflowing() {
243 let versions = DataVersions::<8>::new(0);
244 // Drive one entry to the maximum and past it.
245 let _ = versions.version(0, 0x0006);
246 {
247 let mut entries = versions.entries.borrow_mut();
248 entries[0].version = u32::MAX;
249 }
250 versions.touch(0, 0x0006);
251 assert_eq!(versions.version(0, 0x0006), 0);
252 }
253
254 /// A full table answers rather than refusing: a read that returned no version is a read the
255 /// CHIP SDK discards entirely.
256 #[test]
257 fn a_full_table_still_answers() {
258 let versions = DataVersions::<2>::new(7);
259 let _ = versions.version(0, 1);
260 let _ = versions.version(0, 2);
261 assert_eq!(versions.len(), 2);
262 let overflow = versions.version(0, 3);
263 assert_ne!(overflow, 0);
264 assert_eq!(versions.len(), 2, "and does not evict a tracked instance");
265 }
266}