Skip to main content

matter_kit/
config.rs

1//! What the node promises, and how its promises are checked.
2//!
3//! A Matter node is a set of tables: fabrics it belongs to, sessions it holds, exchanges in
4//! flight, subscriptions it serves, access-control entries it enforces. On a microcontroller
5//! every one of those is a fixed-capacity array whose length has to be known at compile time.
6//!
7//! The obvious way to express that is Cargo features — `fabrics-5`, `sessions-16` — which is
8//! what the other Rust implementation does, with seventy-odd of them. Cargo features are
9//! *additive and global*: two crates in one binary that want different sizes silently get the
10//! union, and nothing checks the result against the specification.
11//!
12//! # Capacity is declared once, on the table
13//!
14//! Stable Rust cannot write `Vec<T, { C::SESSIONS }>`: an associated const may not appear in
15//! const-generic position. So a table's capacity **is** its own const parameter —
16//! `SessionTable<C, N>`, `Acl<C, N, S, T>` — and there is no second place that also claims to
17//! be it. A trait constant that names a capacity it cannot size is worse than no constant at
18//! all: it reads as a promise, it can carry an assertion that looks like enforcement, and the
19//! table it claims to size is whatever length somebody else picked.
20//!
21//! What a table's capacity cannot tell you is what share of it each *fabric* is owed. That is a
22//! policy, it is what the node advertises on the wire, and it is what this trait carries:
23//!
24//! | Constant | What it is | Section |
25//! |---|---|---|
26//! | [`FABRICS`](Config::FABRICS) | how many ecosystems the node can join — `SupportedFabrics` | §11.18.5.3 |
27//! | [`SUBSCRIPTIONS_PER_FABRIC`](Config::SUBSCRIPTIONS_PER_FABRIC) | `SubscriptionsPerFabric` | §2.11.2.2 |
28//! | [`ACL_ENTRIES_PER_FABRIC`](Config::ACL_ENTRIES_PER_FABRIC) | `AccessControlEntriesPerFabric` | §2.11.1.1, §9.10.6.7 |
29//! | [`GROUPS_PER_FABRIC`](Config::GROUPS_PER_FABRIC) | `MaxGroupsPerFabric` | §2.11.1.2, §11.2.6.2 |
30//! | [`GROUP_KEYS_PER_FABRIC`](Config::GROUP_KEYS_PER_FABRIC) | `MaxGroupKeysPerFabric` | §2.11.1.2, §11.2.6.3 |
31//! | [`READ_PATHS`](Config::READ_PATHS) | `ReadPathsSupported` | §2.11.2.1, §11.1.4.4 |
32//! | [`ICD_CLIENTS_PER_FABRIC`](Config::ICD_CLIENTS_PER_FABRIC) | `ClientsSupportedPerFabric` | §9.16.6.6 |
33//! | [`ACL_AUXILIARY`](Config::ACL_AUXILIARY) | whether §9.10.4.3's Auxiliary feature is served | §6.6.6.2 |
34//!
35//! Every one of those is read by the crate through `C::`, and every assertion in
36//! [`AssertValid`] constrains a number something reads.
37//!
38//! # Who checks that a table can keep the promise
39//!
40//! The table does, at compile time, against the `Config` it is parameterised by. A
41//! `SubscriptionTable<C, N, P>` will not compile unless `N` can hold
42//! `FABRICS × SUBSCRIPTIONS_PER_FABRIC`; an `Acl<C, N, S, T>` will not compile unless `N` can
43//! hold `FABRICS × ACL_ENTRIES_PER_FABRIC`, `S` is at least §9.10.6.5's four and `T` at least
44//! §9.10.6.6's three. The failing rule is named in the build error.
45//!
46//! That is the whole mechanism, and it is why §11.1.4.4's `CapabilityMinima` is built from the
47//! tables rather than from this trait: the specification says each field "SHALL indicate the
48//! **actual**" number, and only the table knows it.
49//!
50//! ```
51//! use matter_kit::Config;
52//!
53//! /// A Thread light: room for five ecosystems, and the specification's minimum of everything.
54//! struct Light;
55//! impl Config for Light {}
56//! ```
57//!
58//! Everything not named takes the value in [`DefaultConfig`].
59
60/// What a Matter node promises each fabric, and which optional behaviours it serves.
61///
62/// Implement this on a zero-sized type and pass it as the `C` parameter. Every constant has a
63/// default that is the specification's own minimum, so `impl Config for MyNode {}` is a
64/// complete and conformant implementation.
65///
66/// It does **not** size anything: see the module documentation.
67pub trait Config {
68    /// How many fabrics — commissioned ecosystems — the node can belong to.
69    ///
70    /// Reported as `SupportedFabrics` (Core §11.18.5.3), whose constraint is `5 to 254`: a node
71    /// that supports fewer than five cannot be commissioned into the number of ecosystems the
72    /// specification requires. The fabric table is asserted at compile time to hold this many.
73    const FABRICS: usize = 5;
74
75    /// How many subscriptions any one fabric may hold.
76    ///
77    /// §2.11.2.2 states the rule as a *guarantee*, not a cap: "A publisher SHALL ensure that
78    /// every fabric the node is commissioned into can support at least three Subscribe
79    /// Interactions to the publisher." A table with only a global limit cannot make that
80    /// promise — the first administrator to ask fills it, and every fabric commissioned
81    /// afterwards is told the node is out of resources by a node that is, from its own point
82    /// of view, working perfectly.
83    ///
84    /// So the guarantee is a fixed share each, refusing a fabric that is at its quota even when
85    /// the table has room. That is the strict reading, it is always conformant, and it cannot
86    /// surprise an administrator by granting a subscription one day and refusing it the next
87    /// when what changed was somebody else's fabric.
88    const SUBSCRIPTIONS_PER_FABRIC: usize = 3;
89
90    /// How many access-control entries **one fabric** may hold — §9.10.6.7's
91    /// `AccessControlEntriesPerFabric`, constrained to `4 to 65534`.
92    ///
93    /// §2.11.1.1 requires "at least four Access Control Entries available for every fabric
94    /// supported by the node", and without a quota the first fabric to fill the table would
95    /// lock every later administrator out of granting itself anything.
96    ///
97    /// §2.11.1.1 permits over-subscription — "if it supports N entries must enforce that any K
98    /// fabrics together do not use more than N - 4*(5-K) entries" — which would let one fabric
99    /// borrow the unused quota of another. This is the strict reading instead: a fixed share
100    /// each, for the same reason as [`SUBSCRIPTIONS_PER_FABRIC`](Config::SUBSCRIPTIONS_PER_FABRIC).
101    const ACL_ENTRIES_PER_FABRIC: usize = 4;
102
103    /// How many group memberships one fabric may hold — §11.2.6.2's `MaxGroupsPerFabric`.
104    ///
105    /// Core §2.11.1.2: "at least four groups per fabric".
106    const GROUPS_PER_FABRIC: usize = 4;
107
108    /// How many group key sets one fabric may hold — §11.2.6.3's `MaxGroupKeysPerFabric`.
109    ///
110    /// Core §2.11.1.2: "at least three group keys per fabric".
111    const GROUP_KEYS_PER_FABRIC: usize = 3;
112
113    /// How many paths one Read Request is guaranteed to be answered with.
114    ///
115    /// §11.1.4.4's `ReadPathsSupported`, constrained to `9 to 10000`: "the actual maximum
116    /// number of read paths … which a node guarantees being able to process in any Read Request
117    /// Action". Core §2.11.2.1 sets the floor: "a single Read Interaction from a client on that
118    /// fabric containing up to 9 paths".
119    ///
120    /// Unlike every other constant here this one is a promise about *work* rather than about
121    /// storage, so no table can check it. `tests/im_read_server.rs` does, by reading that many
122    /// paths in one action and requiring an answer.
123    const READ_PATHS: usize = 9;
124
125    /// How many Check-In registrations one fabric may hold — §9.16.6.6's
126    /// `ClientsSupportedPerFabric`, constrained to `min 1`.
127    ///
128    /// §9.16.6.5: "The maximum number of entries that can be in the list SHALL be
129    /// ClientsSupportedPerFabric for each fabric", so this is a per-fabric guarantee like the
130    /// others and the registration table is checked against it at compile time.
131    const ICD_CLIENTS_PER_FABRIC: usize = 1;
132
133    /// Whether §9.10.4.3's Auxiliary feature is implemented.
134    ///
135    /// It changes an access decision: with it, §6.6.6.2 stops a wildcard Group entry from
136    /// reaching endpoint 0, whose clusters administer the node itself.
137    const ACL_AUXILIARY: bool = false;
138}
139
140/// A device-sized profile that satisfies every minimum: five fabrics, sixteen sessions,
141/// fifteen subscriptions.
142///
143/// This is the configuration the crate's own tests and examples use.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct DefaultConfig;
146
147impl Config for DefaultConfig {}
148
149/// The largest message that fits the IPv6 minimum MTU (Core §4.4.4).
150///
151/// "Support for IPv6 fragmentation is not mandatory in Matter, and the expected supported
152/// MTU is 1280 bytes … all messages, including transport headers, SHALL fit within that
153/// minimal IPv6 MTU. This message size limit SHALL apply to the UDP transport."
154pub const MAX_UDP_MESSAGE: usize = 1280;
155
156/// The largest framing a secured unicast message can carry, in octets.
157///
158/// Message header: flags, session id, security flags and counter (8), a source node id (8) and
159/// a destination node id (8) — [`MessageHeader::encoded_len`](crate::msg::MessageHeader::encoded_len)'s
160/// worst case. Protocol header: flags, opcode, exchange id and protocol id (6), a vendor id (2)
161/// and an acknowledged counter (4) — [`ProtocolHeader::encoded_len`](crate::msg::ProtocolHeader::encoded_len)'s.
162/// Then §4.8's AEAD tag (16).
163pub const MAX_MESSAGE_FRAMING: usize = (8 + 8 + 8) + (6 + 2 + 4) + 16;
164
165/// The largest protocol payload that is **certain** to fit a UDP datagram once framed.
166///
167/// A node builds its reply in a payload buffer and hands it to the messaging layer, which adds
168/// the headers and the AEAD tag. So the payload bound is the datagram bound *minus the framing*,
169/// and sizing that buffer by anything else is guesswork that fails as `buffer too small` — from
170/// this node, about its own reply, with nothing on the wire to explain it.
171///
172/// It is a floor rather than an exact figure: a message with no source node id, or on a common
173/// protocol, or with nothing to acknowledge, has room to spare. Sizing to the worst case is what
174/// makes "it fits" independent of which of those happens to be true.
175pub const MAX_UDP_PAYLOAD: usize = MAX_UDP_MESSAGE.saturating_sub(MAX_MESSAGE_FRAMING);
176
177/// Compile-time proof that a [`Config`] is internally conformant.
178///
179/// Instantiating this type evaluates its assertions; every generic entry point in the crate
180/// does so, which is what makes a bad `Config` a build failure at its first use.
181///
182/// It checks the *policy* only. Whether a table is big enough to keep that policy is checked by
183/// the table — see [`Capacity`].
184pub struct AssertValid<C: Config>(core::marker::PhantomData<C>);
185
186impl<C: Config> AssertValid<C> {
187    /// The assertions themselves. Referencing this constant is what runs them.
188    pub const CHECK: () = {
189        assert!(
190            C::FABRICS >= 5,
191            "Config::FABRICS: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
192        );
193        assert!(
194            C::FABRICS <= 254,
195            "Config::FABRICS: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
196        );
197        assert!(
198            C::SUBSCRIPTIONS_PER_FABRIC >= 3,
199            "Config::SUBSCRIPTIONS_PER_FABRIC: Core §2.11.2.2 requires at least 3 per fabric"
200        );
201        assert!(
202            C::ACL_ENTRIES_PER_FABRIC >= 4,
203            "Config::ACL_ENTRIES_PER_FABRIC: Core §2.11.1.1 requires at least 4 per fabric"
204        );
205        assert!(
206            C::GROUPS_PER_FABRIC >= 4,
207            "Config::GROUPS_PER_FABRIC: Core §2.11.1.2 requires at least 4 groups per fabric"
208        );
209        assert!(
210            C::GROUP_KEYS_PER_FABRIC >= 3,
211            "Config::GROUP_KEYS_PER_FABRIC: Core §2.11.1.2 requires at least 3 group keys per fabric"
212        );
213        assert!(
214            C::READ_PATHS >= 9,
215            "Config::READ_PATHS: Core §2.11.2.1 requires a read of up to 9 paths"
216        );
217        assert!(
218            C::ICD_CLIENTS_PER_FABRIC >= 1,
219            "Config::ICD_CLIENTS_PER_FABRIC: §9.16.6.6 constrains ClientsSupportedPerFabric to min 1"
220        );
221    };
222}
223
224/// A table whose capacity the node states on the wire.
225///
226/// §11.1.4.4 requires `CapabilityMinima` to report "the **actual**" number a node supports, and
227/// §11.18.5.3, §9.10.6.7, §11.2.6.2 and §11.2.6.3 do the same for their clusters. Only the table
228/// knows that number, so the table is what publishes it — never [`Config`], which cannot size
229/// anything, and never a value the integrator types beside it.
230///
231/// Implemented by [`FabricTable`](crate::fabric::FabricTable),
232/// [`SessionTable`](crate::session::SessionTable),
233/// [`SubscriptionTable`](crate::im::SubscriptionTable), [`Acl`](crate::acl::Acl) and
234/// [`GroupKeys`](crate::group::GroupKeys).
235pub trait Capacity {
236    /// Total slots, across every fabric.
237    const TOTAL: usize;
238
239    /// What one fabric is guaranteed — the number the specification calls "actual".
240    ///
241    /// A table with no per-fabric quota reports its total.
242    const PER_FABRIC: usize;
243}
244
245/// A subscription table, which has one more number the node states: how many paths one
246/// subscription may carry.
247///
248/// §11.1.4.4's `SubscribePathsSupported`, constrained to `3 to 10000`. It is separate from
249/// [`Capacity`] because it is the only table with an inner capacity the specification asks
250/// about, and a constant on `Capacity` that every other table answered zero to would be a
251/// number that means nothing four times over.
252pub trait SubscriptionCapacity: Capacity {
253    /// How many attribute or event paths one subscription can carry.
254    const PATHS: usize;
255}
256
257/// Runs [`AssertValid::CHECK`] for `C`.
258///
259/// Call it from any `const` context — or just let the crate's generic types do it.
260pub const fn assert_valid<C: Config>() {
261    #[allow(clippy::let_unit_value)]
262    let () = AssertValid::<C>::CHECK;
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    // The real check is a `const` one: `assert_valid` evaluates `AssertValid::CHECK`,
270    // which fails the *build* rather than a test run. Naming it in a `const` context is
271    // what proves that, so these are `const` blocks and not runtime assertions.
272    const _: () = assert_valid::<DefaultConfig>();
273
274    #[test]
275    fn the_default_config_satisfies_every_minimum() {
276        // Reaching this line at all means the `const` above compiled.
277        assert_valid::<DefaultConfig>();
278    }
279
280    #[test]
281    fn a_bigger_fabric_count_is_still_a_valid_policy() {
282        #[derive(Debug)]
283        struct Big;
284        impl Config for Big {
285            const FABRICS: usize = 16;
286        }
287        const _: () = assert_valid::<Big>();
288        // Nothing here scales with `FABRICS`, because nothing here is a capacity. What scales
289        // is the *requirement* each table is checked against: a `SessionTable<Big, 16>` now
290        // fails to build, because §4.14.2.8 wants 48 sessions for sixteen fabrics.
291        assert_eq!(Big::SUBSCRIPTIONS_PER_FABRIC, 3);
292        assert_eq!(Big::ACL_ENTRIES_PER_FABRIC, 4);
293    }
294
295    #[test]
296    fn the_defaults_are_the_specifications_own_minima() {
297        // A `Config` that names nothing is a conformant node and nothing more: every extra is a
298        // deliberate act, and `AssertValid` refuses anything below.
299        assert_eq!(DefaultConfig::FABRICS, 5);
300        assert_eq!(DefaultConfig::SUBSCRIPTIONS_PER_FABRIC, 3);
301        assert_eq!(DefaultConfig::ACL_ENTRIES_PER_FABRIC, 4);
302        assert_eq!(DefaultConfig::GROUPS_PER_FABRIC, 4);
303        assert_eq!(DefaultConfig::GROUP_KEYS_PER_FABRIC, 3);
304        assert_eq!(DefaultConfig::READ_PATHS, 9);
305        const { assert!(!<DefaultConfig as Config>::ACL_AUXILIARY) };
306    }
307
308    #[test]
309    fn max_udp_message_is_the_ipv6_minimum_mtu() {
310        assert_eq!(MAX_UDP_MESSAGE, 1280);
311    }
312}
313
314#[cfg(test)]
315mod payload_bound {
316    use super::{MAX_MESSAGE_FRAMING, MAX_UDP_MESSAGE, MAX_UDP_PAYLOAD};
317    use crate::msg::{
318        Destination, MessageHeader, NodeId, ProtocolHeader, ProtocolId, SessionId, SessionType,
319    };
320
321    /// `MAX_MESSAGE_FRAMING` is the worst case the encoders can actually produce.
322    ///
323    /// Derived by hand from two `encoded_len` implementations, which is exactly the kind of
324    /// arithmetic that is right when written and wrong after the next field is added. So it is
325    /// checked against the encoders rather than against itself.
326    #[test]
327    fn the_framing_bound_is_what_the_headers_encode() {
328        // Every optional field present: a source node id, a destination node id, a vendor
329        // protocol and an acknowledgement.
330        let message = MessageHeader {
331            session_id: SessionId(0x1234),
332            session_type: SessionType::Unicast,
333            privacy: false,
334            control: false,
335            message_counter: 0xDEAD_BEEF,
336            source: Some(NodeId(0x0102_0304_0506_0708)),
337            destination: Destination::Node(NodeId(0x1112_1314_1516_1718)),
338        };
339        let protocol = ProtocolHeader {
340            acknowledged_counter: Some(0x0BAD_F00D),
341            protocol: ProtocolId {
342                vendor: crate::msg::VendorId(0xFFF1),
343                id: 0x0001,
344            },
345            ..ProtocolHeader::default()
346        };
347        let encoded = message.encoded_len() + protocol.encoded_len();
348        let mic = crate::crypto::AEAD_MIC_LENGTH_BYTES;
349        assert_eq!(
350            encoded + mic,
351            MAX_MESSAGE_FRAMING,
352            "the framing bound no longer matches what the headers encode"
353        );
354        assert_eq!(MAX_UDP_PAYLOAD + MAX_MESSAGE_FRAMING, MAX_UDP_MESSAGE);
355    }
356}