Skip to main content

matter_kit/clusters/
joint_fabric_datastore.rs

1//! Joint Fabric Datastore, cluster `0x0752` (Core §11.24).
2//!
3//! What every administrator of a Joint Fabric agrees is on it. Several ecosystems share one
4//! fabric (ch. 12), so "which nodes exist, which groups they are in, what keys they hold and who
5//! may reach them" cannot live in any one ecosystem's cloud — and §11.24 is the shared copy.
6//!
7//! # Two phases, and the second one is the point
8//!
9//! §11.24.4.1 is the rule the whole cluster is shaped around:
10//!
11//! > before completing the commissioning process, the Commissioner SHALL invoke the
12//! > AddPendingNode command … After completion of commissioning and associated configuration,
13//! > the Commissioner SHALL invoke the RefreshNode command … By performing this work in two
14//! > steps (first pending status, then committed status), the design can prevent error scenarios
15//! > where a node is brought onto a fabric without appearing in the Datastore.
16//!
17//! A node that commissioned successfully but never reached the datastore would be invisible to
18//! every *other* ecosystem on the fabric — reachable, administrable, and unknown. Recording it
19//! first and committing after means the failure mode is a `Pending` entry somebody can clean up,
20//! rather than a device nobody can see.
21//!
22//! [`DatastoreStateEnum`] is that state, and §11.24.4.3 has the datastore "periodically review
23//! its data in a Pending and PendingDeletion state and attempt to reach the corresponding Node".
24//!
25//! # Nothing is removed while something still refers to it
26//!
27//! §11.24.7.3 and §11.24.7.6 are the same rule twice: a key set a node still holds, or a group a
28//! node is still in, cannot be removed — `CONSTRAINT_ERROR`. The exception is an entry already
29//! marked `DeletePending`, which is a removal in progress rather than a live reference.
30//!
31//! Without it, removing a group would leave nodes holding a group key for a group that no longer
32//! exists, and the datastore would no longer describe the fabric it is the description of.
33
34use core::cell::RefCell;
35
36use heapless::{String, Vec};
37
38use crate::clusters::generated::joint_fabric_datastore as spec_ds;
39use crate::dm::spec::{Conforming, Optional};
40use crate::dm::{Resolved, ResolvedCommand};
41use crate::im::{
42    ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb,
43};
44use crate::msg::{CaseAuthenticatedTag, GroupId, NodeId, VendorId};
45use crate::tlv::{Tag, TlvWriter};
46
47use super::Cluster;
48
49pub use spec_ds::attribute::{
50    ADMIN_LIST, ANCHOR_NODE_ID, ANCHOR_ROOT_CA, ANCHOR_VENDOR_ID, ENDPOINT_BINDING_LIST,
51    ENDPOINT_GROUP_ID_LIST, FRIENDLY_NAME, GROUP_KEY_SET_LIST, GROUP_LIST, NODE_ACL_LIST,
52    NODE_ENDPOINT_LIST, NODE_KEY_SET_LIST, NODE_LIST, STATUS,
53};
54pub use spec_ds::command::{
55    ADD_ACL_TO_NODE, ADD_ADMIN, ADD_BINDING_TO_ENDPOINT_FOR_NODE, ADD_GROUP,
56    ADD_GROUP_ID_TO_ENDPOINT_FOR_NODE, ADD_KEY_SET, ADD_PENDING_NODE, REFRESH_NODE,
57    REMOVE_ACL_FROM_NODE, REMOVE_ADMIN, REMOVE_BINDING_FROM_ENDPOINT_FOR_NODE, REMOVE_GROUP,
58    REMOVE_GROUP_ID_FROM_ENDPOINT_FOR_NODE, REMOVE_KEY_SET, REMOVE_NODE, UPDATE_ADMIN,
59    UPDATE_ENDPOINT_FOR_NODE, UPDATE_GROUP, UPDATE_KEY_SET, UPDATE_NODE,
60};
61pub use spec_ds::{
62    DatastoreAccessControlEntryPrivilegeEnum, DatastoreStateEnum, ID, PICS, REVISION,
63};
64
65/// §11.24.5's constraint on every `FriendlyName`: "max 32".
66pub const FRIENDLY_NAME_MAX: usize = 32;
67
68/// §11.24.7.3: "Attempt to remove the IPK, which has GroupKeySetID of 0, SHALL fail with
69/// response CONSTRAINT_ERROR."
70pub const IPK_KEY_SET: u16 = 0;
71
72/// §11.24.7.4's constraint on `GroupCAT`: "GroupCAT values SHALL fall within the range 1 to
73/// 65534", which excludes the Joint Fabric's own two reserved identifiers.
74pub const GROUP_CAT_MIN: u16 = 1;
75/// The other end of it.
76pub const GROUP_CAT_MAX: u16 = 65534;
77
78/// A name short enough for §11.24.5's "max 32".
79pub type FriendlyName = String<FRIENDLY_NAME_MAX>;
80
81/// §11.24.5.2's `DatastoreStatusEntryStruct`: where one managed thing has got to.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct StatusEntry {
84    /// "the current state of the target device operation".
85    pub state: DatastoreStateEnum,
86    /// "the timestamp of the last update", in UTC seconds.
87    pub updated_at: u32,
88    /// "the Status Code of the last failed operation where the State field is set to
89    /// CommitFailure".
90    pub failure: Option<Status>,
91}
92
93impl StatusEntry {
94    /// A freshly recorded, not-yet-applied change (§11.24.4.1).
95    #[must_use]
96    pub const fn pending(now: u32) -> Self {
97        Self {
98            state: DatastoreStateEnum::Pending,
99            updated_at: now,
100            failure: None,
101        }
102    }
103
104    /// Whether this entry still refers to something.
105    ///
106    /// §11.24.7.3 and §11.24.7.6 both exempt `DeletePending`: a reference on its way out is not
107    /// one that blocks a removal, or the two halves of a removal would deadlock each other.
108    #[must_use]
109    pub const fn is_live(&self) -> bool {
110        !matches!(self.state, DatastoreStateEnum::DeletePending)
111    }
112}
113
114/// One node the datastore knows about (§11.24.5.14).
115#[derive(Debug, Clone)]
116pub struct NodeEntry {
117    /// Its Node ID on the Joint Fabric.
118    pub node: NodeId,
119    /// "the friendly name for the node".
120    pub friendly_name: FriendlyName,
121    /// Where its commissioning has got to — §11.24.4.1's two phases.
122    pub commissioning: StatusEntry,
123}
124
125/// One group (§11.24.5.5's `DatastoreGroupInformationEntryStruct`).
126#[derive(Debug, Clone)]
127pub struct GroupEntry {
128    /// Its Group ID.
129    pub group: GroupId,
130    /// "the friendly name for the group".
131    pub friendly_name: FriendlyName,
132    /// Which key set secures it.
133    pub key_set: Option<u16>,
134    /// "the CAT value for this group", 1 to 65534.
135    pub cat: Option<u16>,
136    /// "the current version number for this CAT".
137    pub cat_version: Option<u16>,
138    /// "the permission level associated with ACL entries for this group".
139    pub permission: DatastoreAccessControlEntryPrivilegeEnum,
140}
141
142/// One administrator node (§11.24.7.7).
143#[derive(Debug, Clone)]
144pub struct AdminEntry {
145    /// Its Node ID.
146    pub node: NodeId,
147    /// Its friendly name.
148    pub friendly_name: FriendlyName,
149    /// "the Vendor ID for the admin node", which is what a user is shown when an ecosystem
150    /// joins (§12.2.5 step 4d).
151    pub vendor: VendorId,
152    /// Its ICAC, cross-signed by the anchor. §11.24.7.7 caps it at 400 octets, which is the
153    /// Matter certificate encoding's own limit.
154    pub icac_len: usize,
155}
156
157/// One `(node, key set)` association (§11.24.5.3).
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub struct NodeKeySet {
160    /// The node holding it.
161    pub node: NodeId,
162    /// The key set it holds.
163    pub key_set: u16,
164    /// Whether it is applied, pending, or on its way out.
165    pub status: StatusEntry,
166}
167
168/// One `(node, endpoint, group)` membership (§11.24.5.9).
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct EndpointGroup {
171    /// The node.
172    pub node: NodeId,
173    /// The endpoint on it.
174    pub endpoint: EndpointId,
175    /// The group that endpoint is in.
176    pub group: GroupId,
177    /// Whether it is applied, pending, or on its way out.
178    pub status: StatusEntry,
179}
180
181/// The Joint Fabric Datastore's tables (§11.24.6).
182///
183/// `N`, `G`, `K`, `A` and `M` size the node, group, key-set, administrator and membership lists.
184/// §11.24.4 says what a full one does: "The RESOURCE_EXHAUSTED error MAY be used by the
185/// Datastore to indicate that a storage capacity limit … has been reached and SHALL notify the
186/// user of this condition using proprietary means outside of this specification."
187#[derive(Debug)]
188pub struct Datastore<const N: usize, const G: usize, const K: usize, const A: usize, const M: usize>
189{
190    nodes: Vec<NodeEntry, N>,
191    groups: Vec<GroupEntry, G>,
192    key_sets: Vec<u16, K>,
193    admins: Vec<AdminEntry, A>,
194    node_key_sets: Vec<NodeKeySet, M>,
195    endpoint_groups: Vec<EndpointGroup, M>,
196    anchor: Option<(NodeId, VendorId)>,
197    friendly_name: FriendlyName,
198}
199
200impl<const N: usize, const G: usize, const K: usize, const A: usize, const M: usize> Default
201    for Datastore<N, G, K, A, M>
202{
203    fn default() -> Self {
204        Self::new()
205    }
206}
207
208impl<const N: usize, const G: usize, const K: usize, const A: usize, const M: usize>
209    Datastore<N, G, K, A, M>
210{
211    /// An empty datastore.
212    #[must_use]
213    pub const fn new() -> Self {
214        Self {
215            nodes: Vec::new(),
216            groups: Vec::new(),
217            key_sets: Vec::new(),
218            admins: Vec::new(),
219            node_key_sets: Vec::new(),
220            endpoint_groups: Vec::new(),
221            anchor: None,
222            friendly_name: String::new(),
223        }
224    }
225
226    /// `AnchorNodeID` and `AnchorVendorID` (§11.24.6), and the fabric's own name.
227    pub fn set_anchor(&mut self, node: NodeId, vendor: VendorId, name: &str) -> Result<(), Status> {
228        self.anchor = Some((node, vendor));
229        self.friendly_name = FriendlyName::try_from(name).map_err(|_| Status::ConstraintError)?;
230        Ok(())
231    }
232
233    /// The anchor, if one has been recorded.
234    #[must_use]
235    pub const fn anchor(&self) -> Option<(NodeId, VendorId)> {
236        self.anchor
237    }
238
239    /// `NodeList` (§11.24.6).
240    #[must_use]
241    pub fn nodes(&self) -> &[NodeEntry] {
242        &self.nodes
243    }
244
245    /// `GroupList` (§11.24.6).
246    #[must_use]
247    pub fn groups(&self) -> &[GroupEntry] {
248        &self.groups
249    }
250
251    /// `AdminList` (§11.24.6).
252    #[must_use]
253    pub fn admins(&self) -> &[AdminEntry] {
254        &self.admins
255    }
256
257    /// `GroupKeySetList` (§11.24.6) — the ids, since the keys themselves are §11.2's.
258    #[must_use]
259    pub fn key_sets(&self) -> &[u16] {
260        &self.key_sets
261    }
262
263    /// `NodeKeySetList` (§11.24.6).
264    #[must_use]
265    pub fn node_key_sets(&self) -> &[NodeKeySet] {
266        &self.node_key_sets
267    }
268
269    /// `EndpointGroupIDList` (§11.24.6).
270    #[must_use]
271    pub fn endpoint_groups(&self) -> &[EndpointGroup] {
272        &self.endpoint_groups
273    }
274
275    /// §11.24.7.1's `AddKeySet`.
276    pub fn add_key_set(&mut self, key_set: u16) -> Result<(), Status> {
277        // "Ensure there are no KeySets in the KeySetList attribute with the given
278        // GroupKeySetID. If a match is found, then this command SHALL fail with a
279        // CONSTRAINT_ERROR status code."
280        if self.key_sets.contains(&key_set) {
281            return Err(Status::ConstraintError);
282        }
283        self.key_sets
284            .push(key_set)
285            .map_err(|_| Status::ResourceExhausted)
286    }
287
288    /// §11.24.7.3's `RemoveKeySet`.
289    pub fn remove_key_set(&mut self, key_set: u16) -> Result<(), Status> {
290        // "Attempt to remove the IPK, which has GroupKeySetID of 0, SHALL fail with response
291        // CONSTRAINT_ERROR." The IPK is the fabric's own identity key; a datastore that let it
292        // be removed would be describing a fabric nothing could CASE into.
293        if key_set == IPK_KEY_SET {
294            return Err(Status::ConstraintError);
295        }
296        if !self.key_sets.contains(&key_set) {
297            return Err(Status::NotFound);
298        }
299        // Step 2: "If the NodeKeySetList list contains an entry with the given GroupKeySetID,
300        // and the entry does NOT have Status DeletePending, then this command SHALL fail."
301        if self
302            .node_key_sets
303            .iter()
304            .any(|entry| entry.key_set == key_set && entry.status.is_live())
305        {
306            return Err(Status::ConstraintError);
307        }
308        self.key_sets.retain(|id| *id != key_set);
309        Ok(())
310    }
311
312    /// §11.24.7.4's `AddGroup`.
313    pub fn add_group(&mut self, entry: GroupEntry) -> Result<(), Status> {
314        // "GroupCAT values SHALL fall within the range 1 to 65534" *and* "Attempts to add a
315        // group with a GroupCAT value of Administrator CAT or Anchor CAT SHALL fail with
316        // CONSTRAINT_ERROR."
317        //
318        // Two rules, and the second is not implied by the first: the Administrator CAT is
319        // `0xFFFF`, which the range already excludes — but the Anchor CAT is `0xFFFE`, which is
320        // the *top of the range*. A check that tested only the bounds would let a group claim
321        // the identifier that grants Administer on every administrator of the Joint Fabric.
322        if let Some(cat) = entry.cat
323            && (!(GROUP_CAT_MIN..=GROUP_CAT_MAX).contains(&cat) || is_reserved_cat(cat))
324        {
325            return Err(Status::ConstraintError);
326        }
327        if self.groups.iter().any(|g| g.group == entry.group) {
328            return Err(Status::ConstraintError);
329        }
330        // A group keyed to a key set the datastore does not have describes nothing.
331        if let Some(key_set) = entry.key_set
332            && !self.key_sets.contains(&key_set)
333        {
334            return Err(Status::NotFound);
335        }
336        self.groups
337            .push(entry)
338            .map_err(|_| Status::ResourceExhausted)
339    }
340
341    /// §11.24.7.6's `RemoveGroup`.
342    pub fn remove_group(&mut self, group: GroupId) -> Result<(), Status> {
343        let Some(entry) = self.groups.iter().find(|g| g.group == group) else {
344            return Err(Status::NotFound);
345        };
346        // "Attempts to remove a group with GroupCAT value set to Administrator CAT or Anchor CAT
347        // SHALL fail with CONSTRAINT_ERROR." A datastore that had one anyway — from an earlier
348        // revision, or a peer that did not check — must not be the thing that removes it.
349        if entry.cat.is_some_and(is_reserved_cat) {
350            return Err(Status::ConstraintError);
351        }
352        // Step 2: a group with live members is not empty, and removing it would leave those
353        // nodes holding a key for a group that no longer exists.
354        if self
355            .endpoint_groups
356            .iter()
357            .any(|m| m.group == group && m.status.is_live())
358        {
359            return Err(Status::ConstraintError);
360        }
361        self.groups.retain(|g| g.group != group);
362        Ok(())
363    }
364
365    /// §11.24.7.10's `AddPendingNode` — the first half of §11.24.4.1's two-step.
366    pub fn add_pending_node(
367        &mut self,
368        node: NodeId,
369        friendly_name: &str,
370        now: u32,
371    ) -> Result<(), Status> {
372        // "If a DatastoreNodeInformationEntryStruct exists for the given NodeID, then this
373        // command SHALL fail with a INVALID_CONSTRAINT status code."
374        if self.nodes.iter().any(|n| n.node == node) {
375            return Err(Status::ConstraintError);
376        }
377        let friendly_name =
378            FriendlyName::try_from(friendly_name).map_err(|_| Status::ConstraintError)?;
379        self.nodes
380            .push(NodeEntry {
381                node,
382                friendly_name,
383                // "set the status … to Pending": the node is in the datastore before it is on
384                // the fabric, which is the point of doing it in two steps.
385                commissioning: StatusEntry::pending(now),
386            })
387            .map_err(|_| Status::ResourceExhausted)
388    }
389
390    /// §11.24.7.11's `RefreshNode` — the second half.
391    ///
392    /// The specification has the datastore *read* the node's endpoints here and reconcile them.
393    /// That is an interaction with the node, which this table cannot make; what it does is what
394    /// §11.24.7.11 steps 1 and 2 say, and the caller supplies the outcome.
395    pub fn refresh_node(&mut self, node: NodeId, now: u32) -> Result<(), Status> {
396        let Some(entry) = self.nodes.iter_mut().find(|n| n.node == node) else {
397            // Step 1: "if not, then this command SHALL fail with a NOT_FOUND status code."
398            return Err(Status::NotFound);
399        };
400        // Step 2: "Update the CommissioningStatusEntry … to Pending" — the refresh is itself an
401        // operation that can fail, so it starts pending and the caller commits it.
402        entry.commissioning = StatusEntry::pending(now);
403        Ok(())
404    }
405
406    /// Records the outcome of a refresh (§11.24.7.11 steps 3 onwards).
407    ///
408    /// `Ok` commits the entry; an error records `CommitFailed` and the status, which
409    /// §11.24.4.3's periodic review is what retries.
410    pub fn node_refreshed(&mut self, node: NodeId, outcome: Result<(), Status>, now: u32) {
411        if let Some(entry) = self.nodes.iter_mut().find(|n| n.node == node) {
412            entry.commissioning = match outcome {
413                Ok(()) => StatusEntry {
414                    state: DatastoreStateEnum::Committed,
415                    updated_at: now,
416                    failure: None,
417                },
418                Err(status) => StatusEntry {
419                    state: DatastoreStateEnum::CommitFailed,
420                    updated_at: now,
421                    failure: Some(status),
422                },
423            };
424        }
425    }
426
427    /// §11.24.7.13's `RemoveNode`.
428    pub fn remove_node(&mut self, node: NodeId) -> Result<(), Status> {
429        if !self.nodes.iter().any(|n| n.node == node) {
430            return Err(Status::NotFound);
431        }
432        self.nodes.retain(|n| n.node != node);
433        // Everything hanging off the node goes with it: leaving a membership behind would make
434        // §11.24.7.6's "ensure there are no Nodes in this group" true of a node that is gone,
435        // and the group could never be removed.
436        self.node_key_sets.retain(|e| e.node != node);
437        self.endpoint_groups.retain(|e| e.node != node);
438        Ok(())
439    }
440
441    /// §11.24.7.7's `AddAdmin`.
442    pub fn add_admin(&mut self, entry: AdminEntry) -> Result<(), Status> {
443        if self.admins.iter().any(|a| a.node == entry.node) {
444            return Err(Status::ConstraintError);
445        }
446        self.admins
447            .push(entry)
448            .map_err(|_| Status::ResourceExhausted)
449    }
450
451    /// §11.24.7.9's `RemoveAdmin`.
452    pub fn remove_admin(&mut self, node: NodeId) -> Result<(), Status> {
453        if !self.admins.iter().any(|a| a.node == node) {
454            return Err(Status::NotFound);
455        }
456        self.admins.retain(|a| a.node != node);
457        Ok(())
458    }
459
460    /// Associates a key set with a node, pending application (§11.24.5.3).
461    pub fn add_node_key_set(&mut self, node: NodeId, key_set: u16, now: u32) -> Result<(), Status> {
462        if !self.nodes.iter().any(|n| n.node == node) {
463            return Err(Status::NotFound);
464        }
465        if !self.key_sets.contains(&key_set) {
466            return Err(Status::NotFound);
467        }
468        if self
469            .node_key_sets
470            .iter()
471            .any(|e| e.node == node && e.key_set == key_set)
472        {
473            return Err(Status::ConstraintError);
474        }
475        self.node_key_sets
476            .push(NodeKeySet {
477                node,
478                key_set,
479                status: StatusEntry::pending(now),
480            })
481            .map_err(|_| Status::ResourceExhausted)
482    }
483
484    /// §11.24.7.15's `AddGroupIDToEndpointForNode`.
485    pub fn add_group_to_endpoint(
486        &mut self,
487        node: NodeId,
488        endpoint: EndpointId,
489        group: GroupId,
490        now: u32,
491    ) -> Result<(), Status> {
492        if !self.nodes.iter().any(|n| n.node == node) {
493            return Err(Status::NotFound);
494        }
495        // A membership in a group the datastore does not have would be invisible to the removal
496        // check that is supposed to protect it.
497        if !self.groups.iter().any(|g| g.group == group) {
498            return Err(Status::NotFound);
499        }
500        if self
501            .endpoint_groups
502            .iter()
503            .any(|m| m.node == node && m.endpoint == endpoint && m.group == group)
504        {
505            return Err(Status::ConstraintError);
506        }
507        self.endpoint_groups
508            .push(EndpointGroup {
509                node,
510                endpoint,
511                group,
512                status: StatusEntry::pending(now),
513            })
514            .map_err(|_| Status::ResourceExhausted)
515    }
516
517    /// §11.24.7.16's `RemoveGroupIDFromEndpointForNode`.
518    ///
519    /// The removal is *marked*, not done: §11.24.4.3 has the datastore reach the node to apply
520    /// it, and until it has, the membership is `DeletePending` — which §11.24.7.6 then stops
521    /// treating as a live reference.
522    pub fn remove_group_from_endpoint(
523        &mut self,
524        node: NodeId,
525        endpoint: EndpointId,
526        group: GroupId,
527        now: u32,
528    ) -> Result<(), Status> {
529        let Some(entry) = self
530            .endpoint_groups
531            .iter_mut()
532            .find(|m| m.node == node && m.endpoint == endpoint && m.group == group)
533        else {
534            return Err(Status::NotFound);
535        };
536        entry.status = StatusEntry {
537            state: DatastoreStateEnum::DeletePending,
538            updated_at: now,
539            failure: None,
540        };
541        Ok(())
542    }
543
544    /// Applies a pending deletion, once the node has acknowledged it.
545    pub fn deletion_applied(&mut self, node: NodeId, endpoint: EndpointId, group: GroupId) {
546        self.endpoint_groups.retain(|m| {
547            !(m.node == node && m.endpoint == endpoint && m.group == group && !m.status.is_live())
548        });
549    }
550
551    /// §11.24.4.3's periodic review: everything still waiting to reach its node.
552    ///
553    /// > The Datastore SHALL periodically review its data in a Pending and PendingDeletion state
554    /// > and attempt to reach the corresponding Node in order to apply these updates.
555    ///
556    /// Returns the nodes with outstanding work, each once.
557    pub fn nodes_needing_review<const R: usize>(&self) -> Vec<NodeId, R> {
558        let mut out: Vec<NodeId, R> = Vec::new();
559        let note = |node: NodeId, out: &mut Vec<NodeId, R>| {
560            if !out.contains(&node) {
561                let _ = out.push(node);
562            }
563        };
564        for entry in &self.nodes {
565            if matches!(
566                entry.commissioning.state,
567                DatastoreStateEnum::Pending
568                    | DatastoreStateEnum::DeletePending
569                    | DatastoreStateEnum::CommitFailed
570            ) {
571                note(entry.node, &mut out);
572            }
573        }
574        for entry in &self.node_key_sets {
575            if entry.status.state != DatastoreStateEnum::Committed {
576                note(entry.node, &mut out);
577            }
578        }
579        for entry in &self.endpoint_groups {
580            if entry.status.state != DatastoreStateEnum::Committed {
581                note(entry.node, &mut out);
582            }
583        }
584        out
585    }
586}
587
588/// The Joint Fabric Datastore cluster (§11.24).
589#[derive(Debug)]
590pub struct JointFabricDatastore<
591    'a,
592    const N: usize,
593    const G: usize,
594    const K: usize,
595    const A: usize,
596    const M: usize,
597> {
598    store: &'a RefCell<Datastore<N, G, K, A, M>>,
599}
600
601impl<'a, const N: usize, const G: usize, const K: usize, const A: usize, const M: usize>
602    JointFabricDatastore<'a, N, G, K, A, M>
603{
604    /// A cluster over a datastore.
605    #[must_use]
606    pub const fn new(store: &'a RefCell<Datastore<N, G, K, A, M>>) -> Self {
607        Self { store }
608    }
609
610    /// The descriptor for an instance, derived from the specification's tables.
611    pub fn conforming(
612        feature_map: u32,
613        optional: &Optional<'_>,
614    ) -> crate::error::Result<Conforming<14, 20, 0, 0>> {
615        Conforming::new(&spec_ds::CLUSTER, feature_map, optional)
616    }
617
618    /// The tables this cluster serves.
619    #[must_use]
620    pub const fn store(&self) -> &'a RefCell<Datastore<N, G, K, A, M>> {
621        self.store
622    }
623}
624
625impl<const N: usize, const G: usize, const K: usize, const A: usize, const M: usize> ClusterHandler
626    for JointFabricDatastore<'_, N, G, K, A, M>
627{
628    fn read(
629        &self,
630        resolved: &Resolved<'_>,
631        _ctx: &InteractionContext<'_>,
632        w: &mut TlvWriter<'_>,
633        tag: Tag,
634    ) -> Result<(), Status> {
635        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
636        let store = self.store.borrow();
637        match resolved.attribute {
638            ANCHOR_NODE_ID => match store.anchor() {
639                Some((node, _)) => full(w.unsigned(tag, node.0)),
640                None => full(w.null(tag)),
641            },
642            ANCHOR_VENDOR_ID => match store.anchor() {
643                Some((_, vendor)) => full(w.unsigned(tag, u64::from(vendor.0))),
644                None => full(w.null(tag)),
645            },
646            FRIENDLY_NAME => full(w.utf8(tag, &store.friendly_name)),
647            GROUP_KEY_SET_LIST => {
648                full(w.start_array(tag))?;
649                for key_set in store.key_sets() {
650                    full(w.start_structure(Tag::Anonymous))?;
651                    full(w.unsigned(Tag::Context(0), u64::from(*key_set)))?;
652                    full(w.end_container())?;
653                }
654                full(w.end_container())
655            }
656            NODE_LIST => {
657                full(w.start_array(tag))?;
658                for entry in store.nodes() {
659                    full(w.start_structure(Tag::Anonymous))?;
660                    full(w.unsigned(Tag::Context(0), entry.node.0))?;
661                    full(w.utf8(Tag::Context(1), &entry.friendly_name))?;
662                    full(encode_status(&entry.commissioning, w, Tag::Context(2)))?;
663                    full(w.end_container())?;
664                }
665                full(w.end_container())
666            }
667            GROUP_LIST => {
668                full(w.start_array(tag))?;
669                for entry in store.groups() {
670                    full(w.start_structure(Tag::Anonymous))?;
671                    full(w.unsigned(Tag::Context(0), u64::from(entry.group.0)))?;
672                    full(w.utf8(Tag::Context(1), &entry.friendly_name))?;
673                    match entry.key_set {
674                        Some(key_set) => full(w.unsigned(Tag::Context(2), u64::from(key_set)))?,
675                        None => full(w.null(Tag::Context(2)))?,
676                    }
677                    match entry.cat {
678                        Some(cat) => full(w.unsigned(Tag::Context(3), u64::from(cat)))?,
679                        None => full(w.null(Tag::Context(3)))?,
680                    }
681                    match entry.cat_version {
682                        Some(v) => full(w.unsigned(Tag::Context(4), u64::from(v)))?,
683                        None => full(w.null(Tag::Context(4)))?,
684                    }
685                    full(w.unsigned(Tag::Context(5), u64::from(entry.permission.value())))?;
686                    full(w.end_container())?;
687                }
688                full(w.end_container())
689            }
690            ADMIN_LIST => {
691                full(w.start_array(tag))?;
692                for entry in store.admins() {
693                    full(w.start_structure(Tag::Anonymous))?;
694                    full(w.unsigned(Tag::Context(0), entry.node.0))?;
695                    full(w.utf8(Tag::Context(1), &entry.friendly_name))?;
696                    full(w.unsigned(Tag::Context(2), u64::from(entry.vendor.0)))?;
697                    full(w.end_container())?;
698                }
699                full(w.end_container())
700            }
701            NODE_KEY_SET_LIST => {
702                full(w.start_array(tag))?;
703                for entry in store.node_key_sets() {
704                    full(w.start_structure(Tag::Anonymous))?;
705                    full(w.unsigned(Tag::Context(0), entry.node.0))?;
706                    full(w.unsigned(Tag::Context(1), u64::from(entry.key_set)))?;
707                    full(encode_status(&entry.status, w, Tag::Context(2)))?;
708                    full(w.end_container())?;
709                }
710                full(w.end_container())
711            }
712            ENDPOINT_GROUP_ID_LIST => {
713                full(w.start_array(tag))?;
714                for entry in store.endpoint_groups() {
715                    full(w.start_structure(Tag::Anonymous))?;
716                    full(w.unsigned(Tag::Context(0), entry.node.0))?;
717                    full(w.unsigned(Tag::Context(1), u64::from(entry.endpoint)))?;
718                    full(w.unsigned(Tag::Context(2), u64::from(entry.group.0)))?;
719                    full(encode_status(&entry.status, w, Tag::Context(3)))?;
720                    full(w.end_container())?;
721                }
722                full(w.end_container())
723            }
724            _ => Err(Status::UnsupportedAttribute),
725        }
726    }
727
728    fn invoke(
729        &self,
730        resolved: &ResolvedCommand<'_>,
731        fields: Option<&[u8]>,
732        ctx: &InteractionContext<'_>,
733        _w: &mut TlvWriter<'_>,
734        _tag: Tag,
735    ) -> Result<Option<CommandId>, StatusIb> {
736        // §11.24.7's commands all act "of the accessing fabric": on a Joint Fabric there is one,
737        // and a command with none has no datastore to address.
738        if ctx.fabric_index.filter(|f| f.0 != 0).is_none() {
739            return Err(Status::UnsupportedAccess.into());
740        }
741        let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
742        // The datastore's clock is the fabric's: every `StatusEntry` carries an epoch-second
743        // `UpdateTimestamp`, and §11.24.4.3's review compares against it.
744        let now = u32::try_from(ctx.now.as_micros() / 1_000_000).unwrap_or(u32::MAX);
745        let mut store = self.store.borrow_mut();
746        match resolved.command.id {
747            ADD_KEY_SET => {
748                let decoded: spec_ds::AddKeySetFields<'_> = super::decode_fields(payload)?;
749                store.add_key_set(decoded.group_key_set.group_key_set_id)?;
750            }
751            REMOVE_KEY_SET => {
752                let decoded: spec_ds::RemoveKeySetFields = super::decode_fields(payload)?;
753                store.remove_key_set(decoded.group_key_set_id)?;
754            }
755            ADD_GROUP => {
756                let decoded: spec_ds::AddGroupFields<'_> = super::decode_fields(payload)?;
757                store.add_group(GroupEntry {
758                    group: decoded.group_id,
759                    friendly_name: FriendlyName::try_from(decoded.friendly_name)
760                        .map_err(|_| StatusIb::from(Status::ConstraintError))?,
761                    key_set: decoded.group_key_set_id.0,
762                    cat: decoded.group_cat.0,
763                    cat_version: decoded.group_cat_version.0,
764                    permission: decoded.group_permission,
765                })?;
766            }
767            REMOVE_GROUP => {
768                let decoded: spec_ds::RemoveGroupFields = super::decode_fields(payload)?;
769                store.remove_group(decoded.group_id)?;
770            }
771            ADD_ADMIN => {
772                let decoded: spec_ds::AddAdminFields<'_> = super::decode_fields(payload)?;
773                store.add_admin(AdminEntry {
774                    node: decoded.node_id,
775                    friendly_name: FriendlyName::try_from(decoded.friendly_name)
776                        .map_err(|_| StatusIb::from(Status::ConstraintError))?,
777                    vendor: decoded.vendor_id,
778                    icac_len: decoded.icac.len(),
779                })?;
780            }
781            REMOVE_ADMIN => {
782                let decoded: spec_ds::RemoveAdminFields = super::decode_fields(payload)?;
783                store.remove_admin(decoded.node_id)?;
784            }
785            ADD_PENDING_NODE => {
786                let decoded: spec_ds::AddPendingNodeFields<'_> = super::decode_fields(payload)?;
787                store.add_pending_node(decoded.node_id, decoded.friendly_name, now)?;
788            }
789            REFRESH_NODE => {
790                let decoded: spec_ds::RefreshNodeFields = super::decode_fields(payload)?;
791                store.refresh_node(decoded.node_id, now)?;
792            }
793            REMOVE_NODE => {
794                let decoded: spec_ds::RemoveNodeFields = super::decode_fields(payload)?;
795                store.remove_node(decoded.node_id)?;
796            }
797            ADD_GROUP_ID_TO_ENDPOINT_FOR_NODE => {
798                let decoded: spec_ds::AddGroupIDToEndpointForNodeFields =
799                    super::decode_fields(payload)?;
800                store.add_group_to_endpoint(
801                    decoded.node_id,
802                    decoded.endpoint_id,
803                    decoded.group_id,
804                    now,
805                )?;
806            }
807            REMOVE_GROUP_ID_FROM_ENDPOINT_FOR_NODE => {
808                let decoded: spec_ds::RemoveGroupIDFromEndpointForNodeFields =
809                    super::decode_fields(payload)?;
810                store.remove_group_from_endpoint(
811                    decoded.node_id,
812                    decoded.endpoint_id,
813                    decoded.group_id,
814                    now,
815                )?;
816            }
817            _ => return Err(Status::UnsupportedCommand.into()),
818        }
819        Ok(None)
820    }
821}
822
823/// Whether a `GroupCAT` names one of ch. 12's two reserved identifiers (§12.2.4).
824///
825/// Separate from the range check because only one of them is outside the range: `0xFFFF` is, and
826/// `0xFFFE` — the Anchor CAT — is the largest value the range allows.
827const fn is_reserved_cat(cat: u16) -> bool {
828    cat == CaseAuthenticatedTag::ADMINISTRATOR_IDENTIFIER
829        || cat == CaseAuthenticatedTag::ANCHOR_IDENTIFIER
830}
831
832/// §11.24.5.2's `DatastoreStatusEntryStruct`.
833fn encode_status(
834    status: &StatusEntry,
835    w: &mut TlvWriter<'_>,
836    tag: Tag,
837) -> crate::error::Result<()> {
838    w.start_structure(tag)?;
839    w.unsigned(Tag::Context(0), u64::from(status.state.value()))?;
840    w.unsigned(Tag::Context(1), u64::from(status.updated_at))?;
841    // "the Status Code of the last failed operation where the State field is set to
842    // CommitFailure" — and nothing, legibly, when there has been no failure.
843    match status.failure {
844        Some(failure) => w.unsigned(Tag::Context(2), u64::from(failure.value()))?,
845        None => w.unsigned(Tag::Context(2), 0)?,
846    }
847    w.end_container()
848}
849
850/// So a tuple of clusters can dispatch to it by id.
851impl<const N: usize, const G: usize, const K: usize, const A: usize, const M: usize> Cluster
852    for JointFabricDatastore<'_, N, G, K, A, M>
853{
854    const ID: ClusterId = ID;
855}