Skip to main content

matter_kit/im/
timed.rs

1//! The Timed transaction window — Core §8.7.4, §8.7.3.2, §8.8.2.3.
2//!
3//! A Timed transaction puts a deadline on its second phase:
4//!
5//! ```text
6//! Timed Request (Timeout = 1000 ms)  ──▶
7//!                                    ◀──  Status Response (SUCCESS)   ← the clock starts here
8//! Write Request / Invoke Request     ──▶   … within 1000 ms, or TIMEOUT
9//! ```
10//!
11//! Elements with the `T` quality require one — `Door Lock`'s unlock,
12//! `OpenCommissioningWindow`, Access Control entries — so that a captured message stops being
13//! useful shortly after it is captured.
14//!
15//! [`ClusterHandler`](super::server::ClusterHandler) already refuses an element that requires
16//! a Timed transaction when
17//! [`InteractionContext::timed`](super::server::InteractionContext::timed) is false.
18//! [`TimedWindows`] is what *decides* that flag, applying §8.7.3.2's and §8.8.2.3's rules —
19//! the same on both the Write and Invoke sides:
20//!
21//! | Window | `TimedRequest` flag | Outcome |
22//! |---|---|---|
23//! | open, not expired | true | proceed, timed |
24//! | open, **expired** | either | `TIMEOUT` |
25//! | open, not expired | false | `TIMED_REQUEST_MISMATCH` |
26//! | none | true | `TIMED_REQUEST_MISMATCH` |
27//! | none | false | proceed, untimed |
28//!
29//! The two failures stay distinct: `TIMEOUT` means retry with a longer timeout,
30//! `TIMED_REQUEST_MISMATCH` means the client is wrong. Both were `UNSUPPORTED_ACCESS` before
31//! Matter 1.4.
32
33use crate::msg::{ExchangeId, SessionId};
34use crate::platform::{Duration, Instant};
35
36use super::status::Status;
37
38/// One open Timed transaction window.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40struct Window {
41    /// The session the Timed Request arrived on.
42    session: Option<SessionId>,
43    /// The exchange — §8.7.3.2's "matching the same TransactionID".
44    exchange: ExchangeId,
45    /// When the window closes.
46    deadline: Instant,
47}
48
49/// The open Timed transaction windows of a node.
50///
51/// `N` is how many may be open at once. One per concurrent administrator is generous: a Timed
52/// transaction's whole life is one round trip plus a timeout the *client* chose, and a client
53/// with two open at once on the same session is already misbehaving.
54#[derive(Debug, Clone)]
55pub struct TimedWindows<const N: usize> {
56    windows: [Option<Window>; N],
57}
58
59impl<const N: usize> Default for TimedWindows<N> {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl<const N: usize> TimedWindows<N> {
66    /// A table with nothing open.
67    #[must_use]
68    pub const fn new() -> Self {
69        Self { windows: [None; N] }
70    }
71
72    /// Opens a window, as §8.7.4.3 requires after answering a Timed Request.
73    ///
74    /// `sent_at` is when the `SUCCESS` status response went out, **not** when the Timed Request
75    /// arrived: §8.7.4, "the Timeout interval SHALL start when the Status Response action
76    /// acknowledging the Timed Request action with a success code is sent".
77    ///
78    /// A second Timed Request on the same exchange replaces the first: one transaction, one
79    /// deadline.
80    ///
81    /// # Errors
82    ///
83    /// [`ErrorCode::NoSpace`](crate::ErrorCode::NoSpace) when every slot holds a live window —
84    /// §8.7.3.2's `BUSY` case, so a caller answers [`Status::Busy`] rather than pretending the
85    /// window opened.
86    pub fn open(
87        &mut self,
88        session: Option<SessionId>,
89        exchange: ExchangeId,
90        timeout_ms: u16,
91        sent_at: Instant,
92    ) -> crate::Result<()> {
93        let window = Window {
94            session,
95            exchange,
96            deadline: sent_at.saturating_add(Duration::from_millis(u64::from(timeout_ms))),
97        };
98        if let Some(slot) = self.slot_for(session, exchange) {
99            *slot = Some(window);
100            return Ok(());
101        }
102        if let Some(slot) = self.windows.iter_mut().find(|slot| slot.is_none()) {
103            *slot = Some(window);
104            return Ok(());
105        }
106        // Every slot is taken. An expired window is a window whose client is not coming back,
107        // so it is the one to give up — at the cost that its owner now gets
108        // TIMED_REQUEST_MISMATCH instead of TIMEOUT if it turns up after all. Both are
109        // refusals, and holding the slot would refuse a client that is on time.
110        let oldest_expired = self
111            .windows
112            .iter_mut()
113            .filter(|slot| slot.is_some_and(|w| w.deadline <= sent_at))
114            .min_by_key(|slot| slot.map(|w| w.deadline));
115        if let Some(slot) = oldest_expired {
116            *slot = Some(window);
117            return Ok(());
118        }
119        Err(crate::Error::new(crate::ErrorCode::NoSpace))
120    }
121
122    /// Applies §8.7.3.2 and §8.8.2.3's timed rules to an arriving Write or Invoke Request.
123    ///
124    /// `timed_request` is the request's own `TimedRequest` flag. Returns what
125    /// [`InteractionContext::timed`](super::server::InteractionContext::timed) must be set to,
126    /// or the status the interaction terminates with.
127    ///
128    /// The window is **consumed** either way — every outcome here terminates the transaction,
129    /// and a window that survived would let one Timed Request pay for a second request later.
130    ///
131    /// # Errors
132    ///
133    /// [`Status::Timeout`] when the window expired, [`Status::TimedRequestMismatch`] when the
134    /// flag and the window disagree.
135    pub fn check(
136        &mut self,
137        session: Option<SessionId>,
138        exchange: ExchangeId,
139        timed_request: bool,
140        now: Instant,
141    ) -> core::result::Result<bool, Status> {
142        let Some(slot) = self.slot_for(session, exchange) else {
143            // §8.8.2.3 rule 3: "If this action is marked with TimedRequest as TRUE, but this
144            // action is not part of a Timed Invoke transaction … TIMED_REQUEST_MISMATCH".
145            return if timed_request {
146                Err(Status::TimedRequestMismatch)
147            } else {
148                Ok(false)
149            };
150        };
151        let expired = slot.is_some_and(|window| now > window.deadline);
152        *slot = None;
153        if expired {
154            // §8.8.2.3 rule 1 is checked before rule 2: an expired window is TIMEOUT whatever
155            // the flag says. A client that is both late and wrong is told it was late, which is
156            // the fault it can do something about.
157            return Err(Status::Timeout);
158        }
159        if !timed_request {
160            // §8.8.2.3 rule 2.
161            return Err(Status::TimedRequestMismatch);
162        }
163        Ok(true)
164    }
165
166    /// Closes the window on an exchange without applying any rule.
167    ///
168    /// For the case where the exchange itself ends — the session closed, the client vanished —
169    /// rather than a request arriving on it.
170    pub fn close(&mut self, session: Option<SessionId>, exchange: ExchangeId) {
171        if let Some(slot) = self.slot_for(session, exchange) {
172            *slot = None;
173        }
174    }
175
176    /// Drops every window of a session, for when the session closes.
177    pub fn close_session(&mut self, session: Option<SessionId>) {
178        for slot in &mut self.windows {
179            if slot.is_some_and(|window| window.session == session) {
180                *slot = None;
181            }
182        }
183    }
184
185    /// Drops every window whose deadline has passed, returning how many went.
186    ///
187    /// Optional: [`TimedWindows::open`] already reclaims expired slots when it needs one. A
188    /// window dropped here can no longer produce [`Status::Timeout`], only
189    /// [`Status::TimedRequestMismatch`], since the evidence that there was a window is gone.
190    pub fn reap(&mut self, now: Instant) -> usize {
191        let mut reaped = 0usize;
192        for slot in &mut self.windows {
193            if slot.is_some_and(|window| now > window.deadline) {
194                *slot = None;
195                reaped = reaped.saturating_add(1);
196            }
197        }
198        reaped
199    }
200
201    /// How many windows are held, expired or not.
202    #[must_use]
203    pub fn len(&self) -> usize {
204        self.windows.iter().filter(|slot| slot.is_some()).count()
205    }
206
207    /// Whether no window is held.
208    #[must_use]
209    pub fn is_empty(&self) -> bool {
210        self.len() == 0
211    }
212
213    /// The earliest deadline, for a caller that wants to schedule a reap.
214    #[must_use]
215    pub fn next_deadline(&self) -> Option<Instant> {
216        self.windows
217            .iter()
218            .filter_map(|slot| slot.map(|window| window.deadline))
219            .min()
220    }
221
222    fn slot_for(
223        &mut self,
224        session: Option<SessionId>,
225        exchange: ExchangeId,
226    ) -> Option<&mut Option<Window>> {
227        self.windows.iter_mut().find(|slot| {
228            slot.is_some_and(|window| window.session == session && window.exchange == exchange)
229        })
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    const SESSION: Option<SessionId> = Some(SessionId(7));
238    const EXCHANGE: ExchangeId = ExchangeId(42);
239
240    fn at(ms: u64) -> Instant {
241        Instant::ZERO.saturating_add(Duration::from_millis(ms))
242    }
243
244    #[test]
245    fn an_untimed_request_with_no_window_proceeds() {
246        let mut windows = TimedWindows::<2>::new();
247        assert_eq!(windows.check(SESSION, EXCHANGE, false, at(0)), Ok(false));
248    }
249
250    #[test]
251    fn a_timed_request_inside_the_window_proceeds() {
252        let mut windows = TimedWindows::<2>::new();
253        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
254        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(999)), Ok(true));
255    }
256
257    #[test]
258    fn the_deadline_is_inclusive_of_its_last_instant() {
259        // §8.7.4: "within Timeout milliseconds of sending the Status Response". A request that
260        // arrives exactly on the boundary is within it.
261        let mut windows = TimedWindows::<2>::new();
262        windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
263        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(100)), Ok(true));
264
265        let mut windows = TimedWindows::<2>::new();
266        windows.open(SESSION, EXCHANGE, 100, at(0)).expect("open");
267        assert_eq!(
268            windows.check(SESSION, EXCHANGE, true, at(101)),
269            Err(Status::Timeout)
270        );
271    }
272
273    #[test]
274    fn the_clock_starts_when_the_status_response_is_sent() {
275        // §8.7.4: "The Timeout interval SHALL start when the Status Response action
276        // acknowledging the Timed Request action with a success code is sent." A server that
277        // started it on *receipt* would charge the client for its own processing.
278        let mut windows = TimedWindows::<2>::new();
279        // The request arrived at 0; the status response went out at 50.
280        windows.open(SESSION, EXCHANGE, 100, at(50)).expect("open");
281        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(150)), Ok(true));
282    }
283
284    #[test]
285    fn an_expired_window_is_timeout_not_mismatch() {
286        let mut windows = TimedWindows::<2>::new();
287        windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
288        assert_eq!(
289            windows.check(SESSION, EXCHANGE, true, at(11)),
290            Err(Status::Timeout)
291        );
292    }
293
294    #[test]
295    fn expiry_is_checked_before_the_flag() {
296        // §8.8.2.3 lists them in that order. A client that is both late and has its flag clear
297        // is told it was late — the fault it can act on.
298        let mut windows = TimedWindows::<2>::new();
299        windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
300        assert_eq!(
301            windows.check(SESSION, EXCHANGE, false, at(11)),
302            Err(Status::Timeout)
303        );
304    }
305
306    #[test]
307    fn a_timed_window_with_an_untimed_request_is_a_mismatch() {
308        // §8.8.2.3 rule 2.
309        let mut windows = TimedWindows::<2>::new();
310        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
311        assert_eq!(
312            windows.check(SESSION, EXCHANGE, false, at(1)),
313            Err(Status::TimedRequestMismatch)
314        );
315    }
316
317    #[test]
318    fn an_untimed_window_with_a_timed_request_is_a_mismatch() {
319        // §8.8.2.3 rule 3. This is the one a replay would hit: a captured Invoke Request with
320        // `TimedRequest` set, sent again later with no Timed Request in front of it.
321        let mut windows = TimedWindows::<2>::new();
322        assert_eq!(
323            windows.check(SESSION, EXCHANGE, true, at(0)),
324            Err(Status::TimedRequestMismatch)
325        );
326    }
327
328    #[test]
329    fn a_window_is_consumed_by_the_request_it_admits() {
330        // Every outcome terminates the transaction, so a second request must not find the
331        // window still open — that would let one Timed Request pay for two writes.
332        let mut windows = TimedWindows::<2>::new();
333        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
334        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
335        assert_eq!(
336            windows.check(SESSION, EXCHANGE, true, at(2)),
337            Err(Status::TimedRequestMismatch)
338        );
339        assert!(windows.is_empty());
340    }
341
342    #[test]
343    fn a_window_is_consumed_even_by_a_request_it_refuses() {
344        let mut windows = TimedWindows::<2>::new();
345        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
346        assert_eq!(
347            windows.check(SESSION, EXCHANGE, false, at(1)),
348            Err(Status::TimedRequestMismatch)
349        );
350        assert!(windows.is_empty());
351    }
352
353    #[test]
354    fn windows_are_scoped_to_their_exchange_and_session() {
355        // §8.7.3.2: "matching the same TransactionID". Another exchange's window must not
356        // admit this one's request, or one Timed Request would cover a whole session.
357        let mut windows = TimedWindows::<4>::new();
358        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
359        assert_eq!(
360            windows.check(SESSION, ExchangeId(43), true, at(1)),
361            Err(Status::TimedRequestMismatch)
362        );
363        assert_eq!(
364            windows.check(Some(SessionId(8)), EXCHANGE, true, at(1)),
365            Err(Status::TimedRequestMismatch)
366        );
367        // And the original is untouched.
368        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(1)), Ok(true));
369    }
370
371    #[test]
372    fn a_second_timed_request_on_one_exchange_replaces_the_first() {
373        let mut windows = TimedWindows::<2>::new();
374        windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
375        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
376        assert_eq!(windows.len(), 1, "one transaction, one deadline");
377        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(500)), Ok(true));
378    }
379
380    #[test]
381    fn a_full_table_of_live_windows_refuses() {
382        let mut windows = TimedWindows::<2>::new();
383        windows
384            .open(SESSION, ExchangeId(1), 1000, at(0))
385            .expect("open");
386        windows
387            .open(SESSION, ExchangeId(2), 1000, at(0))
388            .expect("open");
389        assert!(
390            windows.open(SESSION, ExchangeId(3), 1000, at(0)).is_err(),
391            "§8.7.3.2's BUSY case"
392        );
393        // Both live windows survive the refusal.
394        assert_eq!(windows.check(SESSION, ExchangeId(1), true, at(1)), Ok(true));
395    }
396
397    #[test]
398    fn a_full_table_gives_up_its_oldest_expired_window_first() {
399        let mut windows = TimedWindows::<2>::new();
400        windows
401            .open(SESSION, ExchangeId(1), 10, at(0))
402            .expect("open");
403        windows
404            .open(SESSION, ExchangeId(2), 20, at(0))
405            .expect("open");
406        windows
407            .open(SESSION, ExchangeId(3), 1000, at(100))
408            .expect("open");
409        // Exchange 1 expired first, so it is the one that went.
410        assert_eq!(
411            windows.check(SESSION, ExchangeId(1), true, at(101)),
412            Err(Status::TimedRequestMismatch)
413        );
414        assert_eq!(
415            windows.check(SESSION, ExchangeId(2), true, at(101)),
416            Err(Status::Timeout),
417            "the later-expiring window is still there to report TIMEOUT"
418        );
419    }
420
421    #[test]
422    fn closing_a_session_drops_its_windows_and_leaves_others() {
423        let mut windows = TimedWindows::<4>::new();
424        windows
425            .open(SESSION, ExchangeId(1), 1000, at(0))
426            .expect("open");
427        windows
428            .open(Some(SessionId(8)), ExchangeId(1), 1000, at(0))
429            .expect("open");
430        windows.close_session(SESSION);
431        assert_eq!(windows.len(), 1);
432        assert_eq!(
433            windows.check(Some(SessionId(8)), ExchangeId(1), true, at(1)),
434            Ok(true)
435        );
436    }
437
438    #[test]
439    fn reaping_trades_timeout_for_mismatch() {
440        let mut windows = TimedWindows::<2>::new();
441        windows.open(SESSION, EXCHANGE, 10, at(0)).expect("open");
442        assert_eq!(windows.reap(at(11)), 1);
443        // The evidence that there was ever a window is gone, so the late client is told its
444        // flag was wrong rather than that it was slow. Both refuse; only one is informative.
445        assert_eq!(
446            windows.check(SESSION, EXCHANGE, true, at(12)),
447            Err(Status::TimedRequestMismatch)
448        );
449    }
450
451    #[test]
452    fn reaping_leaves_live_windows_alone() {
453        let mut windows = TimedWindows::<2>::new();
454        windows.open(SESSION, EXCHANGE, 1000, at(0)).expect("open");
455        assert_eq!(windows.reap(at(11)), 0);
456        assert_eq!(windows.check(SESSION, EXCHANGE, true, at(12)), Ok(true));
457    }
458
459    #[test]
460    fn the_next_deadline_is_the_earliest() {
461        let mut windows = TimedWindows::<4>::new();
462        assert_eq!(windows.next_deadline(), None);
463        windows
464            .open(SESSION, ExchangeId(1), 500, at(0))
465            .expect("open");
466        windows
467            .open(SESSION, ExchangeId(2), 100, at(0))
468            .expect("open");
469        assert_eq!(windows.next_deadline(), Some(at(100)));
470    }
471
472    #[test]
473    fn a_zero_timeout_expires_immediately_but_still_reports_timeout() {
474        // A client may legally ask for zero. It gets one instant, and after that TIMEOUT —
475        // not a mismatch, because the window really did exist.
476        let mut windows = TimedWindows::<2>::new();
477        windows.open(SESSION, EXCHANGE, 0, at(0)).expect("open");
478        assert_eq!(
479            windows.check(SESSION, EXCHANGE, true, at(1)),
480            Err(Status::Timeout)
481        );
482    }
483}