matter_kit/dm/node.rs
1//! A node's tree of endpoints and clusters, and what a wildcard path expands to
2//! (Core §7.2, §8.2.1.6).
3//!
4//! A node is a fixed set of endpoints; each endpoint is a fixed set of cluster instances.
5//! "Fixed" is the point: [`Node`] borrows slices of `const` descriptors rather than owning
6//! anything, so the whole shape of a device lives in flash and costs no RAM.
7//!
8//! # Expansion is the whole of §8.2.1.6
9//!
10//! > Each path in the list that is a Wildcard Path SHALL be expanded into a complete list of
11//! > existent paths. This is done by generating all permutations where the wildcarded
12//! > elements are replaced with existent elements.
13//!
14//! and, in the same section, the sentence that decides the shape of this module:
15//!
16//! > This process does not check access qualities, such as read or write access, privileges,
17//! > or fabric qualities.
18//!
19//! So [`Node::expand`] yields every path that *exists*, and says nothing about whether the
20//! caller may have it. Access is applied afterwards, and §8.4.3.2 is precise about why the
21//! order matters: a **concrete** path that fails a check produces an `AttributeStatusIB`
22//! naming the failure, while an **expanded** path that fails one is "discarded" silently. A
23//! client that asked for a specific attribute learns it may not have it; a client that asked
24//! for everything simply does not see it. Merging the two would leak the shape of a node to
25//! a subject with no privilege over it.
26
27use crate::dm::meta::ClusterDescriptor;
28use crate::im::{AttributeId, AttributePath, ClusterId, EndpointId};
29
30/// One endpoint: a set of cluster instances (§7.2).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Endpoint<'a> {
33 /// The endpoint id. Endpoint 0 is the root node (§9.2).
34 pub id: EndpointId,
35 /// The clusters on it, **sorted by cluster id**.
36 pub clusters: &'a [ClusterDescriptor<'a>],
37 /// The device types it conforms to (§9.5.6.1).
38 ///
39 /// §9.5 requires "at least one device type entry", and two layers read it: the Descriptor
40 /// cluster publishes it as `DeviceTypeList`, and §6.6.6.2's access control matches an ACL
41 /// target's `DeviceType` against it. Keeping it here is what stops those two from
42 /// describing different devices.
43 pub device_types: &'a [crate::dm::meta::DeviceType],
44 /// `ClientList` (§9.5.6.3) — the clusters this endpoint speaks *as a client*.
45 ///
46 /// Not derivable from `clusters`: a [`ClusterDescriptor`] describes a *server* instance,
47 /// and a client binding has no descriptor to be found in — a switch that controls a light
48 /// is a client of On/Off and a server of nothing much.
49 ///
50 /// It lives here rather than on the Descriptor cluster for the same reason
51 /// `device_types` does: two layers read it, the Descriptor cluster publishing
52 /// `ClientList` and §9.2's device-type check demanding it, and a device type may require a
53 /// cluster on the client side — §6.1's On/Off Light Switch requires On/Off as a client and
54 /// as nothing else, which is the only thing that tells it apart from a light.
55 pub clients: &'a [ClusterId],
56}
57
58impl<'a> Endpoint<'a> {
59 /// An endpoint with clusters and no device types yet.
60 #[must_use]
61 pub const fn new(id: EndpointId, clusters: &'a [ClusterDescriptor<'a>]) -> Self {
62 Self {
63 id,
64 clusters,
65 device_types: &[],
66 clients: &[],
67 }
68 }
69
70 /// The same endpoint, declaring the clusters it speaks as a client (§9.5.6.3).
71 #[must_use]
72 pub const fn with_clients(mut self, clients: &'a [ClusterId]) -> Self {
73 self.clients = clients;
74 self
75 }
76
77 /// The same endpoint, declaring the device types of §9.5.6.1.
78 #[must_use]
79 pub const fn with_device_types(
80 mut self,
81 device_types: &'a [crate::dm::meta::DeviceType],
82 ) -> Self {
83 self.device_types = device_types;
84 self
85 }
86
87 /// Whether this endpoint conforms to `device_type`.
88 ///
89 /// §6.6.6.2's `endpoint_contains_device_type`, which decides whether an ACL target that
90 /// names a device type rather than an endpoint applies here.
91 #[must_use]
92 pub fn has_device_type(&self, device_type: u32) -> bool {
93 self.device_types
94 .iter()
95 .any(|d| d.device_type == device_type)
96 }
97}
98
99impl<'a> Endpoint<'a> {
100 /// The descriptor for a cluster id on this endpoint.
101 #[must_use]
102 pub fn cluster(&self, id: ClusterId) -> Option<&'a ClusterDescriptor<'a>> {
103 self.clusters
104 .binary_search_by_key(&id, |c| c.id)
105 .ok()
106 .and_then(|index| self.clusters.get(index))
107 }
108}
109
110/// A node's data model: its endpoints and everything on them.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct Node<'a> {
113 /// The endpoints, **sorted by id**.
114 pub endpoints: &'a [Endpoint<'a>],
115}
116
117/// Why a node's descriptors are not usable.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum Malformed {
121 /// The endpoints are not sorted by id, or two share one.
122 Endpoints,
123 /// An endpoint's clusters are not sorted by id, or two share one.
124 Clusters {
125 /// Which endpoint.
126 endpoint: EndpointId,
127 },
128 /// A cluster's attributes, commands or events are unsorted, or it declares one of
129 /// §7.13's global attribute ids as its own.
130 Cluster {
131 /// Which endpoint.
132 endpoint: EndpointId,
133 /// Which cluster.
134 cluster: ClusterId,
135 },
136}
137
138/// One path that exists on a node, with the descriptors it resolves to.
139#[derive(Debug, Clone, Copy)]
140pub struct Resolved<'a> {
141 /// The endpoint.
142 pub endpoint: EndpointId,
143 /// The cluster's descriptor.
144 pub cluster: &'a ClusterDescriptor<'a>,
145 /// The attribute id.
146 pub attribute: AttributeId,
147}
148
149impl Resolved<'_> {
150 /// The concrete path this resolves to, for putting in a report.
151 #[must_use]
152 pub const fn path(&self) -> AttributePath {
153 AttributePath::attribute(self.endpoint, self.cluster.id, self.attribute)
154 }
155}
156
157/// One command that exists on a node, with the descriptors it resolves to.
158#[derive(Debug, Clone, Copy)]
159pub struct ResolvedCommand<'a> {
160 /// The endpoint.
161 pub endpoint: EndpointId,
162 /// The cluster's descriptor.
163 pub cluster: &'a ClusterDescriptor<'a>,
164 /// The command's descriptor.
165 pub command: crate::dm::meta::CommandDescriptor,
166}
167
168impl ResolvedCommand<'_> {
169 /// The concrete path this resolves to.
170 #[must_use]
171 pub const fn path(&self) -> crate::im::CommandPath {
172 crate::im::CommandPath::command(self.endpoint, self.cluster.id, self.command.id)
173 }
174}
175
176impl<'a> Node<'a> {
177 /// A node over a slice of endpoints.
178 #[must_use]
179 pub const fn new(endpoints: &'a [Endpoint<'a>]) -> Self {
180 Self { endpoints }
181 }
182
183 /// The endpoint with this id.
184 #[must_use]
185 pub fn endpoint(&self, id: EndpointId) -> Option<&'a Endpoint<'a>> {
186 self.endpoints
187 .binary_search_by_key(&id, |e| e.id)
188 .ok()
189 .and_then(|index| self.endpoints.get(index))
190 }
191
192 /// The cluster at an endpoint.
193 #[must_use]
194 pub fn cluster(
195 &self,
196 endpoint: EndpointId,
197 cluster: ClusterId,
198 ) -> Option<&'a ClusterDescriptor<'a>> {
199 self.endpoint(endpoint)?.cluster(cluster)
200 }
201
202 /// Checks every ordering invariant the lookups depend on.
203 ///
204 /// Everything here binary-searches, so an unsorted slice does not fail loudly — it
205 /// silently fails to find things, which on a device looks like a cluster that is simply
206 /// not there. `const` slices cannot be checked by the compiler today, so this is called
207 /// once at start-up instead.
208 pub fn validate(&self) -> Result<(), Malformed> {
209 if !self
210 .endpoints
211 .windows(2)
212 .all(|w| matches!(w, [a, b] if a.id < b.id))
213 {
214 return Err(Malformed::Endpoints);
215 }
216 for endpoint in self.endpoints {
217 if !endpoint
218 .clusters
219 .windows(2)
220 .all(|w| matches!(w, [a, b] if a.id < b.id))
221 {
222 return Err(Malformed::Clusters {
223 endpoint: endpoint.id,
224 });
225 }
226 for cluster in endpoint.clusters {
227 if !cluster.is_well_formed() {
228 return Err(Malformed::Cluster {
229 endpoint: endpoint.id,
230 cluster: cluster.id,
231 });
232 }
233 }
234 }
235 Ok(())
236 }
237
238 /// Expands a request path into every existent path it names (§8.2.1.6).
239 ///
240 /// **No access check happens here.** §8.2.1.6: "This process does not check access
241 /// qualities, such as read or write access, privileges, or fabric qualities." The caller
242 /// applies those, and §8.4.3.2 decides what to do when one fails — which differs between
243 /// a concrete path and an expanded one.
244 ///
245 /// A concrete path that does not exist yields nothing; the caller must notice that and
246 /// produce the right status, which is why [`Node::resolve`] exists beside this.
247 #[must_use]
248 pub fn expand(&self, path: &AttributePath) -> Expand<'a> {
249 self.expand_from(path, ExpandCursor::START)
250 }
251
252 /// The same expansion, resumed at `cursor`.
253 ///
254 /// Core §10.2.3 splits a report "into multiple messages at logical boundaries due to the
255 /// size limitations imposed by IPv6 for UDP packets", and each message after the first
256 /// has to start where the last one stopped. A cursor from [`Expand::cursor`] is that
257 /// place.
258 #[must_use]
259 pub fn expand_from(&self, path: &AttributePath, cursor: ExpandCursor) -> Expand<'a> {
260 Expand {
261 endpoints: self.endpoints,
262 endpoint_filter: path.endpoint,
263 cluster_filter: path.cluster,
264 attribute_filter: path.attribute,
265 endpoint_index: cursor.endpoint,
266 cluster_index: cursor.cluster,
267 attribute_index: cursor.attribute,
268 }
269 }
270
271 /// Resolves a concrete path, saying precisely which part of it does not exist.
272 ///
273 /// §8.4.3.2 requires a distinct status for each level — `UNSUPPORTED_ENDPOINT`,
274 /// `UNSUPPORTED_CLUSTER`, `UNSUPPORTED_ATTRIBUTE` — so "not found" is not a good enough
275 /// answer: a client uses the difference to tell a missing endpoint from a missing
276 /// feature on one that is there.
277 pub fn resolve(
278 &self,
279 endpoint: EndpointId,
280 cluster: ClusterId,
281 attribute: AttributeId,
282 ) -> Result<Resolved<'a>, Missing> {
283 let Some(endpoint_ref) = self.endpoint(endpoint) else {
284 return Err(Missing::Endpoint);
285 };
286 let Some(cluster_ref) = endpoint_ref.cluster(cluster) else {
287 return Err(Missing::Cluster);
288 };
289 if cluster_ref.attribute(attribute).is_none() {
290 return Err(Missing::Attribute);
291 }
292 Ok(Resolved {
293 endpoint,
294 cluster: cluster_ref,
295 attribute,
296 })
297 }
298}
299
300/// One event that exists on a node, with the descriptors it resolves to.
301#[derive(Debug, Clone, Copy)]
302pub struct ResolvedEvent<'a> {
303 /// The endpoint.
304 pub endpoint: EndpointId,
305 /// The cluster's descriptor.
306 pub cluster: &'a ClusterDescriptor<'a>,
307 /// The event's descriptor — its access and its priority.
308 pub event: crate::dm::EventDescriptor,
309}
310
311impl ResolvedEvent<'_> {
312 /// The concrete path this resolves to, for putting in a report.
313 #[must_use]
314 pub const fn path(&self) -> crate::im::EventPath {
315 crate::im::EventPath {
316 node: None,
317 endpoint: Some(self.endpoint),
318 cluster: Some(self.cluster.id),
319 event: Some(self.event.id),
320 is_urgent: None,
321 }
322 }
323}
324
325/// Which level of a concrete command path was not found (§8.8.2.3).
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
327pub enum MissingCommand {
328 /// "the path indicates an endpoint that is unsupported".
329 Endpoint,
330 /// "the path indicates a cluster that is unsupported".
331 Cluster,
332 /// "the path indicates a command that is unsupported".
333 Command,
334}
335
336impl MissingCommand {
337 /// The status §8.8.2.3 step b.ii pairs with this level.
338 #[must_use]
339 pub const fn status(self) -> crate::im::Status {
340 match self {
341 Self::Endpoint => crate::im::Status::UnsupportedEndpoint,
342 Self::Cluster => crate::im::Status::UnsupportedCluster,
343 Self::Command => crate::im::Status::UnsupportedCommand,
344 }
345 }
346}
347
348/// Which level of a concrete path was not found (§8.4.3.2).
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
350pub enum Missing {
351 /// "the path indicates an endpoint that is unsupported".
352 Endpoint,
353 /// "the path indicates a cluster that is unsupported".
354 Cluster,
355 /// "the path indicates an attribute … that is unsupported".
356 Attribute,
357}
358
359impl Missing {
360 /// The status §8.4.3.2 pairs with this level.
361 #[must_use]
362 pub const fn status(self) -> crate::im::Status {
363 match self {
364 Self::Endpoint => crate::im::Status::UnsupportedEndpoint,
365 Self::Cluster => crate::im::Status::UnsupportedCluster,
366 Self::Attribute => crate::im::Status::UnsupportedAttribute,
367 }
368 }
369}
370
371impl<'a> Node<'a> {
372 /// Resolves a concrete event path, the way [`Node::resolve`] does an attribute.
373 ///
374 /// §8.4.3.3's event paths are validated exactly like attribute paths: the endpoint, then
375 /// the cluster, then the event — each level a different answer, because a client that asked
376 /// for an endpoint this node does not have has made a different mistake from one that asked
377 /// for an event the cluster does not define.
378 pub fn resolve_event(
379 &self,
380 endpoint: EndpointId,
381 cluster: ClusterId,
382 event: crate::im::EventId,
383 ) -> Result<ResolvedEvent<'a>, Missing> {
384 let Some(endpoint_ref) = self.endpoint(endpoint) else {
385 return Err(Missing::Endpoint);
386 };
387 let Some(cluster_ref) = endpoint_ref.cluster(cluster) else {
388 return Err(Missing::Cluster);
389 };
390 let Some(descriptor) = cluster_ref.events.iter().find(|e| e.id == event) else {
391 // `Missing::Attribute` is the leaf level, whatever the leaf is called.
392 return Err(Missing::Attribute);
393 };
394 Ok(ResolvedEvent {
395 endpoint,
396 cluster: cluster_ref,
397 event: *descriptor,
398 })
399 }
400
401 /// Resolves a concrete command path, saying which level is missing (§8.8.2.3 step b.ii).
402 pub fn resolve_command(
403 &self,
404 endpoint: EndpointId,
405 cluster: crate::im::ClusterId,
406 command: crate::im::CommandId,
407 ) -> Result<ResolvedCommand<'a>, MissingCommand> {
408 let Some(endpoint_ref) = self.endpoint(endpoint) else {
409 return Err(MissingCommand::Endpoint);
410 };
411 let Some(cluster_ref) = endpoint_ref.cluster(cluster) else {
412 return Err(MissingCommand::Cluster);
413 };
414 let Some(descriptor) = cluster_ref.accepted_command(command) else {
415 return Err(MissingCommand::Command);
416 };
417 Ok(ResolvedCommand {
418 endpoint,
419 cluster: cluster_ref,
420 command: descriptor,
421 })
422 }
423
424 /// Expands a command path into every existent command it names (§8.2.1.6).
425 ///
426 /// §8.8 permits a wildcard here — "Invoke Request action SHALL support group paths and
427 /// SHOULD support wildcard paths" — but only when the request carries exactly one
428 /// command; §8.8.2.2 step 5a requires every path to be concrete once there are several.
429 #[must_use]
430 pub fn expand_commands(&self, path: &crate::im::CommandPath) -> ExpandCommands<'a> {
431 ExpandCommands {
432 endpoints: self.endpoints,
433 endpoint_filter: path.endpoint,
434 cluster_filter: path.cluster,
435 command_filter: path.command,
436 endpoint_index: 0,
437 cluster_index: 0,
438 command_index: 0,
439 }
440 }
441}
442
443/// The commands a wildcard path names, produced one at a time.
444#[derive(Debug, Clone)]
445pub struct ExpandCommands<'a> {
446 endpoints: &'a [Endpoint<'a>],
447 endpoint_filter: Option<EndpointId>,
448 cluster_filter: Option<crate::im::ClusterId>,
449 command_filter: Option<crate::im::CommandId>,
450 endpoint_index: usize,
451 cluster_index: usize,
452 command_index: usize,
453}
454
455impl<'a> Iterator for ExpandCommands<'a> {
456 type Item = ResolvedCommand<'a>;
457
458 fn next(&mut self) -> Option<Self::Item> {
459 loop {
460 let endpoint = self.endpoints.get(self.endpoint_index)?;
461 if self
462 .endpoint_filter
463 .is_some_and(|wanted| wanted != endpoint.id)
464 {
465 self.endpoint_index = self.endpoint_index.saturating_add(1);
466 self.cluster_index = 0;
467 self.command_index = 0;
468 continue;
469 }
470
471 let Some(cluster) = endpoint.clusters.get(self.cluster_index) else {
472 self.endpoint_index = self.endpoint_index.saturating_add(1);
473 self.cluster_index = 0;
474 self.command_index = 0;
475 continue;
476 };
477 if self
478 .cluster_filter
479 .is_some_and(|wanted| wanted != cluster.id)
480 {
481 self.cluster_index = self.cluster_index.saturating_add(1);
482 self.command_index = 0;
483 continue;
484 }
485
486 let Some(command) = cluster.accepted_commands.get(self.command_index) else {
487 self.cluster_index = self.cluster_index.saturating_add(1);
488 self.command_index = 0;
489 continue;
490 };
491 self.command_index = self.command_index.saturating_add(1);
492
493 if self
494 .command_filter
495 .is_some_and(|wanted| wanted != command.id)
496 {
497 continue;
498 }
499
500 return Some(ResolvedCommand {
501 endpoint: endpoint.id,
502 cluster,
503 command: *command,
504 });
505 }
506 }
507}
508
509/// How far a wildcard expansion got, so the next message can carry on from there.
510///
511/// A whole-node wildcard expands to more than one message holds, and Core §10.2.3 answers
512/// that by chunking rather than truncating. Chunking needs somewhere to resume, and this is
513/// it: three indices into the endpoint, cluster and attribute slices, which is enough to
514/// name a position without borrowing the node or remembering the paths already sent.
515///
516/// [`ExpandCursor::START`] is the beginning. A cursor is only meaningful against the node
517/// and path that produced it — the indices are positional, so feeding one to a different
518/// node resumes at a position that means something else.
519#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
520pub struct ExpandCursor {
521 endpoint: usize,
522 cluster: usize,
523 attribute: usize,
524}
525
526impl ExpandCursor {
527 /// The start of an expansion.
528 pub const START: Self = Self {
529 endpoint: 0,
530 cluster: 0,
531 attribute: 0,
532 };
533
534 /// Whether this is the start, i.e. nothing has been served for this path yet.
535 #[must_use]
536 pub const fn is_start(&self) -> bool {
537 self.endpoint == 0 && self.cluster == 0 && self.attribute == 0
538 }
539}
540
541/// The paths a wildcard names, produced one at a time.
542///
543/// Lazy for the same reason the interaction model's arrays are: a whole-node wildcard
544/// on a bridge expands to thousands of paths, and a server must be able to fill one message
545/// and stop rather than materialise the list first.
546///
547/// [`Expand::cursor`] and [`Node::expand_from`] make that stop *resumable*, which is what
548/// §10.2.3's chunking needs.
549#[derive(Debug, Clone)]
550pub struct Expand<'a> {
551 endpoints: &'a [Endpoint<'a>],
552 endpoint_filter: Option<EndpointId>,
553 cluster_filter: Option<ClusterId>,
554 attribute_filter: Option<AttributeId>,
555 endpoint_index: usize,
556 cluster_index: usize,
557 attribute_index: usize,
558}
559
560impl Expand<'_> {
561 /// Where this expansion has got to.
562 ///
563 /// Taken *after* a [`Resolved`] has been dealt with, the cursor names the next path; so
564 /// a chunk that could not fit its last path re-takes the cursor from before that path
565 /// and resumes there.
566 #[must_use]
567 pub const fn cursor(&self) -> ExpandCursor {
568 ExpandCursor {
569 endpoint: self.endpoint_index,
570 cluster: self.cluster_index,
571 attribute: self.attribute_index,
572 }
573 }
574}
575
576impl<'a> Iterator for Expand<'a> {
577 type Item = Resolved<'a>;
578
579 fn next(&mut self) -> Option<Self::Item> {
580 loop {
581 let endpoint = self.endpoints.get(self.endpoint_index)?;
582 if self
583 .endpoint_filter
584 .is_some_and(|wanted| wanted != endpoint.id)
585 {
586 self.endpoint_index = self.endpoint_index.saturating_add(1);
587 self.cluster_index = 0;
588 self.attribute_index = 0;
589 continue;
590 }
591
592 let Some(cluster) = endpoint.clusters.get(self.cluster_index) else {
593 self.endpoint_index = self.endpoint_index.saturating_add(1);
594 self.cluster_index = 0;
595 self.attribute_index = 0;
596 continue;
597 };
598 if self
599 .cluster_filter
600 .is_some_and(|wanted| wanted != cluster.id)
601 {
602 self.cluster_index = self.cluster_index.saturating_add(1);
603 self.attribute_index = 0;
604 continue;
605 }
606
607 // A cluster's attributes are its own followed by §7.13's globals, so the index
608 // walks past the end of the descriptor's slice into that fixed tail.
609 let own = cluster.attributes.len();
610 let attribute = match self.attribute_index.checked_sub(own) {
611 Some(global) => crate::dm::global::ATTRIBUTE_IDS.get(global).copied(),
612 None => cluster.attributes.get(self.attribute_index).map(|a| a.id),
613 };
614 let Some(attribute) = attribute else {
615 self.cluster_index = self.cluster_index.saturating_add(1);
616 self.attribute_index = 0;
617 continue;
618 };
619 self.attribute_index = self.attribute_index.saturating_add(1);
620
621 if self
622 .attribute_filter
623 .is_some_and(|wanted| wanted != attribute)
624 {
625 continue;
626 }
627
628 return Some(Resolved {
629 endpoint: endpoint.id,
630 cluster,
631 attribute,
632 });
633 }
634 }
635}