Skip to main content

matter_kit/im/
server.rs

1//! Serving a Read: from a request path to a report (Core §8.4.3.2).
2//!
3//! §8.4.3.2 spells out the processing in fifteen numbered steps, and the shape that falls
4//! out of them is not obvious until you notice one thing: **a concrete path and an expanded
5//! path are handled differently on failure.**
6//!
7//! > b. Else if the path is a concrete path … an AttributeStatusIB SHALL be generated with
8//! >    the UNSUPPORTED_ENDPOINT Status Code.
9//! >
10//! > c. Else perform Request Path Expansion and process each expanded existent path as
11//! >    follows: … the path SHALL be discarded.
12//!
13//! A client that asked for one specific attribute is *told* why it cannot have it. A client
14//! that asked for everything simply does not see it. That asymmetry is the privacy property
15//! of a wildcard read: merging the two would let a subject with no privilege over a cluster
16//! learn that the cluster exists by counting statuses.
17//!
18//! # The two access checks
19//!
20//! A concrete path is checked **twice**, and the first one is not redundant. §8.4.3.2 step
21//! b.i checks "assuming the required_privilege for the element is View, to determine whether
22//! the subject would have had at least some access", *before* looking at whether the element
23//! exists; step b.iii then checks the attribute's actual privilege. The order is what stops
24//! the existence checks in between from leaking: a subject with no access at all learns
25//! `UNSUPPORTED_ACCESS` rather than `UNSUPPORTED_CLUSTER`, and so cannot map a node it has
26//! no rights over.
27//!
28//! # Chunking
29//!
30//! A whole-node wildcard does not fit in one message, and §4.4.4 caps a UDP message at the
31//! 1280-octet IPv6 minimum MTU. §10.2.3 answers that by *chunking* — "maximally packing these
32//! information blocks (IBs) into a series of 'data' messages" — so filling one message and
33//! stopping is not an option a conforming server has: `MoreChunkedMessages` is a promise that
34//! another message follows, and a client that is told it waits.
35//!
36//! So the boundary is found by *size*, by writing a block and rolling it back when it does not
37//! fit ([`TlvWriter::checkpoint`](crate::tlv::TlvWriter::checkpoint)), and a [`ReadCursor`]
38//! records where to resume. [`Server::serve_chunk`] is the loop; [`Server::serve`] is the
39//! one-message convenience for reads known to be small.
40//!
41//! Progress is guaranteed even when a single value is larger than an entire message: a list is
42//! split per §10.6.4.3.1, and a value that cannot be split is refused with
43//! `RESOURCE_EXHAUSTED` for its own path rather than stalling the read.
44//!
45//! # What this does not do
46//!
47//! Events and `DataVersionFilter`s. Access control is a trait the caller supplies, because the
48//! Access Control cluster (§9.10) does not exist yet — and making it a parameter means the
49//! ordering above is testable without it.
50
51use crate::dm::{AttributeQualities, Node, Privilege};
52use crate::error::{ErrorCode, Result, bail};
53use crate::im::ib::{
54    AttributeData, AttributeReport, AttributeStatus, CommandData, CommandStatus, InvokeResponse,
55    StatusIb,
56};
57use crate::im::path::AttributePath;
58use crate::im::status::Status;
59use crate::tlv::{ContainerKind, Tag, TlvWriter};
60
61/// Who is asking, and what they may have.
62///
63/// A trait rather than a concrete type because the answer comes from the Access Control
64/// cluster (§9.10), which does not exist yet — and because making it a parameter is what
65/// lets §8.4.3.2's check *ordering* be tested without one.
66pub trait AccessControl {
67    /// Whether the subject holds `required` over this path.
68    ///
69    /// §6.6.1's subsumption is the implementor's to apply: a subject granted Administer
70    /// holds every lower privilege, which [`Privilege::grants`] expresses.
71    fn allows(&self, path: &AttributePath, required: Privilege) -> Outcome;
72}
73
74/// What an access check decided (§8.4.3.2).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum Outcome {
77    /// The subject may proceed.
78    Granted,
79    /// "If the outcome is AccessDenied, an AttributeStatusIB SHALL be generated with the
80    /// UNSUPPORTED_ACCESS Status Code."
81    Denied,
82    /// "Else if the outcome is AccessRestricted, an AttributeStatusIB SHALL be generated
83    /// with the ACCESS_RESTRICTED Status Code" — an Access Restriction List (§6.6.3).
84    Restricted,
85}
86
87impl Outcome {
88    /// The status §8.4.3.2 pairs with a refusal, or `None` when it granted.
89    #[must_use]
90    pub const fn status(self) -> Option<Status> {
91        match self {
92            Self::Granted => None,
93            Self::Denied => Some(Status::UnsupportedAccess),
94            Self::Restricted => Some(Status::AccessRestricted),
95        }
96    }
97}
98
99/// An access control that grants everything, for a node with no Access Control cluster yet.
100///
101/// **Not a default.** A commissioned node must consult §9.10, and this is here so that the
102/// path-processing rules can be exercised on their own — and so that the PASE session's
103/// implicit administrator privilege during commissioning (§6.6.2.4) has something to be.
104#[derive(Debug, Clone, Copy, Default)]
105pub struct AllowAll;
106
107impl AccessControl for AllowAll {
108    fn allows(&self, _path: &AttributePath, _required: Privilege) -> Outcome {
109        Outcome::Granted
110    }
111}
112
113/// What a write does to the attribute it names (§10.6.4.3.1's Change enumeration).
114///
115/// The distinction exists because a list may be larger than one message, so §10.6.4.3.1 lets
116/// a client send it as a series of blocks: one that replaces the list, then one per item. The
117/// two are told apart *only* by whether the path carries `ListIndex`, which is why this has
118/// to reach the cluster — the data alone cannot say which was meant.
119///
120/// For an attribute that is not a list there is only [`WriteOp::Replace`], and it means what
121/// a write has always meant.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
123pub enum WriteOp {
124    /// `ListIndex` omitted — §10.6.4.3.1's REPLACE.
125    ///
126    /// "Path SHALL refer to a list with ListIndex omitted and Data SHALL contain new values
127    /// that will replace the existing contents of the list." An empty array therefore clears
128    /// the list, which is how the item-by-item encoding starts.
129    #[default]
130    Replace,
131    /// `ListIndex` present and null — §10.6.4.3.1's ADD.
132    ///
133    /// "Path SHALL refer to a list with ListIndex containing a value of null and Data
134    /// containing the new value of the list item that will be added to the list." The item is
135    /// appended; §8.7.3.3 requires the blocks be "processed in the order conveyed", so the
136    /// list ends up in the order the client sent.
137    Append,
138}
139
140impl WriteOp {
141    /// The operation a path names, or `None` when its `ListIndex` is one the spec forbids.
142    ///
143    /// §10.6.4.3.1: "ListIndex is currently only allowed to be omitted or null. Any other
144    /// value SHALL be interpreted as an error." Writing *at* an index is not a thing a client
145    /// may ask for, and silently treating it as a replace would let one item's write wipe the
146    /// list.
147    const fn of(path: &AttributePath) -> Option<Self> {
148        match path.list_index {
149            None => Some(Self::Replace),
150            Some(crate::im::ListIndex::Append) => Some(Self::Append),
151            Some(crate::im::ListIndex::At(_)) => None,
152        }
153    }
154}
155
156/// Something that happened to the **node**, which every cluster holding state scoped to it
157/// has to react to.
158///
159/// Read, write and invoke are driven by a peer; these three are driven by the node's own
160/// life, and every one of them is a rule the specification states once and expects every
161/// cluster to obey:
162///
163/// * §11.18.6.12 — `RemoveFabric` "SHALL remove all associated data" of the fabric. All of
164///   it: scenes, groups, bindings, ICD registrations, OTA providers, TLS endpoints, group
165///   keys, access control entries. A cluster that keeps one entry hands it to whoever is
166///   assigned that fabric index next.
167/// * §11.10.7.2.2 — an expired fail-safe rolls back what the abandoned commissioner staged.
168/// * §11.10.7.6 — `CommissioningComplete` makes it permanent.
169///
170/// Delivered to *every* member of a handler tuple rather than routed by cluster id, because
171/// unlike a path this is not addressed to one cluster: it is a fact about the node that all
172/// of them are downstream of. Which is also why it is a method on [`ClusterHandler`] and not
173/// a separate trait — a device's cluster tuple is the one place that already names every
174/// cluster it has, so the fan-out cannot be missed by forgetting to register something. The
175/// CHIP SDK registers each cluster with `FabricTable::AddFabricDelegate`, and its own issue
176/// tracker records what an unregistered cluster costs.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178#[non_exhaustive]
179pub enum Lifecycle {
180    /// A fabric was removed, or rolled back before it was ever complete (§11.18.6.12,
181    /// §11.10.7.2.2 step 3).
182    ///
183    /// Every cluster forgets everything scoped to that index. It is not "the accessing
184    /// fabric": an administrator may remove another's, and a rollback removes one nobody was
185    /// speaking on.
186    FabricRemoved(crate::msg::FabricIndex),
187    /// The fail-safe expired without `CommissioningComplete` (§11.10.7.2.2).
188    ///
189    /// A cluster that staged something reverts it. `fabric` is the fail-safe's own fabric,
190    /// when it had one — a fail-safe armed over PASE before `AddNOC` has none.
191    FailSafeExpired {
192        /// The fabric the fail-safe was armed on, if it had reached one.
193        fabric: Option<crate::msg::FabricIndex>,
194    },
195    /// `CommissioningComplete` succeeded on `fabric` (§11.10.7.6).
196    ///
197    /// Whatever was staged under the fail-safe is now the device's permanent state, so the
198    /// snapshot it would have been rolled back to is dropped. A cluster that never drops it
199    /// reverts to *that* snapshot at the next expiry, however many commissionings later —
200    /// which is how a device loses the network credentials it has been using for a month.
201    CommissioningComplete(crate::msg::FabricIndex),
202}
203
204/// What a device's clusters actually do.
205///
206/// One trait rather than three, because a device has one cluster implementation table and
207/// not three. Write and invoke have defaults that refuse, so a read-only node implements one
208/// method — and a cluster that forgets to implement `write` refuses writes rather than
209/// silently accepting them.
210///
211/// Every method returns a [`Status`] rather than an error, because §8.4.3.2, §8.7.3.2 and
212/// §8.8.2.3 all require one path's failure to be reported *for that path* without failing
213/// the action. An error type would force the whole request to fail.
214pub trait ClusterHandler {
215    /// Writes the value of `resolved`'s attribute under `tag`.
216    ///
217    /// The global attributes of §7.13 never reach here: they are synthesised from the
218    /// descriptor ([`dm::global`](crate::dm::global)), so a cluster does not implement its
219    /// own `ClusterRevision`.
220    fn read(
221        &self,
222        resolved: &crate::dm::Resolved<'_>,
223        ctx: &InteractionContext<'_>,
224        w: &mut TlvWriter<'_>,
225        tag: Tag,
226    ) -> core::result::Result<(), Status>;
227
228    /// The cluster instance's data version (§7.10.3), if it tracks one.
229    ///
230    /// `None` omits the field, which a report may do; a client then cannot use a
231    /// `DataVersionFilter` against that cluster, which costs bandwidth rather than
232    /// correctness. It also means §8.7.3.2 step b.vi's `DATA_VERSION_MISMATCH` check cannot
233    /// fire, so a write is never rejected for staleness.
234    fn data_version(&self, _resolved: &crate::dm::Resolved<'_>) -> Option<u32> {
235        None
236    }
237
238    /// Writes `data` — the encoded TLV element, tag included — into the attribute.
239    ///
240    /// `op` says *how*, and a cluster holding a list must honour it. §10.6.4.3.1 gives a
241    /// client two ways to write a list, and they are told apart only by whether the path
242    /// carries `ListIndex`: without it the data replaces the whole list, with it (null) the
243    /// data is one more item to add. A cluster that ignores `op` and replaces on every block
244    /// keeps only the last item of a list written item by item — which is how an access
245    /// control list arrives, so the failure is a device that silently drops every ACL entry
246    /// but one.
247    ///
248    /// §8.7.3.3: a value outside the cluster's constraints is `CONSTRAINT_ERROR`; a value
249    /// that is well-typed but wrong for the device's current state is
250    /// [`Status::DynamicConstraintError`]. A list that cannot take another item is
251    /// [`Status::ResourceExhausted`].
252    fn write(
253        &self,
254        _resolved: &crate::dm::Resolved<'_>,
255        _data: &[u8],
256        _op: WriteOp,
257        _ctx: &InteractionContext<'_>,
258    ) -> core::result::Result<(), Status> {
259        Err(Status::UnsupportedWrite)
260    }
261
262    /// Runs a command.
263    ///
264    /// `fields` is the encoded `CommandFields` element, or `None` for a command that takes
265    /// none. The three outcomes are exactly §8.8.2.3's "Invoke Execution":
266    ///
267    /// * `Ok(None)` — the command succeeded and the cluster defines no response command, so
268    ///   a `CommandStatusIB` with `SUCCESS` is generated.
269    /// * `Ok(Some(id))` — the cluster defines a response command; its fields have been
270    ///   written under `tag` and `id` is its command id.
271    /// * `Err(status)` — a `CommandStatusIB` with that status.
272    ///
273    /// The error is a [`StatusIb`], not a bare [`Status`], because §10.6.17 lets a cluster
274    /// define its own codes alongside `FAILURE` — and some commands have no other way to
275    /// report why they refused. §11.19's `OpenCommissioningWindow` is the example: `Busy`,
276    /// `PAKEParameterError` and `WindowNotOpen` are cluster-specific codes, and it has no
277    /// response command to put them in. [`From<Status>`](StatusIb) makes the common case a
278    /// `?` away.
279    fn invoke(
280        &self,
281        _resolved: &crate::dm::ResolvedCommand<'_>,
282        _fields: Option<&[u8]>,
283        _ctx: &InteractionContext<'_>,
284        _w: &mut TlvWriter<'_>,
285        _tag: Tag,
286    ) -> core::result::Result<Option<crate::im::CommandId>, StatusIb> {
287        Err(Status::UnsupportedCommand.into())
288    }
289
290    /// Reacts to something that happened to the node (see [`Lifecycle`]).
291    ///
292    /// The default does nothing, which is right for every cluster whose state is not scoped
293    /// to a fabric and stages nothing under the fail-safe — most of them. There is no return
294    /// value: nothing here can fail in a way a caller could act on, and a cluster that could
295    /// not forget a fabric would have no way to keep it either.
296    fn on_lifecycle(&self, _event: Lifecycle) {}
297}
298
299/// A shared reference to a handler is a handler.
300///
301/// Which is what lets a device assemble its cluster table out of borrowed clusters — the
302/// clusters themselves own references to the fabric table, the key store and the fail-safe,
303/// so they are rarely cheap to move and there is no reason to.
304impl<T: ClusterHandler + ?Sized> ClusterHandler for &T {
305    fn read(
306        &self,
307        resolved: &crate::dm::Resolved<'_>,
308        ctx: &InteractionContext<'_>,
309        w: &mut TlvWriter<'_>,
310        tag: Tag,
311    ) -> core::result::Result<(), Status> {
312        (**self).read(resolved, ctx, w, tag)
313    }
314
315    fn data_version(&self, resolved: &crate::dm::Resolved<'_>) -> Option<u32> {
316        (**self).data_version(resolved)
317    }
318
319    fn write(
320        &self,
321        resolved: &crate::dm::Resolved<'_>,
322        data: &[u8],
323        op: WriteOp,
324        ctx: &InteractionContext<'_>,
325    ) -> core::result::Result<(), Status> {
326        (**self).write(resolved, data, op, ctx)
327    }
328
329    fn invoke(
330        &self,
331        resolved: &crate::dm::ResolvedCommand<'_>,
332        fields: Option<&[u8]>,
333        ctx: &InteractionContext<'_>,
334        w: &mut TlvWriter<'_>,
335        tag: Tag,
336    ) -> core::result::Result<Option<crate::im::CommandId>, StatusIb> {
337        (**self).invoke(resolved, fields, ctx, w, tag)
338    }
339
340    fn on_lifecycle(&self, event: Lifecycle) {
341        (**self).on_lifecycle(event);
342    }
343}
344
345/// What a handler needs to know about the interaction it is running inside.
346///
347/// Everything here is a fact about the *session and action*, not about the node: a cluster
348/// cannot read any of it for itself, and several of §11.18's commands are wrong without it.
349#[derive(Debug, Clone, Copy)]
350pub struct InteractionContext<'a> {
351    /// Whether this action is part of a Timed transaction (§8.7.4).
352    ///
353    /// The server has already refused anything that *requires* one and did not get it, so a
354    /// handler needs this only if it wants to impose its own rule.
355    pub timed: bool,
356    /// The fabric this interaction is scoped to, if any.
357    ///
358    /// `None` on a PASE session during commissioning, which is why §8.8.2.3 step b.v makes a
359    /// fabric-scoped command `UNSUPPORTED_ACCESS` when there is no accessing fabric.
360    pub fabric_index: Option<crate::msg::FabricIndex>,
361    /// Whether the transport can carry Large Messages (§7.7.5) — that is, whether it is TCP.
362    pub large_messages: bool,
363    /// Whether the request asked for fabric filtering (§7.19.1.8.2).
364    ///
365    /// A fabric-scoped list read with filtering on reports only the accessing fabric's
366    /// entries; with it off, the full list, each entry carrying its `FabricIndex` global
367    /// field. `ReadRequest` and `SubscribeRequest` both carry the flag, and a cluster that
368    /// ignored it would either leak every administrator's entries to one of them or hide from
369    /// a verifier the entries §6.4.10 requires it to read.
370    ///
371    /// Defaults to `false` — the unfiltered, full-list reading, which is what
372    /// `AttributePathIB`'s own default means.
373    pub fabric_filtered: bool,
374    /// Monotonic time, as of the moment the action started.
375    ///
376    /// Handed to the handler rather than read by it, because a cluster is not the thing that
377    /// owns a clock — and because a single action must see a single instant: §11.10.7.2's
378    /// fail-safe decides whether it is armed, re-arms it, and records progress, all of which
379    /// must agree about *when*.
380    ///
381    /// Defaults to [`Instant::ZERO`](crate::platform::Instant::ZERO), which is correct for a
382    /// node whose clusters have no deadlines — nothing consults it.
383    pub now: crate::platform::Instant,
384    /// Whether §6.4.10's Vendor ID Verification has been run against this peer.
385    ///
386    /// Only §11.25.6.1 consults it, and the default of `false` is the cautious one: a node that
387    /// assumed verification had happened would cross-sign an intermediate CA for an ecosystem
388    /// whose vendor nobody had checked.
389    pub vendor_id_verified: bool,
390    /// Which secure session this action arrived on.
391    ///
392    /// §11.18.6.7 scopes the CSR state to a session — "If no context or memory exists of a
393    /// prior CSRRequest command having been invoked **in the same secure session** as that
394    /// which is receiving this AddNOC or UpdateNOC invocation, then the Node SHALL … respond
395    /// with a StatusCode of MissingCsr". Without this, one administrator's `CSRRequest` could
396    /// be consumed by another's `AddNOC`.
397    pub session: Option<crate::msg::SessionId>,
398    /// The atomic write this action is part of, if any (§7.15.3).
399    ///
400    /// An attribute with the Atomic quality is writable *only* inside a claim covering it —
401    /// §7.15.3: "If a server receives a Write Request for an attribute that is not associated
402    /// with an Atomic Write State that is also associated with the client making the request,
403    /// the server SHALL return the error code INVALID_IN_STATE." Derived by the caller from
404    /// [`AtomicWrites::find`](crate::im::AtomicWrites::find), the same way `timed` is derived
405    /// from the window table, and asserted here.
406    pub atomic: Option<crate::im::atomic::ClaimRef<'a>>,
407    /// The peer's operational Node ID, when the session authenticated one (§6.6.6.3).
408    ///
409    /// `None` on a PASE session, which has no node id — only a passcode. §6.6.6.1.3's
410    /// Incoming Subject Descriptor is "deterministic based on both incoming message fields and
411    /// session metadata fields", and this is the session's half: it is what CASE *proved*,
412    /// never what a message claimed, which is the difference between an access decision and a
413    /// suggestion from the sender.
414    pub peer_node_id: Option<crate::msg::NodeId>,
415    /// The session's `AttestationChallenge` — the third key it derived (§4.14.2.6.2).
416    ///
417    /// §11.18.4.7, §11.18.4.9 and §11.18.6.16 all sign over it, and it "SHALL NOT be included
418    /// in any of the payloads conveyed": a signature made over it proves the signer is on
419    /// *this* session, which is precisely what stops a recorded attestation being replayed.
420    ///
421    /// Borrowed rather than copied, because it is key material with a
422    /// [`ZeroizeOnDrop`](zeroize::ZeroizeOnDrop) owner and there is no reason for a second
423    /// copy to exist.
424    pub attestation_challenge: Option<&'a crate::crypto::SymmetricKey>,
425    /// The strongest privilege the ISD holds over this path (§6.6.6.2), when the caller
426    /// computed one.
427    ///
428    /// The access check that admitted an action only proves the subject cleared the *required*
429    /// bar. A few clusters need to know how far above it the subject actually is, because the
430    /// specification gives administrators and managers different rules for the same command:
431    /// §9.16.7.1's `RegisterClient` demands a verification key from a manager and ignores one
432    /// from an administrator, so a server that could not tell them apart would either lock
433    /// administrators out or let a manager overwrite any registration it liked.
434    ///
435    /// Derived by the caller from the same access decision that admitted the action — with
436    /// [`Granted::highest`](crate::acl::Granted::highest) where the ACL engine is in use —
437    /// the way `timed` and `atomic` are derived. `None` means the caller did not compute one,
438    /// and a cluster that needs it must then take the cautious branch.
439    pub privilege: Option<Privilege>,
440    /// The group this action was addressed to, when it arrived as a groupcast (§4.16.1).
441    ///
442    /// `None` is a unicast. Several clusters branch on this rather than on anything in the
443    /// payload: §1.3.7.1.2 says the Groups cluster "SHALL NOT generate an AddGroupResponse
444    /// command" for a groupcast, and the reason is arithmetic — one multicast reaching twenty
445    /// lights would otherwise draw twenty unicast responses at once, on a network chosen for
446    /// low power rather than burst capacity.
447    ///
448    /// §8.8.2.2 also forbids a groupcast Invoke from carrying a concrete endpoint or expecting
449    /// any response at all, so a cluster that answered anyway would be answering a request the
450    /// client is not listening for.
451    pub group: Option<crate::msg::GroupId>,
452    /// §8.4.3.3 step 6.a.i's `EventFilters`, still encoded, as the request carried them.
453    ///
454    /// A client that already holds events up to some number sends this so the node does not
455    /// resend them — the event log's equivalent of `DataVersionFilters`, and the only way a
456    /// client resuming after a gap avoids re-reading the whole ring.
457    pub event_filters: Option<&'a [u8]>,
458    /// §8.4.3.2 step 3.a's `DataVersionFilters`, still encoded, as the request carried them.
459    ///
460    /// Kept as TLV rather than a decoded list because this type is `Copy` and the crate does
461    /// not allocate: the filters are walked once per reported attribute, which is cheap for the
462    /// handful a client sends and costs nothing when there are none.
463    ///
464    /// A client sends these to say "do not send me a cluster I already have", which is the
465    /// only mechanism in the interaction model that makes a wildcard read cheap on a device
466    /// that mostly has not changed. A server that decodes them and ignores them is correct
467    /// about every value it sends and wrong about the bandwidth, on exactly the reads that
468    /// matter most.
469    pub data_version_filters: Option<&'a [u8]>,
470}
471
472impl Default for InteractionContext<'_> {
473    /// The same as [`InteractionContext::new`], so the two cannot drift apart.
474    fn default() -> Self {
475        Self::new()
476    }
477}
478
479impl<'a> InteractionContext<'a> {
480    /// The context of an action on an unauthenticated, untimed session.
481    ///
482    /// A starting point for the `with_*` builders. This is `const`, and the builders are too,
483    /// because a device's fixed set of contexts is `const` data — and a `const` struct literal
484    /// has to name every field, so every field added here would otherwise be a breaking change
485    /// for anyone who wrote one.
486    #[must_use]
487    pub const fn new() -> Self {
488        Self {
489            timed: false,
490            fabric_index: None,
491            large_messages: false,
492            fabric_filtered: false,
493            now: crate::platform::Instant::ZERO,
494            session: None,
495            atomic: None,
496            peer_node_id: None,
497            attestation_challenge: None,
498            privilege: None,
499            group: None,
500            vendor_id_verified: false,
501            data_version_filters: None,
502            event_filters: None,
503        }
504    }
505
506    /// Carries §8.4.3.3 step 6.a.i's `EventFilters`, as the request encoded them.
507    #[must_use]
508    pub const fn with_event_filters(mut self, filters: &'a [u8]) -> Self {
509        self.event_filters = Some(filters);
510        self
511    }
512
513    /// Carries §8.4.3.2 step 3.a's `DataVersionFilters`, as the request encoded them.
514    #[must_use]
515    pub const fn with_data_version_filters(mut self, filters: &'a [u8]) -> Self {
516        self.data_version_filters = Some(filters);
517        self
518    }
519
520    /// Marks the action as a groupcast addressed to `group` (§4.16.1).
521    #[must_use]
522    pub const fn with_group(mut self, group: crate::msg::GroupId) -> Self {
523        self.group = Some(group);
524        self
525    }
526
527    /// Records the strongest privilege the ISD holds over this path.
528    #[must_use]
529    pub const fn with_privilege(mut self, privilege: Privilege) -> Self {
530        self.privilege = Some(privilege);
531        self
532    }
533
534    /// Records that §6.4.10's Fabric Table Vendor ID Verification Procedure was run against
535    /// the peer that sent this action.
536    ///
537    /// §11.25.6.1 is the one place that asks: `ICACCSRRequest` refuses with `JfVidNotVerified`
538    /// until the peer has proved which vendor owns the fabric it is administering from. The
539    /// procedure itself is a challenge and a signature over an exchange this layer does not
540    /// see, so the answer comes in with the action rather than being derived here.
541    #[must_use]
542    pub const fn with_vendor_id_verified(mut self) -> Self {
543        self.vendor_id_verified = true;
544        self
545    }
546
547    /// Marks the action as part of a Timed transaction (§8.7.4).
548    #[must_use]
549    pub const fn timed(mut self) -> Self {
550        self.timed = true;
551        self
552    }
553
554    /// Sets the accessing fabric.
555    #[must_use]
556    pub const fn with_fabric(mut self, fabric_index: crate::msg::FabricIndex) -> Self {
557        self.fabric_index = Some(fabric_index);
558        self
559    }
560
561    /// Marks the transport as able to carry Large Messages (§7.7.5) — that is, TCP.
562    #[must_use]
563    pub const fn with_large_messages(mut self) -> Self {
564        self.large_messages = true;
565        self
566    }
567
568    /// Asks for §7.19.1.8.2's fabric filtering on a fabric-scoped list read.
569    #[must_use]
570    pub const fn fabric_filtered(mut self) -> Self {
571        self.fabric_filtered = true;
572        self
573    }
574
575    /// Sets the instant the action started.
576    #[must_use]
577    pub const fn at(mut self, now: crate::platform::Instant) -> Self {
578        self.now = now;
579        self
580    }
581
582    /// Sets the secure session this action arrived on.
583    #[must_use]
584    pub const fn on_session(mut self, session: crate::msg::SessionId) -> Self {
585        self.session = Some(session);
586        self
587    }
588
589    /// Marks this action as writing under an open atomic claim (§7.15.3).
590    #[must_use]
591    pub const fn under_claim(mut self, claim: crate::im::atomic::ClaimRef<'a>) -> Self {
592        self.atomic = Some(claim);
593        self
594    }
595
596    /// Sets the peer's operational Node ID, as CASE proved it (§6.6.6.3).
597    #[must_use]
598    pub const fn from_peer(mut self, peer_node_id: crate::msg::NodeId) -> Self {
599        self.peer_node_id = Some(peer_node_id);
600        self
601    }
602
603    /// Attaches the session's `AttestationChallenge` (§4.14.2.6.2).
604    #[must_use]
605    pub const fn with_attestation_challenge(
606        mut self,
607        challenge: &'a crate::crypto::SymmetricKey,
608    ) -> Self {
609        self.attestation_challenge = Some(challenge);
610        self
611    }
612}
613
614/// How far a read got.
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub struct ReadOutcome {
617    /// How many reports were written.
618    pub reports: usize,
619    /// Whether the message filled before every path was served.
620    ///
621    /// When this is set the message carries `MoreChunkedMessages` (§10.2.3), which promises
622    /// the client a continuation — so a caller that sets it must send one.
623    /// [`Server::serve_chunk`] produces it; [`ReadCursor`] is where it resumes.
624    pub truncated: bool,
625    /// One past the highest event number this message carried, or `0` if it carried none.
626    ///
627    /// §8.5.3.4's bookmark: the next report over the same subscription starts here, so an event
628    /// is delivered once. [`Server::report_chunk`] records it on the subscription itself, so
629    /// [`Subscription::reported`](crate::im::subscription::Subscription::reported) does not ask
630    /// a caller for a number only the server has.
631    pub events_through: u64,
632}
633
634/// Where a chunked read stopped, and where its next message resumes.
635///
636/// Core §10.2.3 splits a report "into multiple messages at logical boundaries due to the
637/// size limitations imposed by IPv6 for UDP packets", and §4.4.4 fixes that size at the
638/// 1280-octet IPv6 minimum MTU. A whole-node wildcard does not fit in one message and is not
639/// supposed to: it is chunked, "maximally packing" information blocks into each message,
640/// with `MoreChunkedMessages` set on every message but the last.
641///
642/// A cursor is three positions: which request path is being served, how far into that path's
643/// wildcard expansion, and — when one list attribute is itself too big for a message — how
644/// many of its items have gone out. It is `Copy` and holds no borrows, so a device can park
645/// one between messages while it waits for the `StatusResponse` that §10.2.3 requires
646/// before the next chunk.
647///
648/// ```no_run
649/// # use matter_kit::im::{ReadCursor, Server, AttributePath, InteractionContext};
650/// # fn go<A: matter_kit::im::AccessControl, H: matter_kit::im::ClusterHandler>(
651/// #     server: Server<'_, A, H>, paths: &[AttributePath],
652/// #     scratch: &mut [u8], buf: &mut [u8]) -> Result<(), matter_kit::Error> {
653/// let mut cursor = ReadCursor::START;
654/// while !cursor.is_done() {
655///     let (bytes, outcome) = server.serve_chunk(
656///         paths.iter().copied().map(Ok), &InteractionContext::default(),
657///         None, &mut cursor, scratch, buf)?;
658///     send(bytes);
659///     // §10.2.3: "each data message requires a response before the next data message
660///     // can be sent" — await the StatusResponse here.
661///     let _ = outcome;
662/// }
663/// # Ok(()) }
664/// # fn send(_: &[u8]) {}
665/// ```
666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
667pub struct ReadCursor {
668    /// Which of the request's paths is being served.
669    path: usize,
670    /// How far into that path's wildcard expansion.
671    expansion: crate::dm::ExpandCursor,
672    /// How many items of an oversized list have been sent, once one is being split.
673    list: Option<u32>,
674    /// Which of the request's *event* paths is being served, and the lowest event number not
675    /// yet reported from it.
676    ///
677    /// Separate from `path` because §10.7.3's `ReportData` carries two arrays and a series may
678    /// end part-way through either. The number rather than an index because that is what
679    /// resuming an event log means: records are identified by §7.14.1.1's monotonic number, and
680    /// a record added between two chunks must not shift the position of the ones after it.
681    event_path: usize,
682    event_from: u64,
683    /// Whether every path has been served.
684    done: bool,
685}
686
687impl ReadCursor {
688    /// Starts the event half of a report at `number` (§8.5.3.4's bookmark).
689    pub const fn set_event_from(&mut self, number: u64) {
690        self.event_from = number;
691    }
692
693    /// The lowest event number this cursor has **not** reported.
694    ///
695    /// For a device driving [`Server::serve_chunk_with_events`] itself. A subscription's
696    /// bookmark is kept by the subscription — [`Server::report_chunk`] records it and
697    /// [`Subscription::reported`](crate::im::Subscription::reported) applies it — so that it
698    /// moves with what actually went out and no caller has to carry the number between the two.
699    #[must_use]
700    pub const fn event_from(&self) -> u64 {
701        self.event_from
702    }
703
704    /// The start of a read: nothing served yet.
705    pub const START: Self = Self {
706        path: 0,
707        expansion: crate::dm::ExpandCursor::START,
708        list: None,
709        event_path: 0,
710        event_from: 0,
711        done: false,
712    };
713
714    /// Whether the read is complete, so no further chunk is owed.
715    ///
716    /// This is the loop condition: a cursor becomes done on the message that does *not*
717    /// carry `MoreChunkedMessages`.
718    #[must_use]
719    pub const fn is_done(&self) -> bool {
720        self.done
721    }
722}
723
724impl Default for ReadCursor {
725    fn default() -> Self {
726        Self::START
727    }
728}
729
730/// The members of an encoded list value, each yielded as its own raw TLV element.
731///
732/// Used to split a list too large for one message (§10.6.4.3.1). The items are yielded as
733/// slices of the value already encoded in scratch, so splitting a list costs no second copy
734/// of it — [`TlvWriter::raw_element_retagged`] does the re-tagging as it writes.
735struct ListItems<'a> {
736    reader: crate::tlv::TlvReader<'a>,
737    done: bool,
738}
739
740impl<'a> ListItems<'a> {
741    /// Reads `encoded` — one `Data [2]` element — as a list, or `None` if it is not one.
742    fn new(encoded: &'a [u8]) -> Option<Self> {
743        let mut reader = crate::tlv::TlvReader::new_in(encoded, ContainerKind::Structure);
744        let first = reader.next_element().ok()??;
745        if first.value.container() != Some(ContainerKind::Array) {
746            return None;
747        }
748        Some(Self {
749            reader,
750            done: false,
751        })
752    }
753}
754
755impl<'a> Iterator for ListItems<'a> {
756    type Item = Result<&'a [u8]>;
757
758    fn next(&mut self) -> Option<Self::Item> {
759        if self.done {
760            return None;
761        }
762        let start = self.reader.position();
763        let element = match self.reader.next_element() {
764            Ok(Some(element)) => element,
765            Ok(None) => {
766                self.done = true;
767                return None;
768            }
769            Err(e) => {
770                self.done = true;
771                return Some(Err(e));
772            }
773        };
774        if element.value == crate::tlv::Value::EndOfContainer {
775            self.done = true;
776            return None;
777        }
778        if let Err(e) = self.reader.skip_value(&element) {
779            self.done = true;
780            return Some(Err(e));
781        }
782        match self.reader.slice_from(start) {
783            Ok(bytes) => Some(Ok(bytes)),
784            Err(e) => {
785                self.done = true;
786                Some(Err(e))
787            }
788        }
789    }
790}
791
792/// One message being packed, and the two limits that end it.
793///
794/// §10.2.3's boundary is a size — "maximally packing these information blocks (IBs) into a
795/// series of 'data' messages" — so the real test of whether one more block fits is to write
796/// it and see. [`TlvWriter::checkpoint`] makes that non-destructive: a block that does not
797/// fit is rolled back, leaving the message that was already packed intact.
798struct Chunk<'w, 'b> {
799    w: &'w mut TlvWriter<'b>,
800    reports: usize,
801    limit: usize,
802    /// Set when a block did not fit, which ends this message and saves a cursor.
803    full: bool,
804}
805
806/// Writes one information block, undoing it if it does not fit.
807///
808/// A block that overruns the message must leave no trace: the writer documents that a failed
809/// write leaves "the buffer's contents unspecified", so without the rollback the blocks
810/// already packed would be corrupted and the whole action would have to fail. With it, a full
811/// buffer is an ordinary boundary — the caller reports `truncated` and the message it has is
812/// still valid.
813///
814/// `Ok(false)` means the message is full. Errors other than running out of room are real
815/// failures and propagate.
816fn put_block(
817    w: &mut TlvWriter<'_>,
818    responses: &mut usize,
819    limit: usize,
820    f: impl FnOnce(&mut TlvWriter<'_>) -> Result<()>,
821) -> Result<bool> {
822    if *responses >= limit {
823        return Ok(false);
824    }
825    let checkpoint = w.checkpoint();
826    match f(w) {
827        Ok(()) => {
828            *responses = responses.saturating_add(1);
829            Ok(true)
830        }
831        Err(e) if e.code() == ErrorCode::BufferTooSmall => {
832            w.rollback(&checkpoint);
833            Ok(false)
834        }
835        Err(e) => Err(e),
836    }
837}
838
839impl Chunk<'_, '_> {
840    /// Writes one information block, undoing it if it does not fit.
841    ///
842    /// `Ok(false)` means the message is full — the caller stops and records where.
843    fn put(&mut self, f: impl FnOnce(&mut TlvWriter<'_>) -> Result<()>) -> Result<bool> {
844        let mut reports = self.reports;
845        let fitted = put_block(self.w, &mut reports, self.limit, f)?;
846        self.reports = reports;
847        if !fitted {
848            self.full = true;
849        }
850        Ok(fitted)
851    }
852
853    /// Whether anything has been packed into this message yet.
854    ///
855    /// A message that fills before its *first* block would make no progress, and the read
856    /// would never terminate. That is the case §10.6.4.3.1's list encoding exists for, and
857    /// failing that the one `RESOURCE_EXHAUSTED` answers.
858    const fn is_empty(&self) -> bool {
859        self.reports == 0
860    }
861}
862
863/// A server that answers interactions against one node.
864///
865/// The node, the access control and the cluster handler are all long-lived — a device has
866/// one of each for its whole life — so they are held here rather than threaded through every
867/// call. What varies per interaction is the paths and the buffers.
868#[derive(Debug, Clone, Copy)]
869pub struct Server<'a, A, H> {
870    /// The data model being served.
871    pub node: Node<'a>,
872    /// Who is asking, and what they may have.
873    pub access: &'a A,
874    /// The device's clusters.
875    pub handler: &'a H,
876    /// The most reports one message may carry, on top of what fits in its buffer.
877    ///
878    /// A second, coarser bound than the buffer: both end a chunk, whichever comes first, and
879    /// neither loses anything, because [`Server::serve_chunk`] resumes from a
880    /// [`ReadCursor`]. Bounding a message by *bytes* is what §10.2.3 actually asks for, so
881    /// `usize::MAX` here is a reasonable choice — the buffer decides. A smaller value is for
882    /// bounding the work a single response costs the peer that must parse it.
883    pub limit: usize,
884    /// §7.10.3's cluster data versions, for every cluster that does not track its own.
885    ///
886    /// `None` means a report carries a `DataVersion` only where a cluster supplied one. That is
887    /// legal — §10.6.4.1 makes the field omissible — and it is also how a node ends up
888    /// uncommissionable: the CHIP SDK's cluster-state cache is keyed by version and silently
889    /// drops an attribute that arrives without one, so a commissioner receives every attribute
890    /// it asked for and then reports each as missing. Give the server a table.
891    pub versions: Option<&'a dyn crate::dm::DataVersionSource>,
892    /// §7.14's event log, for the `EventRequests` half of a read or subscription.
893    ///
894    /// `None` is a node that reports no events, which is legal — §8.4.3.3 step 5 makes an
895    /// empty `EventRequests` an empty answer — and is the wrong answer for any node whose
896    /// clusters define events, because the client is told the log is empty rather than that
897    /// nobody is serving it.
898    pub events: Option<&'a dyn crate::dm::events::EventSource>,
899}
900
901impl<'a, A: AccessControl, H: ClusterHandler> Server<'a, A, H> {
902    /// A server over a node.
903    #[must_use]
904    pub const fn new(node: Node<'a>, access: &'a A, handler: &'a H, limit: usize) -> Self {
905        Self {
906            node,
907            access,
908            handler,
909            limit,
910            versions: None,
911            events: None,
912        }
913    }
914
915    /// Supplies §7.10.3's data versions for clusters that do not track their own.
916    ///
917    /// A cluster's own [`ClusterHandler::data_version`] still wins where it returns `Some`: a
918    /// cluster that knows when its data changed knows better than a table that is only told
919    /// about writes arriving over the wire.
920    #[must_use]
921    pub const fn with_data_versions(
922        mut self,
923        versions: &'a dyn crate::dm::DataVersionSource,
924    ) -> Self {
925        self.versions = Some(versions);
926        self
927    }
928
929    /// Supplies §7.14's event log, so a read or subscription can answer `EventRequests`.
930    ///
931    /// Without it every event path is answered as though the node had recorded nothing, which
932    /// a client cannot tell from a node that genuinely has.
933    #[must_use]
934    pub const fn with_events(mut self, events: &'a dyn crate::dm::events::EventSource) -> Self {
935        self.events = Some(events);
936        self
937    }
938
939    /// Serves one request path into an open `AttributeReports` array, resuming at `cursor`.
940    ///
941    /// Follows §8.4.3.2 step 1 exactly: a concrete path gets a status on failure, an expanded
942    /// one is discarded.
943    ///
944    /// Returns `true` when the path was served to the end, `false` when the message filled
945    /// first — in which case `cursor` names where to carry on.
946    fn serve_path_chunked(
947        &self,
948        path: &AttributePath,
949        ctx: &InteractionContext<'_>,
950        chunk: &mut Chunk<'_, '_>,
951        cursor: &mut ReadCursor,
952        scratch: &mut [u8],
953    ) -> Result<bool> {
954        // §10.6.2.1's tag compression is provisional and not resolved here. A path that sets
955        // it has fields whose meaning depends on an earlier path in the same action, and
956        // treating an inherited field as a wildcard would read the path as far broader than
957        // it says.
958        //
959        // How it is refused depends on whether it *can* be named. §8.2.1 requires that "each
960        // path indicated by the Report Data action SHALL be a Concrete Path", so a status
961        // may only carry a path that is one:
962        //
963        // * All of endpoint, cluster and attribute present — nothing is omitted, so nothing
964        //   would be inherited and the flag is inert. The path can be named, so it is,
965        //   with `INVALID_ACTION`.
966        // * Anything missing — its value "SHALL be set to the value for that tag in the last
967        //   AttributePathIB that had EnableTagCompression not present or set to false", which
968        //   this crate does not track, and which §10.6.2.1 says "MAY still be missing. In
969        //   that case … they indicate wildcard semantics". So it cannot be named concretely,
970        //   and echoing it would put a wildcard in a report. It is discarded instead —
971        //   §8.4.3.2 step 1c's treatment of any expanded path that cannot be served.
972        if path.enable_tag_compression {
973            return if path.concrete().is_some() {
974                self.write_status(chunk, path, Status::InvalidAction)
975            } else {
976                Ok(true)
977            };
978        }
979
980        match path.concrete() {
981            Some(concrete) => {
982                // A concrete path is one attribute, but that attribute may still be a list
983                // too large for a message, so it carries the list cursor too.
984                self.serve_concrete(path, concrete, ctx, chunk, cursor, scratch)
985            }
986            None => {
987                let mut expand = self.node.expand_from(path, cursor.expansion);
988                loop {
989                    // Taken *before* the step, so a path that does not fit is resumed rather
990                    // than skipped.
991                    let resume = expand.cursor();
992                    let Some(resolved) = expand.next() else {
993                        cursor.expansion = crate::dm::ExpandCursor::START;
994                        return Ok(true);
995                    };
996                    let concrete = resolved.path();
997                    let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
998                        continue;
999                    };
1000                    // §8.4.3.2 step c.i: "If the path indicates attribute data that is not
1001                    // readable, then the path SHALL be discarded."
1002                    let Some(required) = descriptor.access.read else {
1003                        continue;
1004                    };
1005                    // step c.ii: "If the outcome is either AccessDenied or AccessRestricted,
1006                    // then the path SHALL be discarded." No status — silence is the point.
1007                    if self.access.allows(&concrete, required) != Outcome::Granted {
1008                        continue;
1009                    }
1010                    if !self.write_data(&resolved, ctx, chunk, cursor, scratch)? {
1011                        cursor.expansion = resume;
1012                        return Ok(false);
1013                    }
1014                }
1015            }
1016        }
1017    }
1018
1019    fn serve_concrete(
1020        &self,
1021        path: &AttributePath,
1022        concrete: (
1023            crate::im::EndpointId,
1024            crate::im::ClusterId,
1025            crate::im::AttributeId,
1026        ),
1027        ctx: &InteractionContext<'_>,
1028        chunk: &mut Chunk<'_, '_>,
1029        cursor: &mut ReadCursor,
1030        scratch: &mut [u8],
1031    ) -> Result<bool> {
1032        let (endpoint, cluster, attribute) = concrete;
1033        // §8.4.3.2 step b.i — the *first* check, at View, before existence is examined. This
1034        // is what stops the existence checks below from telling a subject with no access at
1035        // all which clusters a node has.
1036        if let Some(status) = self.access.allows(path, Privilege::View).status() {
1037            return self.write_status(chunk, path, status);
1038        }
1039
1040        // step b.ii — existence, level by level, each with its own status.
1041        let resolved = match self.node.resolve(endpoint, cluster, attribute) {
1042            Ok(resolved) => resolved,
1043            Err(missing) => return self.write_status(chunk, path, missing.status()),
1044        };
1045        let Some(descriptor) = resolved.cluster.attribute(attribute) else {
1046            return self.write_status(chunk, path, Status::UnsupportedAttribute);
1047        };
1048        // step b.ii.E — "an attribute that is not readable" is UNSUPPORTED_READ, which is a
1049        // different answer from "does not exist".
1050        let Some(required) = descriptor.access.read else {
1051            return self.write_status(chunk, path, Status::UnsupportedRead);
1052        };
1053
1054        // step b.iii — the second check, at the attribute's actual privilege.
1055        if let Some(status) = self.access.allows(path, required).status() {
1056            return self.write_status(chunk, path, status);
1057        }
1058
1059        self.write_data(&resolved, ctx, chunk, cursor, scratch)
1060    }
1061
1062    /// §8.4.3.2 step 3.a: whether the requester already holds this cluster's data.
1063    ///
1064    /// > "If the DataVersionFilters field indicates DataVersionFilterIB entries with a Path
1065    /// > field that matches the path, where **all** matching entries have a DataVersion field
1066    /// > that matches the data version of the cluster instance in the path, then the path
1067    /// > SHALL be ignored"
1068    ///
1069    /// The quantifier is the whole rule, and `any` is the natural way to get it wrong. A client
1070    /// that sends two filters for one cluster with different versions has contradicted itself,
1071    /// and only one of those versions can be the one it holds — so it is told nothing and sent
1072    /// the data. `all` over an empty set is vacuously true, which would ignore *every* path, so
1073    /// a match must also exist: `matched` is what separates "no filter mentions this cluster"
1074    /// from "every filter that does, agrees".
1075    ///
1076    /// A path is *ignored*, not refused: no `AttributeDataIB` and no status. The requester
1077    /// already has the value and asked not to be told again.
1078    fn already_held(
1079        &self,
1080        resolved: &crate::dm::Resolved<'_>,
1081        ctx: &InteractionContext<'_>,
1082        data_version: Option<u32>,
1083    ) -> bool {
1084        let (Some(filters), Some(version)) = (ctx.data_version_filters, data_version) else {
1085            return false;
1086        };
1087        let Ok(entries) = crate::im::ArrayIter::new(
1088            filters,
1089            ContainerKind::Structure,
1090            crate::im::DataVersionFilter::decode,
1091        ) else {
1092            // Filters this node cannot read are filters it cannot honour. Sending the data is
1093            // the safe direction: the requester gets something it may already have, rather than
1094            // silently not getting something it does not.
1095            return false;
1096        };
1097        let mut matched = false;
1098        for entry in entries {
1099            let Ok(entry) = entry else {
1100                return false;
1101            };
1102            // §10.6.2's `ClusterPathIB`. An absent field matches anything, which is what makes
1103            // "every cluster on endpoint 0" expressible. `node` is not checked: a message that
1104            // reached this node is for this node.
1105            let path = &entry.path;
1106            if path.endpoint.is_some_and(|e| e != resolved.endpoint)
1107                || path.cluster.is_some_and(|c| c != resolved.cluster.id)
1108            {
1109                continue;
1110            }
1111            matched = true;
1112            if entry.data_version != version {
1113                return false;
1114            }
1115        }
1116        matched
1117    }
1118
1119    /// Writes one `AttributeDataIB`, or the status the cluster answered with.
1120    fn write_data(
1121        &self,
1122        resolved: &crate::dm::Resolved<'_>,
1123        ctx: &InteractionContext<'_>,
1124        chunk: &mut Chunk<'_, '_>,
1125        cursor: &mut ReadCursor,
1126        scratch: &mut [u8],
1127    ) -> Result<bool> {
1128        let path = resolved.path();
1129        // The cluster's own answer first; the node's table where it has none. §7.10.3 requires
1130        // a version per cluster instance, and a report without one is one the CHIP SDK discards.
1131        let data_version = self.handler.data_version(resolved).or_else(|| {
1132            self.versions
1133                .map(|v| v.version(resolved.endpoint, resolved.cluster.id))
1134        });
1135
1136        // §8.4.3.2 step 3.a, applied after the existence and access checks of step 2 — the
1137        // filter decides what to *send*, never what exists or who may see it.
1138        if self.already_held(resolved, ctx, data_version) {
1139            return Ok(true);
1140        }
1141
1142        // The value is built beside the message so that a cluster which runs out of room, or
1143        // refuses, leaves no half-written element in the report.
1144        let mut value = TlvWriter::new_in(scratch, ContainerKind::Structure);
1145        let global_written = crate::dm::global::encode(
1146            resolved.cluster,
1147            resolved.attribute,
1148            &mut value,
1149            Tag::Context(2),
1150        )?;
1151        if !global_written
1152            && let Err(status) = self
1153                .handler
1154                .read(resolved, ctx, &mut value, Tag::Context(2))
1155        {
1156            return self.write_status(chunk, &path, status);
1157        }
1158        let Ok(encoded) = value.finish() else {
1159            // A cluster that wrote nothing, or something unfinished, is a bug in the cluster
1160            // — but it must not corrupt the report, so it becomes a status like any other
1161            // refusal.
1162            return self.write_status(chunk, &path, Status::Failure);
1163        };
1164
1165        // The ordinary case: the whole value fits in one block, which §10.6.4.3.1 says
1166        // SHOULD be preferred "when it is possible to encode the entirety of the list in a
1167        // single AttributeDataIB that fits in a single message".
1168        if cursor.list.is_none() {
1169            let fitted = chunk.put(|w| {
1170                AttributeReport::Data(AttributeData {
1171                    data_version,
1172                    path,
1173                    data: encoded,
1174                })
1175                .encode(w)
1176            })?;
1177            if fitted {
1178                return Ok(true);
1179            }
1180            // It did not fit. If this message already carries something, the next one gets
1181            // a clean try at the whole value; only a value too big for an *empty* message
1182            // has to be split.
1183            if !chunk.is_empty() {
1184                return Ok(false);
1185            }
1186        }
1187
1188        self.write_list_in_chunks(&path, data_version, encoded, chunk, cursor)
1189    }
1190
1191    /// Splits one oversized list attribute across messages (§10.6.4.3.1).
1192    ///
1193    /// The spec's second encoding: "a series of AttributeDataIBs, with the first containing a
1194    /// path to the list itself and Data that is an empty array, which signals clearing the
1195    /// list, and subsequent AttributeDataIBs each containing a path to each list item with
1196    /// ListIndex being null, in order, and Data that contains the value of the list item."
1197    /// It is what §10.6.4.3.1 says SHOULD be used "when it is NOT possible to encode the
1198    /// entirety of the list in a single AttributeDataIB that fits in a single message".
1199    ///
1200    /// A value that is not a list cannot be split at all, and a single item that will not fit
1201    /// an empty message cannot either. Both would leave the read unable to make progress, so
1202    /// both answer `RESOURCE_EXHAUSTED` (§8.10.1) for that path and move on.
1203    fn write_list_in_chunks(
1204        &self,
1205        path: &AttributePath,
1206        data_version: Option<u32>,
1207        encoded: &[u8],
1208        chunk: &mut Chunk<'_, '_>,
1209        cursor: &mut ReadCursor,
1210    ) -> Result<bool> {
1211        let Some(items) = ListItems::new(encoded) else {
1212            // Not a list: nothing to split along. Telling the client the value exists but
1213            // cannot be sent is the honest answer, and it keeps the read moving.
1214            cursor.list = None;
1215            return self.write_status(chunk, path, Status::ResourceExhausted);
1216        };
1217
1218        // Step one, once per list: the empty array that clears it.
1219        if cursor.list.is_none() {
1220            let fitted = chunk.put(|w| {
1221                let mut empty = [0u8; 4];
1222                let mut v = TlvWriter::new_in(&mut empty, ContainerKind::Structure);
1223                v.start_array(Tag::Context(2))?;
1224                v.end_container()?;
1225                let empty = v.finish()?;
1226                AttributeReport::Data(AttributeData {
1227                    data_version,
1228                    path: *path,
1229                    data: empty,
1230                })
1231                .encode(w)
1232            })?;
1233            if !fitted {
1234                return Ok(false);
1235            }
1236            cursor.list = Some(0);
1237        }
1238
1239        // Step two: one block per item, with `ListIndex` null — §10.6.4.3.1's ADD.
1240        let sent = cursor.list.unwrap_or(0);
1241        for (index, item) in items.enumerate().skip(sent as usize) {
1242            let item = item?;
1243            let mut append = *path;
1244            append.list_index = Some(crate::im::ListIndex::Append);
1245            // Written out by hand rather than through `AttributeData`, because the item is
1246            // an anonymous member of the array it came from and has to be re-tagged into the
1247            // `Data [2]` slot on the way out.
1248            let fitted = chunk.put(|w| {
1249                w.start_structure(Tag::Anonymous)?;
1250                w.start_structure(Tag::Context(1))?;
1251                if let Some(version) = data_version {
1252                    w.unsigned(Tag::Context(0), u64::from(version))?;
1253                }
1254                append.encode(w, Tag::Context(1))?;
1255                w.raw_element_retagged(item, Tag::Context(2))?;
1256                w.end_container()?;
1257                w.end_container()
1258            })?;
1259            if !fitted {
1260                if chunk.is_empty() {
1261                    // One item alone will not fit an empty message. Nothing can send it, so
1262                    // say so rather than loop forever.
1263                    cursor.list = None;
1264                    return self.write_status(chunk, path, Status::ResourceExhausted);
1265                }
1266                cursor.list = Some(u32::try_from(index).unwrap_or(u32::MAX));
1267                return Ok(false);
1268            }
1269        }
1270        cursor.list = None;
1271        Ok(true)
1272    }
1273
1274    fn write_status(
1275        &self,
1276        chunk: &mut Chunk<'_, '_>,
1277        path: &AttributePath,
1278        status: Status,
1279    ) -> Result<bool> {
1280        chunk.put(|w| {
1281            AttributeReport::Status(AttributeStatus {
1282                path: *path,
1283                status: StatusIb::new(status),
1284            })
1285            .encode(w)
1286        })
1287    }
1288
1289    /// Whether any path in `paths` survives §8.4.3.2's steps 1 and 2 — exists, and the subject
1290    /// may read it.
1291    ///
1292    /// §8.4.3 step 2: "If no error-free existent paths remain, then AttributeRequests are
1293    /// considered empty", and step 7.a makes an empty Subscribe `INVALID_ACTION`. So a
1294    /// subscription to a cluster the subscriber cannot read is not an empty subscription that
1295    /// reports nothing — it is a malformed action, and answering it with a `SubscribeResponse`
1296    /// tells the subscriber it will hear about something it will never hear about.
1297    pub fn any_readable(
1298        &self,
1299        paths: impl IntoIterator<Item = Result<AttributePath>>,
1300    ) -> Result<bool> {
1301        for path in paths {
1302            let path = path?;
1303            for resolved in self.node.expand(&path) {
1304                let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
1305                    continue;
1306                };
1307                let Some(required) = descriptor.access.read else {
1308                    continue;
1309                };
1310                if self
1311                    .access
1312                    .allows(&resolved.path(), required)
1313                    .status()
1314                    .is_none()
1315                {
1316                    return Ok(true);
1317                }
1318            }
1319        }
1320        Ok(false)
1321    }
1322
1323    /// Serves one event request path into an open `EventReports` array (§8.4.3.3).
1324    ///
1325    /// Mirrors [`Server::serve_path_chunked`] and its asymmetry: a *concrete* path that names
1326    /// something this node does not have gets an `EventStatusIB`, an *expanded* one is
1327    /// discarded. A client that asked for a specific event deserves to know it does not exist;
1328    /// one that asked for "every event on the node" does not want a status for every cluster
1329    /// that has none.
1330    ///
1331    /// Returns `false` when the message filled, leaving `from` at the first record not yet
1332    /// reported.
1333    fn serve_event_path(
1334        &self,
1335        path: &crate::im::EventPath,
1336        ctx: &InteractionContext<'_>,
1337        chunk: &mut Chunk<'_, '_>,
1338        from: &mut u64,
1339    ) -> Result<bool> {
1340        let concrete = path.endpoint.zip(path.cluster).zip(path.event);
1341        if let Some(((endpoint, cluster), event)) = concrete {
1342            match self.node.resolve_event(endpoint, cluster, event) {
1343                Err(missing) => {
1344                    let status = match missing {
1345                        crate::dm::Missing::Endpoint => Status::UnsupportedEndpoint,
1346                        crate::dm::Missing::Cluster => Status::UnsupportedCluster,
1347                        crate::dm::Missing::Attribute => Status::UnsupportedEvent,
1348                    };
1349                    return self.write_event_status(chunk, path, status);
1350                }
1351                Ok(resolved) => {
1352                    // §8.4.3.3 step 4: the access check is the event's own, and a path the
1353                    // subject may not read is refused rather than silently empty.
1354                    if let Some(required) = resolved.event.access.read {
1355                        let attribute_path = AttributePath::attribute(endpoint, cluster, 0);
1356                        if let Some(status) = self.access.allows(&attribute_path, required).status()
1357                        {
1358                            return self.write_event_status(chunk, path, status);
1359                        }
1360                    }
1361                }
1362            }
1363        }
1364
1365        let Some(source) = self.events else {
1366            // No log to read. An expanded path says nothing; a concrete one has already been
1367            // resolved above, so the honest answer is that there are no records.
1368            return Ok(true);
1369        };
1370
1371        // §8.4.3.3 step 6.a: every queued record, lowest number first, minus the three
1372        // exceptions — the event filter (6.a.i), the path (6.a.ii) and fabric sensitivity
1373        // (6.a.iii). The store applies the last two; `min_number` is the first.
1374        // §8.4.3.3 step 6.a.i: "If the node indicated matches the Node information field of an
1375        // EventFilterIB from EventFilters, and the event number is less than the EventMin
1376        // field in the EventFilterIB" — the record is not reported.
1377        //
1378        // Several filters raise the floor together: the highest `EventMin` that applies wins,
1379        // because a record below *any* of them is excluded by that one.
1380        let floor = (*from).max(self.event_floor(ctx));
1381        let mut fitted = true;
1382        let mut next = floor;
1383        // §10.6.9.1 and §10.6.9.2's delta forms, against "the previous record" — which here
1384        // means the `EventDataIB` immediately before this one in the array. Records inside one
1385        // path's run are written consecutively, so the previous one is exactly that; the first
1386        // record of each run has nothing before it and takes the absolute form.
1387        //
1388        // The saving is real on the networks this crate targets: a system timestamp is
1389        // milliseconds since boot and grows without bound, while the gap between two records in
1390        // one report is usually small enough to encode in one or two octets.
1391        let mut previous: Option<crate::dm::events::Timestamp> = None;
1392        source.each_matching(path, ctx.fabric_index, floor, &mut |record| {
1393            let data = crate::im::EventData {
1394                path: crate::im::EventPath {
1395                    node: None,
1396                    endpoint: Some(record.endpoint),
1397                    cluster: Some(record.cluster),
1398                    event: Some(record.event),
1399                    is_urgent: None,
1400                },
1401                number: record.number,
1402                priority: record.priority as u8,
1403                timestamp: previous
1404                    .and_then(|before| record.timestamp.delta_from(before))
1405                    .unwrap_or_else(|| record.timestamp.absolute()),
1406                data: &record.data,
1407            };
1408            match chunk.put(|w| crate::im::EventReport::Data(data).encode(w)) {
1409                Ok(true) => {
1410                    next = record.number.saturating_add(1);
1411                    previous = Some(record.timestamp);
1412                    true
1413                }
1414                Ok(false) | Err(_) => {
1415                    fitted = false;
1416                    false
1417                }
1418            }
1419        });
1420        *from = next;
1421        Ok(fitted)
1422    }
1423
1424    /// The lowest event number §8.4.3.3 step 6.a.i lets this request see.
1425    ///
1426    /// Only entries that omit `Node` are applied. §10.6.6 says the tag "MAY be omitted if the
1427    /// target node of the path matches the NodeID of the server involved in the interaction",
1428    /// so an absent `Node` means *this* node and is the ordinary encoding. An entry naming a
1429    /// node cannot be checked here — the server does not know which of its fabrics' node ids
1430    /// the client meant — and the safe direction is to ignore it: an event sent twice is
1431    /// recoverable, one silently withheld is not.
1432    fn event_floor(&self, ctx: &InteractionContext<'_>) -> u64 {
1433        let Some(filters) = ctx.event_filters else {
1434            return 0;
1435        };
1436        let Ok(entries) = crate::im::ArrayIter::new(
1437            filters,
1438            ContainerKind::Structure,
1439            crate::im::EventFilter::decode,
1440        ) else {
1441            return 0;
1442        };
1443        let mut floor = 0;
1444        for entry in entries {
1445            let Ok(entry) = entry else {
1446                return 0;
1447            };
1448            if entry.node.is_none() {
1449                floor = floor.max(entry.event_min);
1450            }
1451        }
1452        floor
1453    }
1454
1455    /// Writes one `EventStatusIB`.
1456    fn write_event_status(
1457        &self,
1458        chunk: &mut Chunk<'_, '_>,
1459        path: &crate::im::EventPath,
1460        status: Status,
1461    ) -> Result<bool> {
1462        chunk.put(|w| {
1463            crate::im::EventReport::Status(crate::im::EventStatus {
1464                path: *path,
1465                status: StatusIb::new(status),
1466            })
1467            .encode(w)
1468        })
1469    }
1470
1471    /// Serves a whole `ReadRequest` into a **single** `ReportData` message.
1472    ///
1473    /// For reads known to be small. A read that does not fit is
1474    /// [`ErrorCode::ReportWouldChunk`] rather than a truncated message: a single message
1475    /// cannot honour `MoreChunkedMessages`, and emitting one anyway would promise the client
1476    /// a continuation that never arrives. Serve such a read with [`Server::serve_chunk`],
1477    /// which is the same processing across as many messages as it takes.
1478    ///
1479    /// A whole-node wildcard on any real device does not fit, so a server answering arbitrary
1480    /// client reads wants `serve_chunk` and not this.
1481    pub fn serve<'b>(
1482        &self,
1483        paths: impl IntoIterator<Item = Result<AttributePath>>,
1484        ctx: &InteractionContext<'_>,
1485        subscription_id: Option<u32>,
1486        scratch: &mut [u8],
1487        buf: &'b mut [u8],
1488    ) -> Result<(&'b [u8], ReadOutcome)> {
1489        let mut cursor = ReadCursor::START;
1490        let (bytes, outcome) =
1491            self.serve_chunk(paths, ctx, subscription_id, &mut cursor, scratch, buf)?;
1492        if outcome.truncated {
1493            bail!(ReportWouldChunk)
1494        }
1495        Ok((bytes, outcome))
1496    }
1497
1498    /// Serves one message of a `ReadRequest`, resuming at `cursor` (§10.2.3).
1499    ///
1500    /// Packs as many information blocks into `buf` as fit, then stops on a block boundary
1501    /// and records where in `cursor`. When more remains the message carries
1502    /// `MoreChunkedMessages` and `ReadOutcome::truncated` is set; call again with the same
1503    /// `cursor` for the next message. The read is over when
1504    /// [`ReadCursor::is_done`] is true, which happens on the message that does *not* set the
1505    /// flag.
1506    ///
1507    /// §10.2.3 requires the client's `StatusResponse` between messages — "each data message
1508    /// requires a response before the next data message can be sent" — so the loop is driven
1509    /// by the exchange, not by this call.
1510    ///
1511    /// Forward progress is guaranteed: a value too large for an empty message is either split
1512    /// per §10.6.4.3.1 when it is a list, or answered `RESOURCE_EXHAUSTED` when it cannot be
1513    /// split. So the loop always terminates, whatever a cluster returns.
1514    pub fn serve_chunk<'b>(
1515        &self,
1516        paths: impl IntoIterator<Item = Result<AttributePath>>,
1517        ctx: &InteractionContext<'_>,
1518        subscription_id: Option<u32>,
1519        cursor: &mut ReadCursor,
1520        scratch: &mut [u8],
1521        buf: &'b mut [u8],
1522    ) -> Result<(&'b [u8], ReadOutcome)> {
1523        self.serve_chunk_with_events(
1524            paths,
1525            core::iter::empty::<Result<crate::im::EventPath>>(),
1526            ctx,
1527            subscription_id,
1528            cursor,
1529            scratch,
1530            buf,
1531        )
1532    }
1533
1534    /// One message of a read that asks for **both** attributes and events (§10.7.3).
1535    ///
1536    /// A `ReportData` carries two arrays, and §8.4.3 processes `AttributeRequests` and
1537    /// `EventRequests` as two halves of one action. They chunk together: attributes first,
1538    /// then events, with the cursor remembering which half a series stopped in. A node that
1539    /// served only the first half would answer every `EventRequests` as though its log were
1540    /// empty — which a client cannot tell from a node that has genuinely recorded nothing.
1541    ///
1542    /// [`Server::serve_chunk`] is this with no event paths.
1543    #[allow(clippy::too_many_arguments)]
1544    pub fn serve_chunk_with_events<'b>(
1545        &self,
1546        paths: impl IntoIterator<Item = Result<AttributePath>>,
1547        events: impl IntoIterator<Item = Result<crate::im::EventPath>>,
1548        ctx: &InteractionContext<'_>,
1549        subscription_id: Option<u32>,
1550        cursor: &mut ReadCursor,
1551        scratch: &mut [u8],
1552        buf: &'b mut [u8],
1553    ) -> Result<(&'b [u8], ReadOutcome)> {
1554        let mut w = TlvWriter::new(buf);
1555        w.start_structure(Tag::Anonymous)?;
1556        if let Some(id) = subscription_id {
1557            w.unsigned(Tag::Context(0), u64::from(id))?;
1558        }
1559        w.start_array(Tag::Context(1))?;
1560
1561        let start = cursor.path;
1562        let mut truncated = false;
1563        let mut events_closed = false;
1564        let mut events_through = 0u64;
1565        // Scoped so the writer is free again for the `EventReports` array below: a `Chunk`
1566        // borrows it for as long as it lives.
1567        let mut reports;
1568        {
1569            let mut chunk = Chunk {
1570                w: &mut w,
1571                reports: 0,
1572                limit: self.limit,
1573                full: false,
1574            };
1575            for (index, path) in paths.into_iter().enumerate() {
1576                let path = path?;
1577                // Paths served by an earlier message of this same action.
1578                if index < start {
1579                    continue;
1580                }
1581                cursor.path = index;
1582                if !self.serve_path_chunked(&path, ctx, &mut chunk, cursor, scratch)? {
1583                    truncated = true;
1584                    break;
1585                }
1586                // Finished: the next message starts at the next path, not inside this one.
1587                cursor.path = index.saturating_add(1);
1588                cursor.expansion = crate::dm::ExpandCursor::START;
1589                cursor.list = None;
1590            }
1591            reports = chunk.reports;
1592        }
1593        // §10.7.3: `AttributeReports` closes before `EventReports` opens — two arrays, in tag
1594        // order. Events are served only once the attribute half has finished, because a series
1595        // that stopped mid-attribute must resume there, and a `ReportData` whose second array
1596        // ran ahead of its first would deliver events for a state the client has not been sent.
1597        if !truncated {
1598            w.end_container()?;
1599            let mut opened = false;
1600            let mut event_chunk = Chunk {
1601                w: &mut w,
1602                reports,
1603                limit: self.limit,
1604                full: false,
1605            };
1606            for (index, path) in events.into_iter().enumerate() {
1607                let path = path?;
1608                if index < cursor.event_path {
1609                    continue;
1610                }
1611                if !opened {
1612                    event_chunk.w.start_array(Tag::Context(2))?;
1613                    opened = true;
1614                }
1615                cursor.event_path = index;
1616                let mut from = cursor.event_from;
1617                let fitted = self.serve_event_path(&path, ctx, &mut event_chunk, &mut from)?;
1618                cursor.event_from = from;
1619                // The bookmark is the highest position reached across every path in the
1620                // message, not the last path's: `cursor.event_from` is reset per path below,
1621                // so reading it at the end would give whatever the final path happened to
1622                // leave — usually zero.
1623                events_through = events_through.max(from);
1624                if !fitted {
1625                    truncated = true;
1626                    break;
1627                }
1628                cursor.event_path = index.saturating_add(1);
1629                cursor.event_from = 0;
1630            }
1631            reports = event_chunk.reports;
1632            if opened {
1633                w.end_container()?;
1634            }
1635            events_closed = true;
1636        }
1637
1638        if truncated && reports == 0 {
1639            // Chunking makes progress by putting at least one block in every message. A
1640            // message that ends empty and still has more to say has made none, so the cursor
1641            // has not moved and a caller looping until `is_done` would loop forever. The
1642            // buffer is simply too small to hold any block this read produces, and no series
1643            // of messages fixes that — every other reason a block does not fit is handled
1644            // before here, by splitting the value or refusing its path.
1645            bail!(BufferTooSmall)
1646        }
1647
1648        if !events_closed {
1649            w.end_container()?;
1650        }
1651        if truncated {
1652            // §10.2.3: "A MoreChunkedMessages flag SHALL be set on every data message except
1653            // the last." §10.7.3.2 adds that SuppressResponse must then be false, which it is
1654            // — it is not written at all, and its default is false.
1655            w.bool(Tag::Context(3), true)?;
1656        } else {
1657            cursor.done = true;
1658        }
1659        w.unsigned(
1660            Tag::Context(crate::im::REVISION_TAG),
1661            u64::from(crate::im::INTERACTION_MODEL_REVISION),
1662        )?;
1663        w.end_container()?;
1664        let bytes = w.finish()?;
1665        Ok((
1666            bytes,
1667            ReadOutcome {
1668                reports,
1669                truncated,
1670                events_through,
1671            },
1672        ))
1673    }
1674}
1675
1676/// The access decision a Write Request action has already taken, and for which path.
1677///
1678/// §10.6.4.3.1's way of writing a whole list is "a series of AttributeDataIBs, with the first
1679/// containing a path to the list itself and Data that is empty array, which signals clearing
1680/// the list, and subsequent AttributeDataIBs containing updates" — every one of them naming the
1681/// same attribute. On one attribute that idiom revokes the writer's own access half-way through:
1682/// clearing the `ACL` list removes the administrator entry the writer is administering *with*,
1683/// so §8.7.3.2 step b.iii fails on the second AttributeDataIB and the node is left with an
1684/// empty list and no administrator at all.
1685///
1686/// So the decision is taken once per concrete path per action, on the first AttributeDataIB that
1687/// names it, and reused by the rest. This cannot widen anybody's access: the grant it reuses was
1688/// checked against the ACL as it stood when the action began, which is the state the client's
1689/// request was composed against.
1690#[derive(Debug, Clone, Copy, Default)]
1691pub struct WriteAction {
1692    granted: Option<(
1693        crate::im::EndpointId,
1694        crate::im::ClusterId,
1695        crate::im::AttributeId,
1696    )>,
1697}
1698
1699impl WriteAction {
1700    /// Nothing written yet.
1701    #[must_use]
1702    pub const fn new() -> Self {
1703        Self { granted: None }
1704    }
1705
1706    const fn already_granted(
1707        &self,
1708        endpoint: crate::im::EndpointId,
1709        cluster: crate::im::ClusterId,
1710        attribute: crate::im::AttributeId,
1711    ) -> bool {
1712        match self.granted {
1713            Some((e, c, a)) => e == endpoint && c == cluster && a == attribute,
1714            None => false,
1715        }
1716    }
1717
1718    const fn grant(
1719        &mut self,
1720        endpoint: crate::im::EndpointId,
1721        cluster: crate::im::ClusterId,
1722        attribute: crate::im::AttributeId,
1723    ) {
1724        self.granted = Some((endpoint, cluster, attribute));
1725    }
1726}
1727
1728// --- Write (§8.7.3.2) ---------------------------------------------------------------------------
1729
1730impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
1731    /// Serves one write path into an already-open `WriteResponses` array.
1732    ///
1733    /// §8.7.3.2 mirrors §8.4.3.2 step for step — the same concrete/expanded asymmetry, the
1734    /// same two-stage access check — with three checks a read does not have:
1735    ///
1736    /// * step b.iv: an attribute with the `T` quality needs a Timed transaction
1737    ///   (`NEEDS_TIMED_INTERACTION`);
1738    /// * step b.v: a fabric-scoped attribute needs an accessing fabric
1739    ///   (`UNSUPPORTED_ACCESS`);
1740    /// * step b.vi: a `DataVersion` that disagrees with the cluster's
1741    ///   (`DATA_VERSION_MISMATCH`).
1742    ///
1743    /// And one difference in what is reported: §8.7.3.3 step 2.b.ii generates a
1744    /// `SUCCESS` status for every path that was written, where a read reports success by
1745    /// returning data. So a write response is never empty unless everything was discarded.
1746    pub fn serve_write_path(
1747        &self,
1748        data: &AttributeData<'_>,
1749        ctx: &InteractionContext<'_>,
1750        action: &mut WriteAction,
1751        w: &mut TlvWriter<'_>,
1752        responses: &mut usize,
1753    ) -> Result<bool> {
1754        let path = data.path;
1755        // The same rule as a read's, and for the same reason: §8.7.3.3's responses name
1756        // concrete paths, so a tag-compressed path is refused by name only when it already
1757        // is one, and otherwise discarded rather than echoed with its wildcards.
1758        if path.enable_tag_compression {
1759            return if path.concrete().is_some() {
1760                self.write_response_status(w, &path, Status::InvalidAction, responses)
1761            } else {
1762                Ok(true)
1763            };
1764        }
1765
1766        // §10.6.4.3.1: "ListIndex is currently only allowed to be omitted or null. Any other
1767        // value SHALL be interpreted as an error." Checked once, here, so neither branch
1768        // below can act on a path whose meaning the specification does not define.
1769        let Some(op) = WriteOp::of(&path) else {
1770            return if path.concrete().is_some() {
1771                self.write_response_status(w, &path, Status::InvalidAction, responses)
1772            } else {
1773                // The same concrete-path rule as above: a status may only name a path that
1774                // is concrete, so a wildcard carrying a bad ListIndex is discarded.
1775                Ok(true)
1776            };
1777        };
1778
1779        match path.concrete() {
1780            Some((endpoint, cluster, attribute)) => self.write_concrete(
1781                data, endpoint, cluster, attribute, op, ctx, action, w, responses,
1782            ),
1783            None => {
1784                for resolved in self.node.expand(&path) {
1785                    let concrete = resolved.path();
1786                    let Some(descriptor) = resolved.cluster.attribute(resolved.attribute) else {
1787                        continue;
1788                    };
1789                    // step c.i: "If the path indicates attribute data that is not writable,
1790                    // then the path SHALL be discarded."
1791                    let Some(required) = descriptor.access.write else {
1792                        continue;
1793                    };
1794                    // step c.ii: denied or restricted — discarded, with no status.
1795                    if self.access.allows(&concrete, required) != Outcome::Granted {
1796                        continue;
1797                    }
1798                    // step c.iii: a Timed-only attribute outside a Timed transaction.
1799                    if descriptor.access.needs_timed() && !ctx.timed {
1800                        continue;
1801                    }
1802                    // §7.15.3: an atomic attribute is writable only inside a claim. An
1803                    // expanded path is discarded rather than answered, per step 1c.
1804                    if descriptor.qualities.contains(AttributeQualities::ATOMIC)
1805                        && !ctx.atomic.is_some_and(|claim| {
1806                            claim.covers(resolved.endpoint, resolved.cluster.id, resolved.attribute)
1807                        })
1808                    {
1809                        continue;
1810                    }
1811                    let status = match self.handler.write(&resolved, data.data, op, ctx) {
1812                        Ok(()) => Status::Success,
1813                        Err(status) => status,
1814                    };
1815                    if !self.write_response_status(w, &concrete, status, responses)? {
1816                        return Ok(false);
1817                    }
1818                }
1819                Ok(true)
1820            }
1821        }
1822    }
1823
1824    #[expect(
1825        clippy::too_many_arguments,
1826        reason = "the endpoint, cluster and attribute are the path's own parts, already \
1827                  destructured by the caller"
1828    )]
1829    fn write_concrete(
1830        &self,
1831        data: &AttributeData<'_>,
1832        endpoint: crate::im::EndpointId,
1833        cluster: crate::im::ClusterId,
1834        attribute: crate::im::AttributeId,
1835        op: WriteOp,
1836        ctx: &InteractionContext<'_>,
1837        action: &mut WriteAction,
1838        w: &mut TlvWriter<'_>,
1839        responses: &mut usize,
1840    ) -> Result<bool> {
1841        let path = data.path;
1842        // A later AttributeDataIB of a list write this action has already been granted. See
1843        // [`WriteAction`]: the `ACL` attribute is the one where re-checking is wrong, because
1844        // clearing the list is what removes the writer's own grant.
1845        let carried = action.already_granted(endpoint, cluster, attribute);
1846        // step b.i — the View check, before existence.
1847        if !carried && let Some(status) = self.access.allows(&path, Privilege::View).status() {
1848            return self.write_response_status(w, &path, status, responses);
1849        }
1850
1851        // step b.ii — existence, level by level.
1852        let resolved = match self.node.resolve(endpoint, cluster, attribute) {
1853            Ok(resolved) => resolved,
1854            Err(missing) => {
1855                return self.write_response_status(w, &path, missing.status(), responses);
1856            }
1857        };
1858        let Some(descriptor) = resolved.cluster.attribute(attribute) else {
1859            return self.write_response_status(w, &path, Status::UnsupportedAttribute, responses);
1860        };
1861        // step b.ii.E — "an attribute that is not writable" is UNSUPPORTED_WRITE. The
1862        // globals of §7.13 land here: Table 95 gives all five `RV`, so a client writing one
1863        // is told it is read-only rather than that it does not exist.
1864        let Some(required) = descriptor.access.write else {
1865            return self.write_response_status(w, &path, Status::UnsupportedWrite, responses);
1866        };
1867
1868        // step b.iii — the second check, at the attribute's actual write privilege.
1869        if !carried {
1870            if let Some(status) = self.access.allows(&path, required).status() {
1871                return self.write_response_status(w, &path, status, responses);
1872            }
1873            action.grant(endpoint, cluster, attribute);
1874        }
1875
1876        // §7.15.3: "If a server receives a Write Request for an attribute that is not
1877        // associated with an Atomic Write State that is also associated with the client making
1878        // the request, the server SHALL return the error code INVALID_IN_STATE." Before the
1879        // Timed check, because an atomic attribute written outside a claim is wrong whatever
1880        // else is true of the request.
1881        if descriptor.qualities.contains(AttributeQualities::ATOMIC)
1882            && !ctx
1883                .atomic
1884                .is_some_and(|claim| claim.covers(endpoint, cluster, attribute))
1885        {
1886            return self.write_response_status(w, &path, Status::InvalidInState, responses);
1887        }
1888
1889        // step b.iv — a Timed-only attribute outside a Timed transaction.
1890        if descriptor.access.needs_timed() && !ctx.timed {
1891            return self.write_response_status(w, &path, Status::NeedsTimedInteraction, responses);
1892        }
1893
1894        // step b.v — "Else if the attribute in the path indicates a fabric-scoped list and
1895        // there is no accessing fabric". A PASE session during commissioning has none.
1896        if descriptor.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
1897            return self.write_response_status(w, &path, Status::UnsupportedAccess, responses);
1898        }
1899
1900        // step b.vi — the client's cached version is stale, so its write was computed
1901        // against data that has since changed.
1902        if let (Some(expected), Some(actual)) =
1903            (data.data_version, self.handler.data_version(&resolved))
1904            && expected != actual
1905        {
1906            return self.write_response_status(w, &path, Status::DataVersionMismatch, responses);
1907        }
1908
1909        // §8.7.3.3 — the write itself, and a SUCCESS status for it. `op` carries whether the
1910        // client meant to replace the attribute or to append one item to a list; §10.6.4.3.1
1911        // encodes that in the path, not in the data, so only this layer can tell the cluster.
1912        let status = match self.handler.write(&resolved, data.data, op, ctx) {
1913            Ok(()) => {
1914                // "A cluster data version SHALL be incremented if any attribute data changes."
1915                // This is the half the server can see; a cluster that changes on its own calls
1916                // `DataVersionSource::touch` itself.
1917                if let Some(versions) = self.versions {
1918                    versions.touch(resolved.endpoint, resolved.cluster.id);
1919                }
1920                Status::Success
1921            }
1922            Err(status) => status,
1923        };
1924        self.write_response_status(w, &path, status, responses)
1925    }
1926
1927    /// Serves a whole `WriteRequest` into a `WriteResponse` message.
1928    pub fn serve_write<'b>(
1929        &self,
1930        writes: impl IntoIterator<Item = Result<AttributeData<'b>>>,
1931        ctx: &InteractionContext<'_>,
1932        more_chunked: bool,
1933        buf: &'b mut [u8],
1934    ) -> Result<(&'b [u8], ReadOutcome)> {
1935        // §10.7.6.2: "A Write Request action that is part of a Timed Write Interaction SHALL
1936        // NOT be chunked." The two mechanisms contradict each other — §8.7.4's window is
1937        // consumed by the first request on it, so every later chunk of the same action would
1938        // arrive to find no window and be refused as a client bug. Refusing the action up
1939        // front says what is actually wrong.
1940        if more_chunked && ctx.timed {
1941            bail!(InvalidAction)
1942        }
1943        let mut w = TlvWriter::new(buf);
1944        w.start_structure(Tag::Anonymous)?;
1945        w.start_array(Tag::Context(0))?;
1946
1947        let mut responses = 0usize;
1948        let mut truncated = false;
1949        let mut action = WriteAction::new();
1950        for data in writes {
1951            let data = data?;
1952            if !self.serve_write_path(&data, ctx, &mut action, &mut w, &mut responses)? {
1953                truncated = true;
1954                break;
1955            }
1956        }
1957
1958        w.end_container()?;
1959        w.unsigned(
1960            Tag::Context(crate::im::REVISION_TAG),
1961            u64::from(crate::im::INTERACTION_MODEL_REVISION),
1962        )?;
1963        w.end_container()?;
1964        let bytes = w.finish()?;
1965        Ok((
1966            bytes,
1967            ReadOutcome {
1968                reports: responses,
1969                truncated,
1970                events_through: 0,
1971            },
1972        ))
1973    }
1974}
1975
1976// --- Invoke (§8.8.2.3) -------------------------------------------------------------------------
1977
1978impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
1979    /// Serves one command into an already-open `InvokeResponses` array.
1980    ///
1981    /// §8.8.2.3 again mirrors the read, with one difference that matters: the *first* access
1982    /// check is at **Operate**, not View. §8.8.2.3 step b.i: "assuming the required_privilege
1983    /// for the element is Operate". That is because there is no such thing as a read-only
1984    /// command — View is enough to look at a node, and never enough to make it do something.
1985    pub fn serve_invoke_command(
1986        &self,
1987        command: &CommandData<'_>,
1988        ctx: &InteractionContext<'_>,
1989        w: &mut TlvWriter<'_>,
1990        responses: &mut usize,
1991        scratch: &mut [u8],
1992    ) -> Result<bool> {
1993        let path = command.path;
1994        match path.concrete() {
1995            Some((endpoint, cluster, id)) => {
1996                self.invoke_concrete(command, endpoint, cluster, id, ctx, w, responses, scratch)
1997            }
1998            None => {
1999                for resolved in self.node.expand_commands(&path) {
2000                    let concrete = resolved.path();
2001                    let Some(required) = resolved.command.access.invoke else {
2002                        continue;
2003                    };
2004                    let attribute_path = command_as_attribute_path(&concrete);
2005                    // step c.i: denied or restricted — discarded, with no status.
2006                    if self.access.allows(&attribute_path, required) != Outcome::Granted {
2007                        continue;
2008                    }
2009                    // step c.ii: a Large Message command on a transport that cannot carry
2010                    // one (§7.7.5).
2011                    if resolved.command.access.needs_large_messages() && !ctx.large_messages {
2012                        continue;
2013                    }
2014                    // step c.iii: fabric-scoped with no accessing fabric.
2015                    if resolved.command.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
2016                        continue;
2017                    }
2018                    // step c.iv: Timed-only outside a Timed transaction.
2019                    if resolved.command.access.needs_timed() && !ctx.timed {
2020                        continue;
2021                    }
2022                    if !self.run_command(&resolved, command, ctx, w, responses, scratch)? {
2023                        return Ok(false);
2024                    }
2025                }
2026                Ok(true)
2027            }
2028        }
2029    }
2030
2031    #[expect(
2032        clippy::too_many_arguments,
2033        reason = "the endpoint, cluster and command are the path's own parts, already \
2034                  destructured by the caller"
2035    )]
2036    fn invoke_concrete(
2037        &self,
2038        command: &CommandData<'_>,
2039        endpoint: crate::im::EndpointId,
2040        cluster: crate::im::ClusterId,
2041        id: crate::im::CommandId,
2042        ctx: &InteractionContext<'_>,
2043        w: &mut TlvWriter<'_>,
2044        responses: &mut usize,
2045        scratch: &mut [u8],
2046    ) -> Result<bool> {
2047        let path = command.path;
2048        let attribute_path = command_as_attribute_path(&path);
2049
2050        // step b.i — "assuming the required_privilege for the element is Operate". Not View:
2051        // looking at a node and making it do something are different things.
2052        if let Some(status) = self
2053            .access
2054            .allows(&attribute_path, Privilege::Operate)
2055            .status()
2056        {
2057            return self.command_status(w, &path, status, command.command_ref, responses);
2058        }
2059
2060        // step b.ii — existence, level by level.
2061        let resolved = match self.node.resolve_command(endpoint, cluster, id) {
2062            Ok(resolved) => resolved,
2063            Err(missing) => {
2064                return self.command_status(
2065                    w,
2066                    &path,
2067                    missing.status(),
2068                    command.command_ref,
2069                    responses,
2070                );
2071            }
2072        };
2073        let Some(required) = resolved.command.access.invoke else {
2074            return self.command_status(
2075                w,
2076                &path,
2077                Status::UnsupportedCommand,
2078                command.command_ref,
2079                responses,
2080            );
2081        };
2082
2083        // step b.iii — the second check, at the command's actual privilege.
2084        if let Some(status) = self.access.allows(&attribute_path, required).status() {
2085            return self.command_status(w, &path, status, command.command_ref, responses);
2086        }
2087
2088        // step b.iv — "If the command in the path has the Large Message Quality and was
2089        // received on a transport that is not capable of transporting Large Messages". A
2090        // privilege cannot substitute for a transport, so this is checked after the access
2091        // checks and independently of them.
2092        if resolved.command.access.needs_large_messages() && !ctx.large_messages {
2093            return self.command_status(
2094                w,
2095                &path,
2096                Status::InvalidTransportType,
2097                command.command_ref,
2098                responses,
2099            );
2100        }
2101
2102        // step b.v — fabric-scoped with no accessing fabric.
2103        if resolved.command.access.is_fabric_scoped() && ctx.fabric_index.is_none() {
2104            return self.command_status(
2105                w,
2106                &path,
2107                Status::UnsupportedAccess,
2108                command.command_ref,
2109                responses,
2110            );
2111        }
2112
2113        // step b.vi — a command that requires a Timed Invoke and did not get one.
2114        if resolved.command.access.needs_timed() && !ctx.timed {
2115            return self.command_status(
2116                w,
2117                &path,
2118                Status::NeedsTimedInteraction,
2119                command.command_ref,
2120                responses,
2121            );
2122        }
2123
2124        self.run_command(&resolved, command, ctx, w, responses, scratch)
2125    }
2126
2127    /// Runs one command and writes whatever §8.8.2.3's "Invoke Execution" says it produced.
2128    fn run_command(
2129        &self,
2130        resolved: &crate::dm::ResolvedCommand<'_>,
2131        command: &CommandData<'_>,
2132        ctx: &InteractionContext<'_>,
2133        w: &mut TlvWriter<'_>,
2134        responses: &mut usize,
2135        scratch: &mut [u8],
2136    ) -> Result<bool> {
2137        if *responses >= self.limit {
2138            return Ok(false);
2139        }
2140        let path = resolved.path();
2141
2142        // The response fields are built beside the message so that a command which refuses,
2143        // or runs out of room, leaves nothing half-written in the response. Note this runs
2144        // the command *before* knowing whether its response fits: §8.8.2.3 has no way to
2145        // undo an invocation, so a response that will not fit is reported as a status rather
2146        // than retried on the next message.
2147        let mut fields = TlvWriter::new_in(scratch, ContainerKind::Structure);
2148        let outcome =
2149            self.handler
2150                .invoke(resolved, command.fields, ctx, &mut fields, Tag::Context(1));
2151
2152        // §7.10.3: "A cluster data version SHALL be incremented if any attribute data changes"
2153        // — *any*, and a command is one of the ways they change. `ArmFailSafe` sets
2154        // `Breadcrumb`, `AddNOC` fills the fabric table, `MoveToLevel` moves `CurrentLevel`.
2155        // The write path has always done this; the invoke path did not, so an attribute changed
2156        // by a command left its version where it was and every client caching by
2157        // `DataVersionFilters` was told its copy was current when it was not — and never found
2158        // out otherwise.
2159        //
2160        // The server cannot see *which* attribute moved, so it bumps the cluster whenever a
2161        // command succeeds. Deliberately conservative: §7.10.3 sets a floor, and a version that
2162        // moves when nothing changed costs a client one re-read, while a version that fails to
2163        // move when something did is a wrong answer the client cannot detect. The alternative —
2164        // each cluster announcing its own changes — is the one every cluster forgets. A cluster
2165        // that changes an attribute with no command behind it, a sensor reading or a switch
2166        // somebody pressed, still calls [`DataVersionSource::touch`] itself; there is nothing
2167        // here for the server to hook.
2168        if outcome.is_ok()
2169            && let Some(versions) = self.versions
2170        {
2171            versions.touch(resolved.endpoint, resolved.cluster.id);
2172        }
2173
2174        match outcome {
2175            // "If the cluster specification defines a following command in response to the
2176            // command, a CommandDataIB SHALL be generated for the following command."
2177            Ok(Some(response_id)) => {
2178                let Ok(encoded) = fields.finish() else {
2179                    return self.command_status(
2180                        w,
2181                        &path,
2182                        Status::Failure,
2183                        command.command_ref,
2184                        responses,
2185                    );
2186                };
2187                let response = CommandData {
2188                    // "ClusterPath field … that is a duplicate of the command path processed,
2189                    // up to the cluster ID; Command field … that is the command ID of the
2190                    // following command."
2191                    path: crate::im::CommandPath::command(
2192                        resolved.endpoint,
2193                        resolved.cluster.id,
2194                        response_id,
2195                    ),
2196                    fields: Some(encoded),
2197                    command_ref: command.command_ref,
2198                };
2199                if put_block(w, responses, self.limit, |w| {
2200                    InvokeResponse::Command(response).encode(w)
2201                })? {
2202                    return Ok(true);
2203                }
2204                // The command has already run and cannot be run again, so its response
2205                // cannot simply wait for the next message. Saying the response would not fit
2206                // is the only honest answer left: the client learns the command executed and
2207                // that its result is unavailable, rather than never hearing about it.
2208                self.command_status(
2209                    w,
2210                    &path,
2211                    Status::ResourceExhausted,
2212                    command.command_ref,
2213                    responses,
2214                )
2215            }
2216            // "Else if the cluster specification defines a success or error status as a
2217            // response … a CommandStatusIB SHALL be generated."
2218            Ok(None) => {
2219                self.command_status(w, &path, Status::Success, command.command_ref, responses)
2220            }
2221            Err(status) => self.command_status(w, &path, status, command.command_ref, responses),
2222        }
2223    }
2224
2225    /// Writes a bare `AttributeStatusIB` — what a `WriteResponse`'s array holds.
2226    ///
2227    /// Not the same as [`Server::write_status`], which emits an `AttributeReportIB`
2228    /// *wrapping* one: §10.7.3's `AttributeReports` is an array of `AttributeReportIB`, and
2229    /// §10.7.7's `WriteResponses` is an array of `AttributeStatusIB` directly. Reusing the
2230    /// read's helper here produces a response a client cannot decode.
2231    fn write_response_status(
2232        &self,
2233        w: &mut TlvWriter<'_>,
2234        path: &AttributePath,
2235        status: Status,
2236        responses: &mut usize,
2237    ) -> Result<bool> {
2238        put_block(w, responses, self.limit, |w| {
2239            AttributeStatus {
2240                path: *path,
2241                status: StatusIb::new(status),
2242            }
2243            .encode(w, Tag::Anonymous)
2244        })
2245    }
2246
2247    fn command_status(
2248        &self,
2249        w: &mut TlvWriter<'_>,
2250        path: &crate::im::CommandPath,
2251        status: impl Into<StatusIb>,
2252        command_ref: Option<u16>,
2253        responses: &mut usize,
2254    ) -> Result<bool> {
2255        let status = status.into();
2256        put_block(w, responses, self.limit, |w| {
2257            InvokeResponse::Status(CommandStatus {
2258                // §8.8.2.3 step b: "its CommandPath field SHALL be a duplicate of the concrete
2259                // path processed, including the command ID of the original concrete path."
2260                path: *path,
2261                status,
2262                command_ref,
2263            })
2264            .encode(w)
2265        })
2266    }
2267
2268    /// Serves a whole `InvokeRequest` into an `InvokeResponse` message.
2269    ///
2270    /// `commands` is the request's `InvokeRequests` array. §8.8.2.2 step 5 forbids a wildcard
2271    /// once there is more than one command, and the caller is expected to have refused such a
2272    /// request with `INVALID_ACTION` before reaching here — this serves what it is given.
2273    pub fn serve_invoke<'b>(
2274        &self,
2275        commands: impl IntoIterator<Item = Result<CommandData<'b>>>,
2276        ctx: &InteractionContext<'_>,
2277        suppress_response: bool,
2278        scratch: &mut [u8],
2279        buf: &'b mut [u8],
2280    ) -> Result<(&'b [u8], ReadOutcome)> {
2281        let mut w = TlvWriter::new(buf);
2282        w.start_structure(Tag::Anonymous)?;
2283        // §8.8.3.1: "as Matter does not support responses to InvokeResponse actions, this
2284        // field has no effect" — but it is mandatory, so it is echoed.
2285        w.bool(Tag::Context(0), suppress_response)?;
2286        w.start_array(Tag::Context(1))?;
2287
2288        let mut responses = 0usize;
2289        let mut truncated = false;
2290        for command in commands {
2291            let command = command?;
2292            if !self.serve_invoke_command(&command, ctx, &mut w, &mut responses, scratch)? {
2293                truncated = true;
2294                break;
2295            }
2296        }
2297
2298        w.end_container()?;
2299        if truncated {
2300            w.bool(Tag::Context(2), true)?;
2301        }
2302        w.unsigned(
2303            Tag::Context(crate::im::REVISION_TAG),
2304            u64::from(crate::im::INTERACTION_MODEL_REVISION),
2305        )?;
2306        w.end_container()?;
2307        let bytes = w.finish()?;
2308        Ok((
2309            bytes,
2310            ReadOutcome {
2311                reports: responses,
2312                truncated,
2313                events_through: 0,
2314            },
2315        ))
2316    }
2317}
2318
2319/// Borrows a command path as an attribute path, for the access check.
2320///
2321/// [`AccessControl`] is expressed over attribute paths because §6.6's access-control entries
2322/// are: a `TargetStruct` names an endpoint, a cluster and optionally a device type, never a
2323/// command. So a command's access is decided by its endpoint and cluster, and this makes that
2324/// explicit rather than leaving two near-identical traits.
2325fn command_as_attribute_path(path: &crate::im::CommandPath) -> AttributePath {
2326    AttributePath {
2327        endpoint: path.endpoint,
2328        cluster: path.cluster,
2329        ..AttributePath::wildcard()
2330    }
2331}
2332
2333// --- Subscribe (§8.5) -----------------------------------------------------------------------
2334
2335impl<A: AccessControl, H: ClusterHandler> Server<'_, A, H> {
2336    /// Serves the priming report of a subscription — §8.5.1's second action.
2337    ///
2338    /// A Subscribe transaction is four actions: the request, a `ReportData` that primes the
2339    /// subscriber, a `StatusResponse` acknowledging it, and only then the `SubscribeResponse`
2340    /// that activates the subscription. This is the second, and it is an ordinary read — the
2341    /// specification routes both through the same processing, "as defined in Incoming Read
2342    /// Request and Subscribe Request Action Processing".
2343    ///
2344    /// The difference is the `SubscriptionId`, which §8.5.3.2 requires to be "the same as the
2345    /// one used in Report Data generated to prime this subscription". So the id is allocated
2346    /// *before* the priming report and confirmed afterwards, not the other way round.
2347    pub fn prime<'b>(
2348        &self,
2349        subscription_id: u32,
2350        paths: impl IntoIterator<Item = Result<AttributePath>>,
2351        ctx: &InteractionContext<'_>,
2352        scratch: &mut [u8],
2353        buf: &'b mut [u8],
2354    ) -> Result<(&'b [u8], ReadOutcome)> {
2355        self.serve(paths, ctx, Some(subscription_id), scratch, buf)
2356    }
2357
2358    /// Serves a subscription's periodic report (§8.6).
2359    ///
2360    /// `reason` decides the shape. A [`ReportReason::Data`](crate::im::subscription::ReportReason::Data) report carries what changed and
2361    /// asks for a `StatusResponse`; a [`ReportReason::KeepAlive`](crate::im::subscription::ReportReason::KeepAlive) one is §8.6.2's "Report
2362    /// Transaction Empty" — "report with no data or events with SuppressResponse set to TRUE",
2363    /// because its only job is to prove the publisher is still there and there is nothing for
2364    /// a subscriber to acknowledge.
2365    ///
2366    /// A subscription whose dirty set overflowed reports everything it covers: §8.5's own
2367    /// recovery, "Including all subscription data to re-prime the subscription".
2368    ///
2369    /// One message only, and [`ErrorCode::ReportWouldChunk`] when that is not enough — the
2370    /// re-primed case above makes that likely, so a publisher serving wildcard subscriptions
2371    /// wants [`Server::report_chunk`].
2372    pub fn report<'b, const P: usize>(
2373        &self,
2374        subscription: &mut crate::im::subscription::Subscription<P>,
2375        reason: crate::im::subscription::ReportReason,
2376        ctx: &InteractionContext<'_>,
2377        scratch: &mut [u8],
2378        buf: &'b mut [u8],
2379    ) -> Result<(&'b [u8], ReadOutcome)> {
2380        let (bytes, outcome) = self.report_chunk(subscription, reason, ctx, scratch, buf)?;
2381        if outcome.truncated {
2382            // Same rule as [`Server::serve`]: one message cannot honour the flag it would
2383            // have to set, so this refuses rather than promising a continuation. The series
2384            // it started is abandoned with it, or the next call here would resume a report
2385            // this one told the caller it never sent.
2386            subscription.cursor = ReadCursor::START;
2387            bail!(ReportWouldChunk)
2388        }
2389        Ok((bytes, outcome))
2390    }
2391
2392    /// One message of a subscription's report, resuming at `cursor` (§10.2.3).
2393    ///
2394    /// A report over a wildcard subscription, and any re-primed one, is as large as the read
2395    /// that primed it, so it chunks the same way. [`Server::report`] is this for reports
2396    /// expected to fit.
2397    ///
2398    /// The subscription carries its own cursor, so a series resumes and a finished one starts
2399    /// over without the caller tracking either: call this until
2400    /// [`ReadOutcome::truncated`] is false, answering each `StatusResponse` with the next
2401    /// chunk (§10.2.3). Two subscriptions reporting at once therefore cannot resume into each
2402    /// other's report, which is the failure a single shared cursor produces and nothing on the
2403    /// wire reveals.
2404    pub fn report_chunk<'b, const P: usize>(
2405        &self,
2406        subscription: &mut crate::im::subscription::Subscription<P>,
2407        reason: crate::im::subscription::ReportReason,
2408        ctx: &InteractionContext<'_>,
2409        scratch: &mut [u8],
2410        buf: &'b mut [u8],
2411    ) -> Result<(&'b [u8], ReadOutcome)> {
2412        use crate::im::subscription::ReportReason;
2413
2414        let id = subscription.id;
2415        match reason {
2416            ReportReason::KeepAlive => {
2417                subscription.cursor.done = true;
2418                self.empty_report(id, buf)
2419            }
2420            ReportReason::Data => {
2421                let (paths, events, from, cursor) = subscription.report_source();
2422                // A cursor that finished its last series starts the next one, which is why no
2423                // caller resets it: the two states a caller could confuse — "resume" and
2424                // "begin" — are the same call.
2425                if cursor.is_done() {
2426                    *cursor = ReadCursor::START;
2427                }
2428                // §8.5.3.4's bookmark: a *new* series starts at the first event the subscriber
2429                // has not been sent; a resumed one keeps the position it stopped at. "New" is a
2430                // cursor still at the start — which covers both a series that finished above
2431                // and one that `Subscription::reported` reset after the last report went out.
2432                // `is_done()` alone covers only the first, and the second is the common case.
2433                if *cursor == ReadCursor::START {
2434                    cursor.set_event_from(from);
2435                }
2436                let served = self.serve_chunk_with_events(
2437                    paths.iter().copied().map(Ok),
2438                    events.iter().copied().map(Ok),
2439                    ctx,
2440                    Some(id),
2441                    cursor,
2442                    scratch,
2443                    buf,
2444                );
2445                // Where this message left the bookmark, recorded on the subscription rather
2446                // than returned to the device: §8.5.3.4 resumes the next report after the last
2447                // event delivered, and that is a fact the server has and the device would have
2448                // to reconstruct. Both devices in this repository reconstructed it as `0`.
2449                //
2450                // Accumulated across the chunks of one series — `note_reported_through` keeps
2451                // the maximum — because each chunk carries part of it.
2452                if let Ok((_, outcome)) = &served {
2453                    subscription.note_reported_through(outcome.events_through);
2454                }
2455                served
2456            }
2457        }
2458    }
2459
2460    /// §8.6.2's Report Transaction Empty: a `ReportData` with no reports and
2461    /// `SuppressResponse` set.
2462    fn empty_report<'b>(
2463        &self,
2464        subscription_id: u32,
2465        buf: &'b mut [u8],
2466    ) -> Result<(&'b [u8], ReadOutcome)> {
2467        let mut w = TlvWriter::new(buf);
2468        w.start_structure(Tag::Anonymous)?;
2469        w.unsigned(Tag::Context(0), u64::from(subscription_id))?;
2470        // No `AttributeReports`, no `EventReports`: an empty report is empty.
2471        // §8.6.2: "SuppressResponse set to TRUE" — there is nothing to acknowledge, and asking
2472        // would double the traffic a keep-alive exists to minimise.
2473        w.bool(Tag::Context(4), true)?;
2474        w.unsigned(
2475            Tag::Context(crate::im::REVISION_TAG),
2476            u64::from(crate::im::INTERACTION_MODEL_REVISION),
2477        )?;
2478        w.end_container()?;
2479        let bytes = w.finish()?;
2480        Ok((
2481            bytes,
2482            ReadOutcome {
2483                reports: 0,
2484                truncated: false,
2485                events_through: 0,
2486            },
2487        ))
2488    }
2489}