Skip to main content

matter_kit/im/
dispatch.rs

1//! One entry point for an arriving interaction-model message (Core §8.7, §8.8).
2//!
3//! [`Server`] exposes the *processing* of each action — [`Server::serve_chunk`],
4//! [`Server::serve_write`], [`Server::serve_invoke`] — and deliberately takes already-decoded
5//! paths, because that is what makes each of them testable against the specification's own
6//! path tables. What it does not do is decide *which* of them an opcode means, and that
7//! decision is not the triviality it looks like: between the opcode and the processing sit the
8//! rules of §8.7.2.3 and §8.8.2.3, which a node must apply before it does any work and which
9//! are invisible in the shape of the request.
10//!
11//! [`Dispatcher`] is that layer. It owns the one piece of state the rules need — §8.7.4's
12//! [`TimedWindows`] — and turns "a message arrived on this exchange" into "send this opcode
13//! back", or into [`Served::Subscribe`] for the one action whose state lives elsewhere.
14//!
15//! # What it refuses before the node does any work
16//!
17//! | Rule | Section | Answer |
18//! |---|---|---|
19//! | a Timed transaction whose window expired | §8.7.2.3, §8.8.2.3 rule 1 | `TIMEOUT` |
20//! | a Timed transaction whose request says `TimedRequest = false` | §8.7.2.3, §8.8.2.3 rule 2 | `TIMED_REQUEST_MISMATCH` |
21//! | `TimedRequest = true` with no window open | §8.7.2.3, §8.8.2.3 rule 3 | `TIMED_REQUEST_MISMATCH` |
22//! | more commands than `MaxPathsPerInvoke` | §8.8.2.3 rule 4 | `INVALID_ACTION` |
23//! | a `TimedRequest` with no room to record it | §8.7.3.2 | `BUSY` |
24//!
25//! The fourth is the one a hand-written dispatch reliably forgets. `MaxPathsPerInvoke` is a
26//! Basic Information attribute (§11.1.5.23) whose default is 1, so a device that does not
27//! enforce it advertises "one command per invoke" and then executes however many a client
28//! sends — which is both a specification violation and the only bound the server has on the
29//! work one message can ask of it.
30//!
31//! # Why a length rather than a slice
32//!
33//! Every other encoder here returns `&'b [u8]`. This one returns how many octets it wrote,
34//! because [`Server::serve_write`] ties the lifetime of the decoded `AttributeData` to the
35//! lifetime of the output buffer, and a dispatcher that returned a borrow of the buffer would
36//! propagate that unification into its own signature and tie the *request* to it too. The
37//! caller writes `&buf[..len]`, which is what it was going to do with the slice anyway.
38
39use super::message::{
40    InvokeRequest, ReadRequest, StatusResponse, SubscribeRequest, TimedRequest, WriteRequest,
41    opcode,
42};
43use super::server::{AccessControl, ClusterHandler, InteractionContext, ReadCursor, Server};
44use super::status::Status;
45use super::timed::TimedWindows;
46use crate::error::Result;
47use crate::msg::{ExchangeId, SessionId};
48
49/// One arriving interaction-model message, with the exchange facts §8.7.4 keys its window on.
50///
51/// Constructible as a literal: an unsecured session is `session: None`, which
52/// [`Request::new`] cannot express.
53#[derive(Debug, Clone, Copy)]
54pub struct Request<'a> {
55    /// The protocol opcode (§10.2.1).
56    pub opcode: u8,
57    /// The message body, everything after the protocol header.
58    pub payload: &'a [u8],
59    /// Which secure session it arrived on, `None` for an unsecured one.
60    ///
61    /// §8.7.4's window is keyed by session *and* exchange, so that one client's Timed Request
62    /// cannot be spent by another's Write on a coincidentally equal exchange id.
63    pub session: Option<SessionId>,
64    /// The exchange it arrived on.
65    pub exchange: ExchangeId,
66    /// Whether it arrived as a groupcast.
67    ///
68    /// §8.7.2.3: "If this action was unicast and SuppressResponse is FALSE, a Write Response
69    /// action SHALL be generated … otherwise no Write Response SHALL be sent." A groupcast
70    /// write is answered by silence whatever the flag says.
71    pub groupcast: bool,
72}
73
74impl<'a> Request<'a> {
75    /// A unicast request on a secure session.
76    #[must_use]
77    pub const fn new(
78        opcode: u8,
79        payload: &'a [u8],
80        session: SessionId,
81        exchange: ExchangeId,
82    ) -> Self {
83        Self {
84            opcode,
85            payload,
86            session: Some(session),
87            exchange,
88            groupcast: false,
89        }
90    }
91
92    /// The same request, marked as having arrived on a group session.
93    #[must_use]
94    pub const fn groupcast(mut self) -> Self {
95        self.groupcast = true;
96        self
97    }
98}
99
100/// What the caller should do with the result of a dispatch.
101///
102/// Deliberately **not** `#[non_exhaustive]`. Every variant demands a different action from the
103/// caller, so a wildcard arm is a silent bug rather than forward compatibility: a node that
104/// matched `_ => {}` would answer a new action with silence. Adding a variant here is a
105/// breaking change, and should be.
106#[derive(Debug)]
107pub enum Served<'a> {
108    /// Send `buf[..len]` back on the same exchange, with this opcode.
109    Reply {
110        /// The response opcode (§10.2.1).
111        opcode: u8,
112        /// How many octets of the output buffer the message occupies.
113        len: usize,
114        /// Whether the message set `MoreChunkedMessages` (§10.2.3).
115        ///
116        /// When set, the read is not finished: §10.2.3 requires the client's `StatusResponse`
117        /// before the next message, so the caller sends this one, waits for it, and dispatches
118        /// again with the same [`ReadCursor`].
119        more_chunks: bool,
120    },
121    /// A `SubscribeRequest`, decoded and handed on.
122    ///
123    /// Subscriptions are the one action whose state is not the dispatcher's: it lives in
124    /// [`SubscriptionTable`](super::subscription::SubscriptionTable), outlives the exchange,
125    /// and is driven by a reporting engine rather than by a reply. So this is where the
126    /// dispatcher stops.
127    Subscribe(SubscribeRequest<'a>),
128    /// Nothing to send: the action was suppressed or groupcast (§8.7.2.3).
129    Silent,
130    /// Not an action this layer serves — a response opcode, or one from a newer revision.
131    ///
132    /// The one that matters in practice is `StatusResponse`: §10.2.3 makes it the client's
133    /// acknowledgement of a chunk, so a caller holding a [`ReadCursor`] that is not
134    /// [`ReadCursor::is_done`] answers it by dispatching the *same* read again rather than by
135    /// treating it as a new action.
136    ///
137    /// §8.2.5.1 makes an unexpected action `INVALID_ACTION`, but a *response* opcode on an
138    /// exchange this node initiated is not unexpected at all, and the dispatcher cannot tell
139    /// the two apart without knowing which role it holds. So it says what it saw and lets the
140    /// caller, which does know, decide.
141    Unhandled {
142        /// The opcode that was not served.
143        opcode: u8,
144    },
145}
146
147/// The opcode-to-action layer of §8.7 and §8.8, and the state its rules need.
148///
149/// `W` is how many Timed transactions may be open at once — §8.7.4's windows, one per
150/// (session, exchange).
151#[derive(Debug)]
152pub struct Dispatcher<const W: usize> {
153    timed: TimedWindows<W>,
154    max_paths_per_invoke: u16,
155}
156
157impl<const W: usize> Dispatcher<W> {
158    /// A dispatcher that enforces `max_paths_per_invoke` on incoming invokes.
159    ///
160    /// The value must be the one the node's Basic Information cluster advertises
161    /// (§11.1.5.23), or the node promises one thing and enforces another.
162    ///
163    /// Zero is raised to one. §11.1.5.23 constrains the attribute to `min 1`, so zero is not a
164    /// value a node may advertise — but it is what an uninitialised field holds, and a
165    /// dispatcher that took it at its word would answer every invoke `INVALID_ACTION` and look
166    /// like a data-model fault rather than a typo.
167    #[must_use]
168    pub const fn new(max_paths_per_invoke: u16) -> Self {
169        Self {
170            timed: TimedWindows::new(),
171            max_paths_per_invoke: if max_paths_per_invoke == 0 {
172                1
173            } else {
174                max_paths_per_invoke
175            },
176        }
177    }
178
179    /// The Timed windows, for the reaping and session-teardown a node owes them.
180    pub const fn timed(&mut self) -> &mut TimedWindows<W> {
181        &mut self.timed
182    }
183
184    /// Serves one message, returning what to send back.
185    ///
186    /// `ctx` supplies the facts about the session that the action does not carry — the
187    /// accessing fabric, the clock, whether the transport is large-message capable. Its
188    /// [`timed`](InteractionContext::timed) field is **overwritten** from §8.7.4's window
189    /// rather than read: whether an action is part of a Timed transaction is a property of the
190    /// exchange's history, which only this layer knows, and a caller that set it by hand would
191    /// be guessing.
192    ///
193    /// `cursor` carries a chunked read between messages and is [`ReadCursor::START`] for a new
194    /// one. One cursor belongs to one exchange.
195    ///
196    /// # Errors
197    ///
198    /// A malformed message is an [`Error`](crate::Error) — the decoders' own verdict. §8.2.5.1
199    /// makes that `INVALID_ACTION` on the wire, which the caller sends; the dispatcher does not
200    /// invent a status for bytes it could not parse.
201    pub fn dispatch<'a, A: AccessControl, H: ClusterHandler>(
202        &mut self,
203        server: &Server<'_, A, H>,
204        request: Request<'a>,
205        ctx: &InteractionContext<'_>,
206        cursor: &mut ReadCursor,
207        scratch: &mut [u8],
208        buf: &mut [u8],
209    ) -> Result<Served<'a>> {
210        match request.opcode {
211            opcode::READ_REQUEST => self.read(server, request, ctx, cursor, scratch, buf),
212            opcode::WRITE_REQUEST => self.write(server, request, ctx, buf),
213            opcode::INVOKE_REQUEST => self.invoke(server, request, ctx, scratch, buf),
214            opcode::TIMED_REQUEST => self.timed_request(request, ctx, buf),
215            opcode::SUBSCRIBE_REQUEST => {
216                let subscribe = SubscribeRequest::decode(request.payload)?;
217                // §8.9.2.6's table is "valid for AttributePathIB for a Read Request action **or
218                // a Subscribe Request action**". Enforced here rather than left to the device:
219                // a subscription that accepted a path a read refuses would answer the same
220                // question by a different door, and forever rather than once.
221                if let Some(paths) = subscribe.attribute_paths()? {
222                    for path in paths {
223                        if !path?.is_valid_for_read() {
224                            return status_reply(Status::InvalidAction, buf);
225                        }
226                    }
227                }
228                // §8.4.3 step 7.b: "if either MinIntervalFloor or MaxIntervalCeiling is
229                // missing, or MinIntervalFloor is greater than MaxIntervalCeiling" the action
230                // is `INVALID_ACTION`. Clamping instead would grant an interval the subscriber
231                // never asked for and cannot detect.
232                if subscribe.min_interval_floor_s > subscribe.max_interval_ceiling_s {
233                    return status_reply(Status::InvalidAction, buf);
234                }
235                // §8.4.3 step 7.a: "If both AttributeRequests and EventRequests are empty" the
236                // action is `INVALID_ACTION` — and step 2 defines empty as "no error-free
237                // existent paths remain", so a path the subscriber may not read counts as
238                // absent, not as a subscription that reports nothing.
239                //
240                // The difference matters to the subscriber and only to the subscriber: a
241                // `SubscribeResponse` is a promise to report, and a subscription over paths it
242                // will never be allowed to see is a promise that cannot be kept and cannot be
243                // distinguished from a quiet device.
244                let has_events = subscribe
245                    .event_paths()?
246                    .is_some_and(|mut paths| paths.next().is_some());
247                let has_attributes = match subscribe.attribute_paths()? {
248                    Some(paths) => server.any_readable(paths)?,
249                    None => false,
250                };
251                if !has_attributes && !has_events {
252                    return status_reply(Status::InvalidAction, buf);
253                }
254                Ok(Served::Subscribe(subscribe))
255            }
256            other => Ok(Served::Unhandled { opcode: other }),
257        }
258    }
259
260    /// §8.4's Read, chunked per §10.2.3.
261    fn read<'a, A: AccessControl, H: ClusterHandler>(
262        &mut self,
263        server: &Server<'_, A, H>,
264        request: Request<'a>,
265        ctx: &InteractionContext<'_>,
266        cursor: &mut ReadCursor,
267        scratch: &mut [u8],
268        buf: &mut [u8],
269    ) -> Result<Served<'a>> {
270        let read = ReadRequest::decode(request.payload)?;
271        let mut ctx = *ctx;
272        ctx.timed = false;
273        ctx.fabric_filtered = read.fabric_filtered;
274        // §8.4.3.2 step 3.a. §10.7.2.4 permits ignoring them when `AttributeRequests` is empty
275        // — which is exactly when they cost nothing to carry, so they are simply passed on.
276        ctx.data_version_filters = read.data_version_filters_raw();
277        ctx.event_filters = read.event_filters_raw();
278        // §8.9.2.6's table of valid wildcard combinations. Checked before anything is served,
279        // because a path it does not admit makes the whole *action* malformed — not one path
280        // in it — so the answer is a single `INVALID_ACTION`, not a report with a status in it.
281        if let Some(paths) = read.attribute_paths()? {
282            for path in paths {
283                if !path?.is_valid_for_read() {
284                    return status_reply(Status::InvalidAction, buf);
285                }
286            }
287        }
288        let paths = read.attribute_paths()?;
289        // §8.4.3.3's other half. A read may ask for events, attributes or both, and a server
290        // that answered only the attribute half would report an empty log rather than say it
291        // is not serving one.
292        let events = read.event_paths()?;
293        let (bytes, outcome) = server.serve_chunk_with_events(
294            paths.into_iter().flatten(),
295            events.into_iter().flatten(),
296            &ctx,
297            None,
298            cursor,
299            scratch,
300            buf,
301        )?;
302        Ok(Served::Reply {
303            opcode: opcode::REPORT_DATA,
304            len: bytes.len(),
305            more_chunks: outcome.truncated,
306        })
307    }
308
309    /// §8.7.2.3's Write, with its three Timed rules and its two silences.
310    fn write<'a, A: AccessControl, H: ClusterHandler>(
311        &mut self,
312        server: &Server<'_, A, H>,
313        request: Request<'a>,
314        ctx: &InteractionContext<'_>,
315        buf: &mut [u8],
316    ) -> Result<Served<'a>> {
317        let write = WriteRequest::decode(request.payload)?;
318        let timed = match self.timed.check(
319            request.session,
320            request.exchange,
321            write.timed_request,
322            ctx.now,
323        ) {
324            Ok(timed) => timed,
325            Err(status) => return status_reply(status, buf),
326        };
327        let mut ctx = *ctx;
328        ctx.timed = timed;
329        let writes = write.writes()?;
330        let (bytes, _) = server.serve_write(writes, &ctx, write.more_chunked_messages, buf)?;
331        let len = bytes.len();
332        // "If this action was unicast and SuppressResponse is FALSE, a Write Response action
333        // SHALL be generated … otherwise no Write Response SHALL be sent."
334        if request.groupcast || write.suppress_response {
335            return Ok(Served::Silent);
336        }
337        Ok(Served::Reply {
338            opcode: opcode::WRITE_RESPONSE,
339            len,
340            more_chunks: false,
341        })
342    }
343
344    /// §8.8.2.3's Invoke: rules 1–3 are the Timed window, rule 4 is `MaxPathsPerInvoke`.
345    fn invoke<'a, A: AccessControl, H: ClusterHandler>(
346        &mut self,
347        server: &Server<'_, A, H>,
348        request: Request<'a>,
349        ctx: &InteractionContext<'_>,
350        scratch: &mut [u8],
351        buf: &mut [u8],
352    ) -> Result<Served<'a>> {
353        let invoke = InvokeRequest::decode(request.payload)?;
354        let timed = match self.timed.check(
355            request.session,
356            request.exchange,
357            invoke.timed_request,
358            ctx.now,
359        ) {
360            Ok(timed) => timed,
361            Err(status) => return status_reply(status, buf),
362        };
363
364        // Rule 4: "If this action contains more CommandDataIB elements in the InvokeRequests
365        // list than are supported by the device … then a Status Response action with the
366        // INVALID_ACTION Status Code SHALL be submitted to the message layer and this
367        // interaction SHALL terminate."
368        //
369        // Counted before anything is executed, because the point is to execute none of them.
370        // A malformed element inside the list is *not* judged here — that is rule 5's
371        // per-path processing, which answers with a status for that path rather than
372        // terminating the interaction — so the count stops at the first decode error and
373        // lets `serve_invoke` report it.
374        let mut commands = 0usize;
375        for command in invoke.commands()? {
376            if command.is_err() {
377                break;
378            }
379            commands = commands.saturating_add(1);
380            if commands > usize::from(self.max_paths_per_invoke) {
381                return status_reply(Status::InvalidAction, buf);
382            }
383        }
384
385        let mut ctx = *ctx;
386        ctx.timed = timed;
387        let (bytes, _) = server.serve_invoke(
388            invoke.commands()?,
389            &ctx,
390            invoke.suppress_response,
391            scratch,
392            buf,
393        )?;
394        // §8.8.2.3's Invoke Response Generation, first bullet: "If the previous action in this
395        // transaction action is groupcast, this process and transaction terminate with no
396        // response." The commands have run — that is the whole point of a groupcast — and the
397        // answer goes nowhere.
398        //
399        // It is the same rule the write path obeys and the one with the louder failure: a
400        // groupcast reaches every member of the group at once, so a node that answers turns one
401        // multicast into as many unicast responses as there are lights in the room, all sent in
402        // the same instant, to a sender that is not waiting for any of them.
403        if request.groupcast {
404            return Ok(Served::Silent);
405        }
406        Ok(Served::Reply {
407            opcode: opcode::INVOKE_RESPONSE,
408            len: bytes.len(),
409            more_chunks: false,
410        })
411    }
412
413    /// §8.7.4.3: answer `SUCCESS`, then expect a Write or Invoke within `Timeout`.
414    fn timed_request<'a>(
415        &mut self,
416        request: Request<'a>,
417        ctx: &InteractionContext<'_>,
418        buf: &mut [u8],
419    ) -> Result<Served<'a>> {
420        let timed = TimedRequest::decode(request.payload)?;
421        // §8.7.4: "the Timeout interval SHALL start when the Status Response action
422        // acknowledging the Timed Request action with a success code is sent". The dispatcher
423        // does not send — it writes the bytes the caller sends — so the window opens from
424        // `ctx.now`, which is the moment the action started and is earlier than the send by
425        // however long it takes to hand a buffer to a socket. Earlier is the safe direction:
426        // it can only shorten the client's window, never extend it past the timeout.
427        if self
428            .timed
429            .open(request.session, request.exchange, timed.timeout_ms, ctx.now)
430            .is_err()
431        {
432            // §8.7.3.2's exhaustion case: every slot holds a live window.
433            return status_reply(Status::Busy, buf);
434        }
435        status_reply(Status::Success, buf)
436    }
437}
438
439/// Encodes a `StatusResponse` carrying `status`.
440fn status_reply<'a>(status: Status, buf: &mut [u8]) -> Result<Served<'a>> {
441    let bytes = StatusResponse::new(status).encode(buf)?;
442    Ok(Served::Reply {
443        opcode: opcode::STATUS_RESPONSE,
444        len: bytes.len(),
445        more_chunks: false,
446    })
447}