Skip to main content

matter_kit/im/
client.rs

1//! The client half of the interaction model: putting a chunked answer back together.
2//!
3//! A client's encoding is already done — [`encode_read_request`](crate::im::encode_read_request)
4//! and its siblings build every request of chapter 10. What a client additionally needs, and
5//! what a server does not, is the *inverse of chunking*.
6//!
7//! §10.2.3 splits a report "into multiple messages at logical boundaries due to the size
8//! limitations imposed by IPv6 for UDP packets". A whole-node wildcard read therefore arrives
9//! as a series of `ReportData` messages, each carrying part of the answer and all but the last
10//! setting `MoreChunkedMessages`. A client that looked at only the first would silently see a
11//! fraction of the node — and would have no way to know it, because the fraction it sees is
12//! perfectly well-formed.
13//!
14//! [`ReportAssembler`] is the other side of [`Server::serve_chunk`](crate::im::Server::serve_chunk):
15//! feed it every chunk, and it tells you when the answer is whole.
16//!
17//! # Between chunks, the client must speak
18//!
19//! §10.2.3: "each data message requires a response before the next data message can be sent".
20//! The server will not send chunk *n+1* until the client's `StatusResponse` to chunk *n*
21//! arrives, so a client that assembles without acknowledging waits forever on a server that is
22//! waiting for it. [`ReportAssembler::push`] returning `false` is the signal to send one.
23//!
24//! # Lists arrive in pieces too
25//!
26//! A list too large for one message is sent as §10.6.4.3.1's series: one block clearing the
27//! list, then one block per item with `ListIndex` null. The assembler keeps those blocks as
28//! they came, in order, because reassembling them means knowing the attribute's *type* — which
29//! is the application's knowledge, not the interaction model's.
30//! [`AttributePath::list_index`](crate::im::AttributePath::list_index)
31//! is how each block says which it is.
32
33use crate::error::{Error, ErrorCode, Result, bail};
34use crate::im::ib::AttributeReport;
35use crate::im::message::ReportData;
36use crate::tlv::{ContainerKind, TlvReader, Value};
37
38/// An `Array` with an anonymous tag — Core Table 128's control octet.
39const ANONYMOUS_ARRAY: u8 = 0x16;
40/// End-of-container — §A.10: "control octet 0x18 exactly".
41const END_OF_CONTAINER: u8 = 0x18;
42
43/// Reassembles a report that arrived as a series of chunks (§10.2.3).
44///
45/// `N` is the byte budget for the assembled answer. A whole-node wildcard read of a real
46/// device is several kilobytes, so this is the one place in the crate where a caller has to
47/// size a buffer against *what it asked for* rather than against a message: the answer is by
48/// definition larger than any single message, or it would not have been chunked.
49#[derive(Debug)]
50pub struct ReportAssembler<const N: usize> {
51    /// A real `Array` element: the header, then every member seen so far, then — once the
52    /// last chunk has arrived — its end-of-container.
53    ///
54    /// Storing the members bare would be smaller and wrong: §A.1 says "all valid TLV
55    /// encodings consist of a single top-level element", so a bare run of members is not TLV
56    /// anything can read, and [`ReportAssembler::assembled`] promises bytes that can be
57    /// forwarded without looking.
58    buf: [u8; N],
59    len: usize,
60    subscription_id: Option<u32>,
61    chunks: usize,
62    complete: bool,
63}
64
65impl<const N: usize> Default for ReportAssembler<N> {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl<const N: usize> ReportAssembler<N> {
72    /// An empty assembler.
73    #[must_use]
74    pub const fn new() -> Self {
75        let mut buf = [0u8; N];
76        buf[0] = ANONYMOUS_ARRAY;
77        Self {
78            buf,
79            len: 1,
80            subscription_id: None,
81            chunks: 0,
82            complete: false,
83        }
84    }
85
86    /// Forgets everything, for the next read on the same buffer.
87    pub const fn reset(&mut self) {
88        self.buf[0] = ANONYMOUS_ARRAY;
89        self.len = 1;
90        self.subscription_id = None;
91        self.chunks = 0;
92        self.complete = false;
93    }
94
95    /// Whether the last chunk has arrived.
96    #[must_use]
97    pub const fn is_complete(&self) -> bool {
98        self.complete
99    }
100
101    /// How many messages the answer took.
102    #[must_use]
103    pub const fn chunks(&self) -> usize {
104        self.chunks
105    }
106
107    /// The subscription this report belongs to, if any (§8.5.3.2).
108    #[must_use]
109    pub const fn subscription_id(&self) -> Option<u32> {
110        self.subscription_id
111    }
112
113    /// Adds one chunk, returning whether the report is now complete.
114    ///
115    /// `false` means another `ReportData` is coming — and that the server is waiting for a
116    /// `StatusResponse` before it sends one (§10.2.3).
117    ///
118    /// [`ErrorCode::NoSpace`] means the answer is larger than `N`. Nothing partial is kept:
119    /// half a report is not a smaller report, it is a wrong one.
120    pub fn push(&mut self, report: &ReportData<'_>) -> Result<bool> {
121        if self.complete {
122            // A chunk after the last one is not part of this answer. Accepting it would
123            // silently splice two reports together.
124            bail!(InvalidState)
125        }
126        // §8.5.3.2 requires every report of one subscription to carry the same id; a change
127        // mid-answer means these are not chunks of the same thing.
128        match (self.subscription_id, report.subscription_id) {
129            (None, id) if self.chunks == 0 => self.subscription_id = id,
130            (held, id) if held == id => {}
131            _ => bail!(InvalidState),
132        }
133
134        if let Some(bytes) = report.attribute_reports_bytes() {
135            self.append_members(bytes)?;
136        }
137
138        self.chunks = self.chunks.saturating_add(1);
139        if !report.more_chunked_messages {
140            self.push_byte(END_OF_CONTAINER)?;
141            self.complete = true;
142        }
143        Ok(self.complete)
144    }
145
146    /// Copies each member of a captured `AttributeReports` array into the accumulator.
147    ///
148    /// Member by member rather than wholesale, because each chunk carries a *complete* array
149    /// element — header and end-of-container included — and concatenating two of those would
150    /// produce two arrays rather than one.
151    fn append_members(&mut self, array: &[u8]) -> Result<()> {
152        let mut reader = TlvReader::new_in(array, ContainerKind::Structure);
153        let Some(head) = reader.next_element()? else {
154            bail!(TlvTruncated)
155        };
156        if head.value.container() != Some(ContainerKind::Array) {
157            bail!(TlvWrongType)
158        }
159        loop {
160            let start = reader.position();
161            let Some(element) = reader.next_element()? else {
162                return Ok(());
163            };
164            if element.value == Value::EndOfContainer {
165                return Ok(());
166            }
167            reader.skip_value(&element)?;
168            let member = reader.slice_from(start)?;
169            let end = self
170                .len
171                .checked_add(member.len())
172                // One byte is always reserved for the end-of-container, so a report that
173                // exactly fills the buffer still closes.
174                .and_then(|end| (end < N).then_some(end))
175                .ok_or(Error::new(ErrorCode::NoSpace))?;
176            let Some(slot) = self.buf.get_mut(self.len..end) else {
177                bail!(NoSpace)
178            };
179            slot.copy_from_slice(member);
180            self.len = end;
181        }
182    }
183
184    fn push_byte(&mut self, byte: u8) -> Result<()> {
185        let Some(slot) = self.buf.get_mut(self.len) else {
186            bail!(NoSpace)
187        };
188        *slot = byte;
189        self.len = self.len.saturating_add(1);
190        Ok(())
191    }
192
193    /// Every attribute report the answer carried, in the order it arrived.
194    ///
195    /// Order is part of the answer: §10.6.4.3.1's list encoding is a clearing block followed
196    /// by its items, and reordering them would change what the list means.
197    pub fn reports(&self) -> Reports<'_> {
198        let mut reader = TlvReader::new(self.assembled());
199        // Step over the array header. An incomplete answer has no end-of-container yet, so
200        // this is also where an iteration before the last chunk stops being meaningful.
201        let opened = matches!(
202            reader.next_element(),
203            Ok(Some(element)) if element.value.container() == Some(ContainerKind::Array)
204        );
205        Reports {
206            reader,
207            done: !opened,
208        }
209    }
210
211    /// The assembled answer as one `Array` element.
212    ///
213    /// Valid TLV once [`ReportAssembler::is_complete`], and forwardable verbatim — a bridge
214    /// relaying a report it does not understand needs exactly this.
215    #[must_use]
216    pub fn assembled(&self) -> &[u8] {
217        self.buf.get(..self.len).unwrap_or(&[])
218    }
219}
220
221/// The attribute reports of an assembled answer, decoded one at a time.
222#[derive(Debug)]
223pub struct Reports<'a> {
224    reader: TlvReader<'a>,
225    done: bool,
226}
227
228impl<'a> Iterator for Reports<'a> {
229    type Item = Result<AttributeReport<'a>>;
230
231    fn next(&mut self) -> Option<Self::Item> {
232        if self.done {
233            return None;
234        }
235        let element = match self.reader.next_element() {
236            Ok(Some(element)) => element,
237            Ok(None) => {
238                self.done = true;
239                return None;
240            }
241            Err(e) => {
242                self.done = true;
243                return Some(Err(e));
244            }
245        };
246        if element.value == Value::EndOfContainer {
247            self.done = true;
248            return None;
249        }
250        if element.value.container() != Some(ContainerKind::Structure) {
251            self.done = true;
252            return Some(Err(Error::new(ErrorCode::TlvWrongType)));
253        }
254        match AttributeReport::decode(&mut self.reader) {
255            Ok(report) => Some(Ok(report)),
256            Err(e) => {
257                self.done = true;
258                Some(Err(e))
259            }
260        }
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::im::ib::AttributeData;
268    use crate::im::{AttributePath, encode_report_data};
269    use crate::tlv::{Tag, TlvWriter};
270
271    /// Builds a `ReportData` carrying `values` for attributes `first..`.
272    fn chunk(buf: &mut [u8], first: u32, values: &[u64], more: bool) -> usize {
273        let mut value_bufs: heapless::Vec<heapless::Vec<u8, 16>, 8> = heapless::Vec::new();
274        for value in values {
275            let mut scratch = [0u8; 16];
276            let mut w = TlvWriter::new_in(&mut scratch, ContainerKind::Structure);
277            w.unsigned(Tag::Context(2), *value).expect("value");
278            let encoded = w.finish().expect("finish");
279            value_bufs
280                .push(heapless::Vec::from_slice(encoded).expect("fits"))
281                .expect("fits");
282        }
283        let reports: heapless::Vec<AttributeReport<'_>, 8> = values
284            .iter()
285            .enumerate()
286            .map(|(index, _)| {
287                AttributeReport::Data(AttributeData {
288                    data_version: Some(1),
289                    path: AttributePath::attribute(1, 0x0006, first + index as u32),
290                    data: &value_bufs[index],
291                })
292            })
293            .collect();
294        let bytes = encode_report_data(buf, None, reports, more, false).expect("encode");
295        bytes.len()
296    }
297
298    #[test]
299    fn a_report_split_across_messages_comes_back_whole_and_in_order() {
300        let mut assembler = ReportAssembler::<512>::new();
301
302        let mut first = [0u8; 256];
303        let n = chunk(&mut first, 0, &[10, 11], true);
304        let report = ReportData::decode(&first[..n]).expect("decode");
305        assert!(
306            !assembler.push(&report).expect("push"),
307            "more is coming, and the server is waiting for a StatusResponse"
308        );
309
310        let mut second = [0u8; 256];
311        let n = chunk(&mut second, 2, &[12], false);
312        let report = ReportData::decode(&second[..n]).expect("decode");
313        assert!(assembler.push(&report).expect("push"), "the last chunk");
314
315        assert!(assembler.is_complete());
316        assert_eq!(assembler.chunks(), 2);
317
318        let paths: heapless::Vec<u32, 8> = assembler
319            .reports()
320            .map(|r| r.expect("decode").path().attribute.expect("concrete"))
321            .collect();
322        assert_eq!(
323            paths.as_slice(),
324            &[0, 1, 2],
325            "every block, in the order it arrived — order is part of the answer"
326        );
327    }
328
329    #[test]
330    fn a_single_message_answer_is_complete_at_once() {
331        let mut assembler = ReportAssembler::<256>::new();
332        let mut buf = [0u8; 256];
333        let n = chunk(&mut buf, 0, &[42], false);
334        let report = ReportData::decode(&buf[..n]).expect("decode");
335        assert!(assembler.push(&report).expect("push"));
336        assert_eq!(assembler.chunks(), 1);
337        assert_eq!(assembler.reports().count(), 1);
338    }
339
340    #[test]
341    fn an_answer_larger_than_the_buffer_is_refused_rather_than_truncated() {
342        // Half a report is not a smaller report, it is a wrong one — and a client that kept
343        // the fraction would have no way to tell.
344        let mut assembler = ReportAssembler::<24>::new();
345        let mut buf = [0u8; 256];
346        let n = chunk(&mut buf, 0, &[1, 2, 3, 4], false);
347        let report = ReportData::decode(&buf[..n]).expect("decode");
348        assert_eq!(
349            assembler.push(&report).map_err(|e| e.code()),
350            Err(ErrorCode::NoSpace)
351        );
352    }
353
354    #[test]
355    fn a_chunk_after_the_last_one_is_refused() {
356        // Accepting it would splice two separate answers into one.
357        let mut assembler = ReportAssembler::<256>::new();
358        let mut buf = [0u8; 256];
359        let n = chunk(&mut buf, 0, &[1], false);
360        let report = ReportData::decode(&buf[..n]).expect("decode");
361        assert!(assembler.push(&report).expect("push"));
362        assert_eq!(
363            assembler.push(&report).map_err(|e| e.code()),
364            Err(ErrorCode::InvalidState)
365        );
366    }
367
368    #[test]
369    fn chunks_of_two_different_subscriptions_are_not_spliced_together() {
370        // §8.5.3.2 requires every report of one subscription to carry the same id, so a
371        // change mid-answer means these are not chunks of the same thing.
372        let mut assembler = ReportAssembler::<512>::new();
373        let mut first = [0u8; 256];
374        let mut scratch = [0u8; 16];
375        let mut w = TlvWriter::new_in(&mut scratch, ContainerKind::Structure);
376        w.unsigned(Tag::Context(2), 1).expect("value");
377        let value = w.finish().expect("finish").to_vec();
378        let report = AttributeReport::Data(AttributeData {
379            data_version: Some(1),
380            path: AttributePath::attribute(1, 0x0006, 0),
381            data: &value,
382        });
383        let bytes = encode_report_data(&mut first, Some(7), [report], true, false).expect("encode");
384        let len = bytes.len();
385        let decoded = ReportData::decode(&first[..len]).expect("decode");
386        assert!(!assembler.push(&decoded).expect("push"));
387        assert_eq!(assembler.subscription_id(), Some(7));
388
389        let mut second = [0u8; 256];
390        let report = AttributeReport::Data(AttributeData {
391            data_version: Some(1),
392            path: AttributePath::attribute(1, 0x0006, 1),
393            data: &value,
394        });
395        let bytes =
396            encode_report_data(&mut second, Some(9), [report], false, false).expect("encode");
397        let len = bytes.len();
398        let decoded = ReportData::decode(&second[..len]).expect("decode");
399        assert_eq!(
400            assembler.push(&decoded).map_err(|e| e.code()),
401            Err(ErrorCode::InvalidState),
402            "a different subscription id is a different answer"
403        );
404    }
405
406    #[test]
407    fn reset_makes_it_usable_for_the_next_read() {
408        let mut assembler = ReportAssembler::<256>::new();
409        let mut buf = [0u8; 256];
410        let n = chunk(&mut buf, 0, &[1], false);
411        let report = ReportData::decode(&buf[..n]).expect("decode");
412        assembler.push(&report).expect("push");
413        assembler.reset();
414        assert!(!assembler.is_complete());
415        assert_eq!(assembler.chunks(), 0);
416        assert_eq!(assembler.reports().count(), 0);
417        assembler.push(&report).expect("usable again");
418        assert!(assembler.is_complete());
419    }
420}
421
422// --- Subscriptions, from the client's side ---------------------------------------------------
423
424/// What a client knows about a subscription it holds (§8.5).
425///
426/// The server's half lives in [`subscription`](crate::im::subscription); this is the twin a
427/// controller keeps. It exists for one reason: §8.5.3.2 lets the server answer with intervals
428/// that are *not* the ones requested —
429///
430/// > the publisher SHALL compute the MaxInterval ... and SHALL report it in the
431/// > SubscribeResponse
432///
433/// — so a client that assumed its own ceiling had been honoured would declare a perfectly live
434/// subscription dead, tear it down and build another, for ever.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub struct Subscription {
437    /// `SubscriptionID`, which every subsequent report carries.
438    id: u32,
439    /// The `MaxInterval` the *publisher* chose, in seconds.
440    max_interval_s: u16,
441    /// When the last report or keep-alive arrived.
442    last_heard: crate::platform::Instant,
443}
444
445impl Subscription {
446    /// Records a subscription the publisher has just confirmed.
447    #[must_use]
448    pub const fn new(
449        response: &crate::im::message::SubscribeResponse,
450        now: crate::platform::Instant,
451    ) -> Self {
452        Self {
453            id: response.subscription_id,
454            max_interval_s: response.max_interval_s,
455            last_heard: now,
456        }
457    }
458
459    /// The id every report of this subscription carries.
460    #[must_use]
461    pub const fn id(&self) -> u32 {
462        self.id
463    }
464
465    /// The `MaxInterval` the publisher chose — not the ceiling that was asked for.
466    #[must_use]
467    pub const fn max_interval_s(&self) -> u16 {
468        self.max_interval_s
469    }
470
471    /// Records that something arrived on this subscription.
472    ///
473    /// Any report counts, including §8.5.3's empty keep-alive: "the publisher SHALL send an
474    /// empty ReportData message" when nothing has changed by the maximum interval, and its
475    /// whole purpose is to be this proof of life.
476    ///
477    /// Returns `false` — and records nothing — for a report belonging to a *different*
478    /// subscription. §8.5.3.2 makes the id part of every report precisely so a subscriber
479    /// holding several can tell them apart; crediting one subscription's liveness to another
480    /// would keep a dead one alive indefinitely.
481    pub fn heard(&mut self, report: &ReportData<'_>, now: crate::platform::Instant) -> bool {
482        if report.subscription_id != Some(self.id) {
483            return false;
484        }
485        self.last_heard = now;
486        true
487    }
488
489    /// When this subscription should be considered lost (§8.5.4).
490    ///
491    /// > If the subscriber does not receive a report within the maximum interval ... the
492    /// > subscriber SHALL consider the subscription to have expired.
493    ///
494    /// The window is deliberately generous: `MaxInterval` plus the time a report needs to
495    /// traverse a lossy network and be retried by MRP. A subscriber that timed out at exactly
496    /// `MaxInterval` would tear down a working subscription on the first retransmission — and
497    /// a Thread network's first retransmission is not unusual.
498    #[must_use]
499    pub fn expires_at(&self) -> crate::platform::Instant {
500        self.last_heard.saturating_add(
501            crate::platform::Duration::from_secs(u64::from(self.max_interval_s))
502                .saturating_add(LIVENESS_MARGIN),
503        )
504    }
505
506    /// Whether the subscription has gone quiet for longer than §8.5.4 permits.
507    #[must_use]
508    pub fn is_expired(&self, now: crate::platform::Instant) -> bool {
509        now >= self.expires_at()
510    }
511}
512
513/// How long past `MaxInterval` a subscriber waits before giving up (§8.5.4).
514///
515/// §8.5.4 does not fix a number — it says a subscriber "SHALL consider the subscription to have
516/// expired" without saying when to start counting past the interval. This is the allowance for
517/// one MRP retransmission cycle over a sleepy network, which is the case that makes an exact
518/// deadline wrong.
519pub const LIVENESS_MARGIN: crate::platform::Duration = crate::platform::Duration::from_secs(10);