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