matter_kit/im/atomic.rs
1//! Atomic writes: several attributes changed together, or not at all (Core §7.15).
2//!
3//! > Atomic writes allow a client to make multiple writes to certain sets of attributes
4//! > atomically, such that changes are either applied entirely or none at all.
5//!
6//! The case it exists for is a set of attributes whose *combination* has to be valid — a
7//! thermostat's heating and cooling setpoints, where each is legal alone and the pair can be
8//! contradictory. Writing them one at a time means passing through a state the device must
9//! either reject or briefly obey, and neither is acceptable.
10//!
11//! §7.15.1's flow is three stages: `AtomicRequest(BeginWrite)` claims a set of attributes,
12//! ordinary Write Requests then *pend* rather than apply, and `AtomicRequest(CommitWrite)`
13//! applies them together — or `RollbackWrite` throws them away.
14//!
15//! # What this module is
16//!
17//! The **state**, which is the part with the security-relevant rules. §7.15.3 defines an
18//! Atomic Write State as five things — an endpoint, a cluster, an Atomic Writer ID, the
19//! accessing fabric, and a set of attribute ids — and this is the table of them, with the
20//! timeout that §7.15.6.4 requires a claim to expire under.
21//!
22//! Holding the *pending values* is the cluster's, deliberately. A pending value has the
23//! cluster's own type, and a table here would have to hold it as bytes and hand the cluster
24//! back something it must re-parse — for no gain, since the cluster is the only thing that
25//! can evaluate §7.15.3's "integrity checks … in the context of the pending values".
26//!
27//! # The writer is the session's, never the message's
28//!
29//! §7.15.2: "If the session context for the transaction is a Secure Session Context, the
30//! Atomic Writer ID SHALL be the Peer Node ID stored in the context." A claim identified by
31//! something the message carried could be taken over by anyone who could guess it — so
32//! [`Writer::from_context`] reads the session and nothing else, and a group message, which
33//! has no peer node id, can never hold a claim at all.
34
35use core::marker::PhantomData;
36
37use heapless::Vec;
38
39use crate::config::{AssertValid, Config};
40use crate::im::{AttributeId, ClusterId, EndpointId, InteractionContext, Status};
41use crate::msg::{FabricIndex, NodeId, NodeIdKind};
42use crate::platform::{Duration, Instant};
43
44/// §7.15.4's `AtomicRequestTypeEnum`.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum RequestType {
47 /// `0` — claim a set of attributes and start pending writes to them.
48 BeginWrite = 0,
49 /// `1` — apply every pending write, or none.
50 CommitWrite = 1,
51 /// `2` — "Rollback an atomic write, discarding any pending changes".
52 RollbackWrite = 2,
53}
54
55impl RequestType {
56 /// Reads the enum value off the wire.
57 #[must_use]
58 pub const fn from_value(value: u8) -> Option<Self> {
59 match value {
60 0 => Some(Self::BeginWrite),
61 1 => Some(Self::CommitWrite),
62 2 => Some(Self::RollbackWrite),
63 _ => None,
64 }
65 }
66}
67
68/// Who holds a claim — §7.15.2's Atomic Writer ID, together with its fabric.
69///
70/// §7.15.3 keys a state on both: the same node id on two fabrics is two different clients,
71/// and letting one inherit the other's claim would let a second administrator commit writes
72/// the first had staged.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct Writer {
75 /// The peer's operational Node ID, from the session.
76 pub node: NodeId,
77 /// The accessing fabric.
78 pub fabric: FabricIndex,
79}
80
81impl Writer {
82 /// The writer an interaction identifies, or `None` when it cannot hold a claim.
83 ///
84 /// §7.15.6.4: "If an AtomicRequest command is received without an accessing fabric, the
85 /// server SHALL return a status code of INVALID_COMMAND", and likewise for a writer id
86 /// that is "either unavailable or not a valid Operational Node ID". Both are `None` here.
87 ///
88 /// A PASE session has no operational node id, and a group message has no peer at all, so
89 /// neither can begin an atomic write — which is right: an atomic write is a claim held
90 /// across several messages, and a claim needs somebody to be held *by*.
91 #[must_use]
92 pub fn from_context(ctx: &InteractionContext<'_>) -> Option<Self> {
93 let node = ctx.peer_node_id?;
94 if !matches!(node.kind(), NodeIdKind::Operational) {
95 return None;
96 }
97 let fabric = ctx.fabric_index?;
98 if fabric.0 == 0 {
99 return None;
100 }
101 Some(Self { node, fabric })
102 }
103}
104
105/// One Atomic Write State (§7.15.3).
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Claim<const A: usize> {
108 /// Which endpoint.
109 pub endpoint: EndpointId,
110 /// Which cluster instance on it.
111 pub cluster: ClusterId,
112 /// Who holds it.
113 pub writer: Writer,
114 /// The attributes it covers.
115 pub attributes: Vec<AttributeId, A>,
116 /// When it lapses if no `CommitWrite` arrives (§7.15.6.4 BeginWrite step 3(e)(iii)).
117 pub deadline: Instant,
118}
119
120impl<const A: usize> Claim<A> {
121 /// A borrowed, non-generic view of this claim.
122 ///
123 /// What [`InteractionContext`] carries: the server needs only "which attributes, on which
124 /// cluster instance", and threading `A` through every layer that touches a write would
125 /// spread one table's sizing across the whole interaction model.
126 #[must_use]
127 pub fn as_ref(&self) -> ClaimRef<'_> {
128 ClaimRef {
129 endpoint: self.endpoint,
130 cluster: self.cluster,
131 attributes: &self.attributes,
132 }
133 }
134}
135
136/// The claim an action is writing under (§7.15.3), as the server sees it.
137///
138/// Derived by the caller from [`AtomicWrites::find`] and asserted by the server — the same
139/// shape as [`InteractionContext::timed`], and for the same reason: the table that knows the
140/// answer is the device's, and the interaction model's job is to *apply* it rather than to own
141/// it.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct ClaimRef<'a> {
144 /// The endpoint the claim is on.
145 pub endpoint: EndpointId,
146 /// The cluster instance it covers.
147 pub cluster: ClusterId,
148 /// The attributes it covers.
149 pub attributes: &'a [AttributeId],
150}
151
152impl ClaimRef<'_> {
153 /// Whether this claim covers one attribute of one cluster instance.
154 #[must_use]
155 pub fn covers(&self, endpoint: EndpointId, cluster: ClusterId, attribute: AttributeId) -> bool {
156 self.endpoint == endpoint && self.cluster == cluster && self.attributes.contains(&attribute)
157 }
158}
159
160/// The claims a node is holding (§7.15.3).
161///
162/// `N` is how many may be open at once and `A` how many attributes one may cover.
163#[derive(Debug)]
164pub struct AtomicWrites<C: Config, const N: usize, const A: usize> {
165 claims: Vec<Claim<A>, N>,
166 _config: PhantomData<C>,
167}
168
169impl<C: Config, const N: usize, const A: usize> Default for AtomicWrites<C, N, A> {
170 fn default() -> Self {
171 Self::new()
172 }
173}
174
175impl<C: Config, const N: usize, const A: usize> AtomicWrites<C, N, A> {
176 /// A node holding no claims.
177 #[must_use]
178 pub fn new() -> Self {
179 let () = AssertValid::<C>::CHECK;
180 Self {
181 claims: Vec::new(),
182 _config: PhantomData,
183 }
184 }
185
186 /// How many claims are open.
187 #[must_use]
188 pub fn len(&self) -> usize {
189 self.claims.len()
190 }
191
192 /// Whether none are.
193 #[must_use]
194 pub fn is_empty(&self) -> bool {
195 self.claims.is_empty()
196 }
197
198 /// Every open claim.
199 pub fn iter(&self) -> impl Iterator<Item = &Claim<A>> {
200 self.claims.iter()
201 }
202
203 /// §7.15.6.4's `BeginWrite`.
204 ///
205 /// The per-attribute statuses §7.15.6.4 BeginWrite step 3(a) asks for are the *cluster's*
206 /// to produce — only it knows whether an attribute supports atomic writes or whether it
207 /// has room to pend a value. What this decides is the two rules that are about the table:
208 ///
209 /// * a client already holding a claim on the same cluster and endpoint is
210 /// [`Status::InvalidInState`] (§7.15.6.4 BeginWrite step 1);
211 /// * an attribute another client is already using is [`Status::Busy`]
212 /// (§7.15.6.4 BeginWrite step 3(a)(iii)).
213 ///
214 /// `attributes` must be non-empty and free of duplicates — §7.15.6.4's rules 1 and 2, both
215 /// [`Status::InvalidCommand`].
216 pub fn begin(
217 &mut self,
218 endpoint: EndpointId,
219 cluster: ClusterId,
220 writer: Writer,
221 attributes: &[AttributeId],
222 timeout: Duration,
223 now: Instant,
224 ) -> Result<(), Status> {
225 // Rule 1: "If the AttributeRequests field is empty, the server SHALL return an error
226 // code of INVALID_COMMAND."
227 if attributes.is_empty() {
228 return Err(Status::InvalidCommand);
229 }
230 // Rule 2: duplicates. A set that named an attribute twice would be committed twice,
231 // and the second write would see the first's pending value as if it were current.
232 for (index, id) in attributes.iter().enumerate() {
233 if attributes
234 .get(index.saturating_add(1)..)
235 .is_some_and(|rest| rest.contains(id))
236 {
237 return Err(Status::InvalidCommand);
238 }
239 }
240
241 // §7.15.6.4 BeginWrite step 1: one claim per client per cluster instance.
242 if self.find(endpoint, cluster, writer).is_some() {
243 return Err(Status::InvalidInState);
244 }
245 // §7.15.6.4 BeginWrite step 3(a)(iii): "If the specified attribute is currently being
246 // used by a different atomic write, the status SHALL be BUSY."
247 for id in attributes {
248 if self.holder(endpoint, cluster, *id).is_some() {
249 return Err(Status::Busy);
250 }
251 }
252
253 let mut held = Vec::new();
254 for id in attributes {
255 held.push(*id).map_err(|_| Status::ResourceExhausted)?;
256 }
257 self.claims
258 .push(Claim {
259 endpoint,
260 cluster,
261 writer,
262 attributes: held,
263 deadline: now.saturating_add(timeout),
264 })
265 .map_err(|_| Status::ResourceExhausted)
266 }
267
268 /// §7.15.6's `CommitWrite` and `RollbackWrite`: releases the claim.
269 ///
270 /// Both end the claim; what differs is whether the cluster applies its pending values,
271 /// which it does on the strength of the [`RequestType`] it was given. Returns
272 /// [`Status::InvalidInState`] when the client holds no matching claim — §7.15.6's rule 1
273 /// for `CommitWrite`, which requires the attribute set to match too, "irrespective of
274 /// order".
275 pub fn finish(
276 &mut self,
277 endpoint: EndpointId,
278 cluster: ClusterId,
279 writer: Writer,
280 attributes: &[AttributeId],
281 ) -> Result<(), Status> {
282 let Some(index) = self
283 .claims
284 .iter()
285 .position(|c| c.endpoint == endpoint && c.cluster == cluster && c.writer == writer)
286 else {
287 return Err(Status::InvalidInState);
288 };
289 let matches = self
290 .claims
291 .get(index)
292 .is_some_and(|claim| same_set(&claim.attributes, attributes));
293 if !matches {
294 return Err(Status::InvalidInState);
295 }
296 self.claims.swap_remove(index);
297 Ok(())
298 }
299
300 /// The claim a client holds on a cluster instance, if any.
301 #[must_use]
302 pub fn find(
303 &self,
304 endpoint: EndpointId,
305 cluster: ClusterId,
306 writer: Writer,
307 ) -> Option<&Claim<A>> {
308 self.claims
309 .iter()
310 .find(|c| c.endpoint == endpoint && c.cluster == cluster && c.writer == writer)
311 }
312
313 /// Who holds a claim covering one attribute, if anybody.
314 #[must_use]
315 pub fn holder(
316 &self,
317 endpoint: EndpointId,
318 cluster: ClusterId,
319 attribute: AttributeId,
320 ) -> Option<Writer> {
321 self.claims
322 .iter()
323 .find(|c| {
324 c.endpoint == endpoint && c.cluster == cluster && c.attributes.contains(&attribute)
325 })
326 .map(|c| c.writer)
327 }
328
329 /// Whether a write to an attribute with the Atomic quality may proceed (§7.15.3).
330 ///
331 /// > If a server receives a Write Request for an attribute that is not associated with an
332 /// > Atomic Write State that is also associated with the client making the request, the
333 /// > server SHALL return the error code INVALID_IN_STATE.
334 ///
335 /// Both halves matter, and they are different failures. A write with **no** claim is a
336 /// client that skipped `BeginWrite`; a write against **somebody else's** claim is a client
337 /// trying to change values another client has staged and is about to commit.
338 pub fn check_write(
339 &self,
340 endpoint: EndpointId,
341 cluster: ClusterId,
342 writer: Option<Writer>,
343 attribute: AttributeId,
344 ) -> Result<(), Status> {
345 let Some(writer) = writer else {
346 return Err(Status::InvalidInState);
347 };
348 match self.find(endpoint, cluster, writer) {
349 Some(claim) if claim.attributes.contains(&attribute) => Ok(()),
350 _ => Err(Status::InvalidInState),
351 }
352 }
353
354 /// Drops every claim whose timeout has passed, returning how many — §7.15.6.4 BeginWrite
355 /// step 3(e)(iii).
356 ///
357 /// > If the server does not receive a matching AtomicRequest with a RequestType of
358 /// > CommitWrite from the associated client before the timeout … the server SHALL roll
359 /// > back any pending writes and discard the atomic write.
360 ///
361 /// Without this a client that crashed mid-write would hold its attributes against every
362 /// other client until the device was restarted.
363 pub fn reap(&mut self, now: Instant) -> usize {
364 let before = self.claims.len();
365 self.claims.retain(|claim| claim.deadline > now);
366 before.saturating_sub(self.claims.len())
367 }
368
369 /// Drops every claim a fabric holds — what `RemoveFabric` must do.
370 pub fn remove_fabric(&mut self, fabric: FabricIndex) -> usize {
371 let before = self.claims.len();
372 self.claims.retain(|claim| claim.writer.fabric != fabric);
373 before.saturating_sub(self.claims.len())
374 }
375
376 /// When [`AtomicWrites::reap`] next has something to do.
377 #[must_use]
378 pub fn next_deadline(&self) -> Option<Instant> {
379 self.claims.iter().map(|c| c.deadline).min()
380 }
381}
382
383/// Whether two attribute sets are equal "irrespective of order" (§7.15.6's Commit rule 1).
384fn same_set(held: &[AttributeId], asked: &[AttributeId]) -> bool {
385 held.len() == asked.len() && held.iter().all(|id| asked.contains(id))
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391 use crate::config::DefaultConfig;
392
393 type Table = AtomicWrites<DefaultConfig, 4, 4>;
394
395 const EP: EndpointId = 1;
396 const THERMOSTAT: ClusterId = 0x0201;
397 const HEAT: AttributeId = 0x0012;
398 const COOL: AttributeId = 0x0011;
399
400 fn alice() -> Writer {
401 Writer {
402 node: NodeId(0x0000_0000_0000_1111),
403 fabric: FabricIndex(1),
404 }
405 }
406
407 fn bob() -> Writer {
408 Writer {
409 node: NodeId(0x0000_0000_0000_2222),
410 fabric: FabricIndex(1),
411 }
412 }
413
414 fn at(ms: u64) -> Instant {
415 Instant::from_micros(ms.saturating_mul(1000))
416 }
417
418 fn timeout() -> Duration {
419 Duration::from_millis(1_000)
420 }
421
422 #[test]
423 fn a_claim_covers_its_attributes_and_only_its_own_client() {
424 let mut table = Table::new();
425 table
426 .begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
427 .expect("begin");
428
429 assert!(
430 table
431 .check_write(EP, THERMOSTAT, Some(alice()), HEAT)
432 .is_ok()
433 );
434 // Somebody else's claim is not a licence to write into it.
435 assert_eq!(
436 table.check_write(EP, THERMOSTAT, Some(bob()), HEAT),
437 Err(Status::InvalidInState)
438 );
439 // Nor is an attribute the claim does not cover.
440 assert_eq!(
441 table.check_write(EP, THERMOSTAT, Some(alice()), 0x0099),
442 Err(Status::InvalidInState)
443 );
444 }
445
446 #[test]
447 fn writing_an_atomic_attribute_with_no_claim_is_invalid_in_state() {
448 // §7.15.3: an attribute with the Atomic quality is writable only inside a claim, so a
449 // client that skipped BeginWrite is told so rather than having its write applied.
450 let table = Table::new();
451 assert_eq!(
452 table.check_write(EP, THERMOSTAT, Some(alice()), HEAT),
453 Err(Status::InvalidInState)
454 );
455 // And a session with no writer at all — a PASE or group one — never has a claim.
456 assert_eq!(
457 table.check_write(EP, THERMOSTAT, None, HEAT),
458 Err(Status::InvalidInState)
459 );
460 }
461
462 #[test]
463 fn a_second_claim_on_the_same_cluster_by_the_same_client_is_refused() {
464 // §7.15.6.4 BeginWrite step 1: one claim per client per cluster instance.
465 let mut table = Table::new();
466 table
467 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
468 .expect("begin");
469 assert_eq!(
470 table.begin(EP, THERMOSTAT, alice(), &[COOL], timeout(), at(0)),
471 Err(Status::InvalidInState)
472 );
473 }
474
475 #[test]
476 fn an_attribute_another_client_has_claimed_is_busy() {
477 // §7.15.6.4 BeginWrite step 3(a)(iii). `BUSY` rather than a flat refusal because the
478 // client "could attempt to write to it again after a pause" — try later, not never.
479 let mut table = Table::new();
480 table
481 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
482 .expect("begin");
483 assert_eq!(
484 table.begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(0)),
485 Err(Status::Busy)
486 );
487 // A disjoint set is fine: two clients may stage different attributes at once.
488 table
489 .begin(EP, THERMOSTAT, bob(), &[COOL], timeout(), at(0))
490 .expect("a different attribute is free");
491 }
492
493 #[test]
494 fn an_empty_or_duplicated_attribute_set_is_invalid() {
495 // §7.15.6.4 rules 1 and 2. A duplicate would be committed twice, with the second
496 // write seeing the first's pending value as if it were the current one.
497 let mut table = Table::new();
498 assert_eq!(
499 table.begin(EP, THERMOSTAT, alice(), &[], timeout(), at(0)),
500 Err(Status::InvalidCommand)
501 );
502 assert_eq!(
503 table.begin(EP, THERMOSTAT, alice(), &[HEAT, HEAT], timeout(), at(0)),
504 Err(Status::InvalidCommand)
505 );
506 }
507
508 #[test]
509 fn committing_requires_the_same_set_in_any_order() {
510 // §7.15.6's Commit rule 1: the set must match "irrespective of order" — order is not
511 // meaningful, but a *different* set means the client and server disagree about what
512 // is being committed, and applying either reading would be a guess.
513 let mut table = Table::new();
514 table
515 .begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
516 .expect("begin");
517
518 assert_eq!(
519 table.finish(EP, THERMOSTAT, alice(), &[HEAT]),
520 Err(Status::InvalidInState),
521 "a subset is not the set"
522 );
523 assert_eq!(
524 table.finish(EP, THERMOSTAT, bob(), &[COOL, HEAT]),
525 Err(Status::InvalidInState),
526 "and not another client's"
527 );
528 table
529 .finish(EP, THERMOSTAT, alice(), &[COOL, HEAT])
530 .expect("the same set, reordered");
531 assert!(table.is_empty(), "the claim is released either way");
532 }
533
534 #[test]
535 fn a_claim_that_is_never_committed_lapses() {
536 // §7.15.6.4 BeginWrite step 3(e)(iii). Without it a client that crashed mid-write would
537 // hold its attributes against everyone else until the device restarted.
538 let mut table = Table::new();
539 table
540 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
541 .expect("begin");
542 assert_eq!(table.next_deadline(), Some(at(1_000)));
543
544 assert_eq!(table.reap(at(999)), 0, "not yet");
545 assert_eq!(table.reap(at(1_001)), 1, "lapsed");
546 assert!(table.is_empty());
547
548 // ...and the attribute is free for somebody else.
549 table
550 .begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(1_001))
551 .expect("no longer held");
552 }
553
554 #[test]
555 fn only_an_operational_node_on_a_fabric_can_hold_a_claim() {
556 // §7.15.2: the writer is the session's Peer Node ID, and "an Atomic Writer ID that is
557 // not a valid Operational Node ID SHALL be invalid". A PASE session has no
558 // operational identity, so it can stage nothing.
559 let mut ctx = InteractionContext::new();
560 assert_eq!(Writer::from_context(&ctx), None, "no peer at all");
561
562 ctx.peer_node_id = Some(NodeId(0x0000_0000_0000_1111));
563 assert_eq!(Writer::from_context(&ctx), None, "no accessing fabric");
564
565 ctx.fabric_index = Some(FabricIndex(1));
566 assert_eq!(
567 Writer::from_context(&ctx),
568 Some(alice()),
569 "a CASE session on a fabric"
570 );
571
572 // A group node id is not operational, so it can never be a writer.
573 ctx.peer_node_id = Some(NodeId(0xFFFF_FFFF_FFFF_0001));
574 assert_eq!(Writer::from_context(&ctx), None);
575 }
576
577 #[test]
578 fn removing_a_fabric_releases_its_claims() {
579 let mut table = Table::new();
580 table
581 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
582 .expect("begin");
583 let other_fabric = Writer {
584 node: NodeId(0x0000_0000_0000_3333),
585 fabric: FabricIndex(2),
586 };
587 table
588 .begin(EP, THERMOSTAT, other_fabric, &[COOL], timeout(), at(0))
589 .expect("begin");
590
591 assert_eq!(table.remove_fabric(FabricIndex(1)), 1);
592 assert_eq!(table.len(), 1);
593 assert!(table.find(EP, THERMOSTAT, other_fabric).is_some());
594 }
595
596 #[test]
597 fn the_same_node_id_on_two_fabrics_is_two_clients() {
598 // §7.15.3 keys a state on the fabric as well as the writer. Letting one inherit the
599 // other's claim would let a second administrator commit writes the first had staged.
600 let mut table = Table::new();
601 let on_one = alice();
602 let on_two = Writer {
603 node: on_one.node,
604 fabric: FabricIndex(2),
605 };
606 table
607 .begin(EP, THERMOSTAT, on_one, &[HEAT], timeout(), at(0))
608 .expect("begin");
609 assert_eq!(
610 table.check_write(EP, THERMOSTAT, Some(on_two), HEAT),
611 Err(Status::InvalidInState)
612 );
613 }
614}