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.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.3.a asks for are the *cluster's* to produce — only
206 /// it knows whether an attribute supports atomic writes or whether it has room to pend a
207 /// 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.3.1);
211 /// * an attribute another client is already using is [`Status::Busy`]
212 /// (§7.15.6.4.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.3.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.3.a.iii: "If the specified attribute is currently being used by a
246 // 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.3.e.iii).
355 ///
356 /// > If the server does not receive a matching AtomicRequest with a RequestType of
357 /// > CommitWrite from the associated client before the timeout … the server SHALL roll
358 /// > back any pending writes and discard the atomic write.
359 ///
360 /// Without this a client that crashed mid-write would hold its attributes against every
361 /// other client until the device was restarted.
362 pub fn reap(&mut self, now: Instant) -> usize {
363 let before = self.claims.len();
364 self.claims.retain(|claim| claim.deadline > now);
365 before.saturating_sub(self.claims.len())
366 }
367
368 /// Drops every claim a fabric holds — what `RemoveFabric` must do.
369 pub fn remove_fabric(&mut self, fabric: FabricIndex) -> usize {
370 let before = self.claims.len();
371 self.claims.retain(|claim| claim.writer.fabric != fabric);
372 before.saturating_sub(self.claims.len())
373 }
374
375 /// When [`AtomicWrites::reap`] next has something to do.
376 #[must_use]
377 pub fn next_deadline(&self) -> Option<Instant> {
378 self.claims.iter().map(|c| c.deadline).min()
379 }
380}
381
382/// Whether two attribute sets are equal "irrespective of order" (§7.15.6's Commit rule 1).
383fn same_set(held: &[AttributeId], asked: &[AttributeId]) -> bool {
384 held.len() == asked.len() && held.iter().all(|id| asked.contains(id))
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390 use crate::config::DefaultConfig;
391
392 type Table = AtomicWrites<DefaultConfig, 4, 4>;
393
394 const EP: EndpointId = 1;
395 const THERMOSTAT: ClusterId = 0x0201;
396 const HEAT: AttributeId = 0x0012;
397 const COOL: AttributeId = 0x0011;
398
399 fn alice() -> Writer {
400 Writer {
401 node: NodeId(0x0000_0000_0000_1111),
402 fabric: FabricIndex(1),
403 }
404 }
405
406 fn bob() -> Writer {
407 Writer {
408 node: NodeId(0x0000_0000_0000_2222),
409 fabric: FabricIndex(1),
410 }
411 }
412
413 fn at(ms: u64) -> Instant {
414 Instant::from_micros(ms.saturating_mul(1000))
415 }
416
417 fn timeout() -> Duration {
418 Duration::from_millis(1_000)
419 }
420
421 #[test]
422 fn a_claim_covers_its_attributes_and_only_its_own_client() {
423 let mut table = Table::new();
424 table
425 .begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
426 .expect("begin");
427
428 assert!(
429 table
430 .check_write(EP, THERMOSTAT, Some(alice()), HEAT)
431 .is_ok()
432 );
433 // Somebody else's claim is not a licence to write into it.
434 assert_eq!(
435 table.check_write(EP, THERMOSTAT, Some(bob()), HEAT),
436 Err(Status::InvalidInState)
437 );
438 // Nor is an attribute the claim does not cover.
439 assert_eq!(
440 table.check_write(EP, THERMOSTAT, Some(alice()), 0x0099),
441 Err(Status::InvalidInState)
442 );
443 }
444
445 #[test]
446 fn writing_an_atomic_attribute_with_no_claim_is_invalid_in_state() {
447 // §7.15.3: an attribute with the Atomic quality is writable only inside a claim, so a
448 // client that skipped BeginWrite is told so rather than having its write applied.
449 let table = Table::new();
450 assert_eq!(
451 table.check_write(EP, THERMOSTAT, Some(alice()), HEAT),
452 Err(Status::InvalidInState)
453 );
454 // And a session with no writer at all — a PASE or group one — never has a claim.
455 assert_eq!(
456 table.check_write(EP, THERMOSTAT, None, HEAT),
457 Err(Status::InvalidInState)
458 );
459 }
460
461 #[test]
462 fn a_second_claim_on_the_same_cluster_by_the_same_client_is_refused() {
463 // §7.15.6.4.3.1: one claim per client per cluster instance.
464 let mut table = Table::new();
465 table
466 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
467 .expect("begin");
468 assert_eq!(
469 table.begin(EP, THERMOSTAT, alice(), &[COOL], timeout(), at(0)),
470 Err(Status::InvalidInState)
471 );
472 }
473
474 #[test]
475 fn an_attribute_another_client_has_claimed_is_busy() {
476 // §7.15.6.4.3.a.iii. `BUSY` rather than a flat refusal because the client "could
477 // attempt to write to it again after a pause" — it says *try later*, not *never*.
478 let mut table = Table::new();
479 table
480 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
481 .expect("begin");
482 assert_eq!(
483 table.begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(0)),
484 Err(Status::Busy)
485 );
486 // A disjoint set is fine: two clients may stage different attributes at once.
487 table
488 .begin(EP, THERMOSTAT, bob(), &[COOL], timeout(), at(0))
489 .expect("a different attribute is free");
490 }
491
492 #[test]
493 fn an_empty_or_duplicated_attribute_set_is_invalid() {
494 // §7.15.6.4 rules 1 and 2. A duplicate would be committed twice, with the second
495 // write seeing the first's pending value as if it were the current one.
496 let mut table = Table::new();
497 assert_eq!(
498 table.begin(EP, THERMOSTAT, alice(), &[], timeout(), at(0)),
499 Err(Status::InvalidCommand)
500 );
501 assert_eq!(
502 table.begin(EP, THERMOSTAT, alice(), &[HEAT, HEAT], timeout(), at(0)),
503 Err(Status::InvalidCommand)
504 );
505 }
506
507 #[test]
508 fn committing_requires_the_same_set_in_any_order() {
509 // §7.15.6's Commit rule 1: the set must match "irrespective of order" — order is not
510 // meaningful, but a *different* set means the client and server disagree about what
511 // is being committed, and applying either reading would be a guess.
512 let mut table = Table::new();
513 table
514 .begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
515 .expect("begin");
516
517 assert_eq!(
518 table.finish(EP, THERMOSTAT, alice(), &[HEAT]),
519 Err(Status::InvalidInState),
520 "a subset is not the set"
521 );
522 assert_eq!(
523 table.finish(EP, THERMOSTAT, bob(), &[COOL, HEAT]),
524 Err(Status::InvalidInState),
525 "and not another client's"
526 );
527 table
528 .finish(EP, THERMOSTAT, alice(), &[COOL, HEAT])
529 .expect("the same set, reordered");
530 assert!(table.is_empty(), "the claim is released either way");
531 }
532
533 #[test]
534 fn a_claim_that_is_never_committed_lapses() {
535 // §7.15.6.4.3.e.iii. Without it a client that crashed mid-write would hold its
536 // attributes against everyone else until the device restarted.
537 let mut table = Table::new();
538 table
539 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
540 .expect("begin");
541 assert_eq!(table.next_deadline(), Some(at(1_000)));
542
543 assert_eq!(table.reap(at(999)), 0, "not yet");
544 assert_eq!(table.reap(at(1_001)), 1, "lapsed");
545 assert!(table.is_empty());
546
547 // ...and the attribute is free for somebody else.
548 table
549 .begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(1_001))
550 .expect("no longer held");
551 }
552
553 #[test]
554 fn only_an_operational_node_on_a_fabric_can_hold_a_claim() {
555 // §7.15.2: the writer is the session's Peer Node ID, and "an Atomic Writer ID that is
556 // not a valid Operational Node ID SHALL be invalid". A PASE session has no
557 // operational identity, so it can stage nothing.
558 let mut ctx = InteractionContext::new();
559 assert_eq!(Writer::from_context(&ctx), None, "no peer at all");
560
561 ctx.peer_node_id = Some(NodeId(0x0000_0000_0000_1111));
562 assert_eq!(Writer::from_context(&ctx), None, "no accessing fabric");
563
564 ctx.fabric_index = Some(FabricIndex(1));
565 assert_eq!(
566 Writer::from_context(&ctx),
567 Some(alice()),
568 "a CASE session on a fabric"
569 );
570
571 // A group node id is not operational, so it can never be a writer.
572 ctx.peer_node_id = Some(NodeId(0xFFFF_FFFF_FFFF_0001));
573 assert_eq!(Writer::from_context(&ctx), None);
574 }
575
576 #[test]
577 fn removing_a_fabric_releases_its_claims() {
578 let mut table = Table::new();
579 table
580 .begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
581 .expect("begin");
582 let other_fabric = Writer {
583 node: NodeId(0x0000_0000_0000_3333),
584 fabric: FabricIndex(2),
585 };
586 table
587 .begin(EP, THERMOSTAT, other_fabric, &[COOL], timeout(), at(0))
588 .expect("begin");
589
590 assert_eq!(table.remove_fabric(FabricIndex(1)), 1);
591 assert_eq!(table.len(), 1);
592 assert!(table.find(EP, THERMOSTAT, other_fabric).is_some());
593 }
594
595 #[test]
596 fn the_same_node_id_on_two_fabrics_is_two_clients() {
597 // §7.15.3 keys a state on the fabric as well as the writer. Letting one inherit the
598 // other's claim would let a second administrator commit writes the first had staged.
599 let mut table = Table::new();
600 let on_one = alice();
601 let on_two = Writer {
602 node: on_one.node,
603 fabric: FabricIndex(2),
604 };
605 table
606 .begin(EP, THERMOSTAT, on_one, &[HEAT], timeout(), at(0))
607 .expect("begin");
608 assert_eq!(
609 table.check_write(EP, THERMOSTAT, Some(on_two), HEAT),
610 Err(Status::InvalidInState)
611 );
612 }
613}