Skip to main content

matter_kit/exchange/
mrp.rs

1//! The Message Reliability Protocol (Core §4.12).
2//!
3//! UDP loses messages. MRP is how Matter gets them there anyway: a sender sets the **R**
4//! flag, keeps the message, and retransmits on a backoff curve until the receiver
5//! acknowledges it or [`MRP_MAX_TRANSMISSIONS`] attempts have gone by. The receiver
6//! acknowledges either by piggybacking on a message it was going to send anyway, or —
7//! after [`MRP_STANDALONE_ACK_TIMEOUT`] of having nothing to say — with a standalone
8//! acknowledgement.
9//!
10//! # Sans-I/O
11//!
12//! Nothing here touches a socket or reads a clock. Time arrives as a parameter:
13//!
14//! ```text
15//! on_send(counter, now)         // a reliable message went out
16//! on_ack(counter)               // the peer acknowledged one
17//! poll_deadline()               // when to come back
18//! on_timeout(now)               // the deadline passed: retransmit, or give up
19//! ```
20//!
21//! Which is what makes the whole five-transmission ladder — four seconds of wall-clock
22//! waiting — a unit test that runs in microseconds, and the same test every time.
23//!
24//! # The backoff curve
25//!
26//! §4.12.2.1 states it as
27//!
28//! ```text
29//! mrpBackoffTime = i * MRP_BACKOFF_BASE^max(0, n - MRP_BACKOFF_THRESHOLD)
30//!                    * (1.0 + random(0,1) * MRP_BACKOFF_JITTER)
31//! ```
32//!
33//! where `n` is "the number of send attempts before the current one" and `i` is the peer's
34//! retry interval, scaled by [`MRP_BACKOFF_MARGIN`]. The threshold gives it two phases:
35//! flat at first — "to improve initial latency when congestion is not the cause of packet
36//! drops" — and exponential after, "to provide convergence when the network is congested".
37//!
38//! It is computed here in integer arithmetic, because a microcontroller has no FPU and a
39//! retransmission timer does not need one. [`Duration::mul_ratio`] is the whole trick.
40
41use crate::error::{Error, ErrorCode, Result};
42use crate::platform::Duration;
43use crate::platform::Instant;
44
45/// "The maximum number of transmission attempts for a given reliable message" (Table 22).
46pub const MRP_MAX_TRANSMISSIONS: u32 = 5;
47
48/// "The base number for the exponential backoff equation": 1.6, as 16/10.
49pub const MRP_BACKOFF_BASE: (u64, u64) = (16, 10);
50
51/// "The scaler for random jitter in the backoff equation": 0.25, as 1/4.
52pub const MRP_BACKOFF_JITTER: (u64, u64) = (1, 4);
53
54/// "The scaler margin increase to backoff over the peer idle interval": 1.1, as 11/10.
55pub const MRP_BACKOFF_MARGIN: (u64, u64) = (11, 10);
56
57/// "The number of retransmissions before transitioning from linear to exponential
58/// backoff".
59pub const MRP_BACKOFF_THRESHOLD: u32 = 1;
60
61/// "Amount of time to wait for an opportunity to piggyback an acknowledgement on an
62/// outbound message before falling back to sending a standalone acknowledgement."
63pub const MRP_STANDALONE_ACK_TIMEOUT: Duration = Duration::from_millis(200);
64
65/// "Minimum amount of time between sender retries when the destination node is Idle"
66/// (Table 22).
67pub const SESSION_IDLE_INTERVAL: Duration = Duration::from_millis(500);
68
69/// "Minimum amount of time between sender retries when the destination node is Active".
70pub const SESSION_ACTIVE_INTERVAL: Duration = Duration::from_millis(300);
71
72/// "Minimum amount of time the node SHOULD stay active after network activity".
73pub const SESSION_ACTIVE_THRESHOLD: Duration = Duration::from_millis(4000);
74
75/// The peer's retry parameters, learned from discovery or session establishment
76/// (§4.12.3).
77///
78/// "MRP control parameters … are computed outside of the Exchange communication itself;
79/// instead, they are valid for the duration of a secure session." A peer advertises them
80/// in its `SII`, `SAI` and `SAT` TXT keys, or sends them in Sigma1/Sigma2 or the PBKDF
81/// parameter exchange.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct MrpParams {
84    /// `SESSION_IDLE_INTERVAL` — how often to retry a peer that is idle.
85    pub idle_interval: Duration,
86    /// `SESSION_ACTIVE_INTERVAL` — how often to retry a peer that is active.
87    pub active_interval: Duration,
88    /// `SESSION_ACTIVE_THRESHOLD` — how long a peer stays active after it last spoke.
89    pub active_threshold: Duration,
90}
91
92impl Default for MrpParams {
93    fn default() -> Self {
94        Self {
95            idle_interval: SESSION_IDLE_INTERVAL,
96            active_interval: SESSION_ACTIVE_INTERVAL,
97            active_threshold: SESSION_ACTIVE_THRESHOLD,
98        }
99    }
100}
101
102impl MrpParams {
103    /// Clamps values that arrived from a peer to what the specification allows.
104    ///
105    /// "The SII value SHALL NOT exceed 3600000 (1 hour in milliseconds)", likewise `SAI`;
106    /// `SAT` "SHALL NOT exceed 65535". A peer that sends more is not trusted to set this
107    /// node's timers to an hour and a half — these are numbers a stranger on the network
108    /// controls, and they decide how long this node waits.
109    #[must_use]
110    pub fn clamped(self) -> Self {
111        const MAX_INTERVAL: Duration = Duration::from_millis(3_600_000);
112        const MAX_THRESHOLD: Duration = Duration::from_millis(65_535);
113        Self {
114            idle_interval: min(self.idle_interval, MAX_INTERVAL),
115            active_interval: min(self.active_interval, MAX_INTERVAL),
116            active_threshold: min(self.active_threshold, MAX_THRESHOLD),
117        }
118    }
119
120    /// The base retry interval `i` for a peer in the given state, including the
121    /// [`MRP_BACKOFF_MARGIN`] of §4.12.2.1.
122    ///
123    /// "The backoff base interval SHALL be set to a value at least 10% greater than the
124    /// idle interval of the destination."
125    #[must_use]
126    pub fn base_interval(&self, peer_active: bool) -> Duration {
127        let i = if peer_active {
128            self.active_interval
129        } else {
130            self.idle_interval
131        };
132        i.mul_ratio(MRP_BACKOFF_MARGIN.0, MRP_BACKOFF_MARGIN.1)
133    }
134}
135
136const fn min(a: Duration, b: Duration) -> Duration {
137    if a.as_micros() <= b.as_micros() { a } else { b }
138}
139
140/// The retransmission timeout for the `n`-th attempt, without jitter (§4.12.2.1).
141///
142/// `n` is "the number of send attempts before the current one for this message (0 if this
143/// is the initial transmission)".
144#[must_use]
145pub fn backoff(base_interval: Duration, n: u32) -> Duration {
146    let exponent = n.saturating_sub(MRP_BACKOFF_THRESHOLD);
147    let mut d = base_interval;
148    for _ in 0..exponent {
149        d = d.mul_ratio(MRP_BACKOFF_BASE.0, MRP_BACKOFF_BASE.1);
150    }
151    d
152}
153
154/// Applies the jitter term `(1.0 + random(0,1) * MRP_BACKOFF_JITTER)`.
155///
156/// `randomness` is any value; its low bits are used as the `random(0,1)` draw, so a
157/// caller passes whatever its [`Rng`](crate::platform::Rng) produced without scaling it.
158/// Jitter only ever *adds*: the specification's term is `1.0 + …`, so the un-jittered
159/// backoff is the floor, not the average.
160#[must_use]
161pub fn with_jitter(backoff: Duration, randomness: u32) -> Duration {
162    // A draw in 0..RESOLUTION stands for random(0,1).
163    const RESOLUTION: u64 = 1 << 16;
164    let draw = u64::from(randomness) % RESOLUTION;
165    let denominator = RESOLUTION.saturating_mul(MRP_BACKOFF_JITTER.1);
166    let extra = backoff.mul_ratio(draw.saturating_mul(MRP_BACKOFF_JITTER.0), denominator);
167    backoff.saturating_add(extra)
168}
169
170/// What the sender should do when a retransmission timer fires.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum OnTimeout {
174    /// Send the message again; this is attempt number `attempt` (zero-based).
175    Retransmit {
176        /// The message counter to resend — "logical retransmission is of a given message
177        /// as identified by its message counter" (§4.4.1.4), so the counter does not
178        /// change.
179        counter: u32,
180        /// Which attempt this is, counting the original as 0.
181        attempt: u32,
182    },
183    /// Send the standalone acknowledgement that has been waiting for a piggyback ride.
184    SendStandaloneAck {
185        /// The counter to acknowledge.
186        counter: u32,
187    },
188    /// [`MRP_MAX_TRANSMISSIONS`] attempts have gone by unacknowledged. §4.12.2.1: the
189    /// sender gives up and, in the specification's words, notifies the application.
190    GiveUp {
191        /// The counter that was never acknowledged.
192        counter: u32,
193    },
194    /// The deadline that fired was not one this state machine set.
195    Nothing,
196}
197
198/// One exchange's reliability state.
199///
200/// §4.12.3: "MRP SHALL support one pending acknowledgement and one pending retransmission
201/// per Exchange" — so this holds exactly one of each, and the types say so.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub struct Mrp {
204    params: MrpParams,
205    /// The message awaiting acknowledgement, if any.
206    pending_tx: Option<PendingTx>,
207    /// The counter awaiting acknowledgement to the peer, if any.
208    pending_ack: Option<PendingAck>,
209    /// When the peer was last heard from, for the `PeerActiveMode` rule of §4.12.5.
210    last_heard: Option<Instant>,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214struct PendingTx {
215    counter: u32,
216    /// How many times it has been sent; 1 after the original transmission.
217    sent: u32,
218    /// When the current retransmission timer expires.
219    deadline: Instant,
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223struct PendingAck {
224    counter: u32,
225    /// When to give up on piggybacking and send a standalone acknowledgement.
226    deadline: Instant,
227}
228
229impl Mrp {
230    /// A fresh exchange with the given peer parameters.
231    #[must_use]
232    pub fn new(params: MrpParams) -> Self {
233        Self {
234            params: params.clamped(),
235            pending_tx: None,
236            pending_ack: None,
237            last_heard: None,
238        }
239    }
240
241    /// The peer's parameters, as clamped.
242    #[must_use]
243    pub const fn params(&self) -> MrpParams {
244        self.params
245    }
246
247    /// Whether a message is awaiting acknowledgement.
248    #[must_use]
249    pub const fn is_awaiting_ack(&self) -> bool {
250        self.pending_tx.is_some()
251    }
252
253    /// The counter awaiting acknowledgement from the peer, if any.
254    #[must_use]
255    pub const fn awaiting(&self) -> Option<u32> {
256        match self.pending_tx {
257            Some(tx) => Some(tx.counter),
258            None => None,
259        }
260    }
261
262    /// Whether the peer counts as active right now (§4.12.5).
263    ///
264    /// `PeerActiveMode = (now() - ActiveTimestamp) < SESSION_ACTIVE_THRESHOLD`.
265    #[must_use]
266    pub fn peer_active(&self, now: Instant) -> bool {
267        match self.last_heard {
268            Some(t) => now.saturating_duration_since(t) < self.params.active_threshold,
269            None => false,
270        }
271    }
272
273    /// Records that something arrived from the peer, which makes it active.
274    pub fn note_peer_activity(&mut self, now: Instant) {
275        self.last_heard = Some(now);
276    }
277
278    /// Records a reliable message that has just been sent.
279    ///
280    /// `randomness` seeds the jitter. Returns [`ErrorCode::Busy`] if a message is already
281    /// awaiting acknowledgement: §4.12.3 allows exactly one per exchange, and quietly
282    /// dropping the first would lose it.
283    pub fn on_send(&mut self, counter: u32, now: Instant, randomness: u32) -> Result<()> {
284        if self.pending_tx.is_some() {
285            return Err(Error::new(ErrorCode::Busy));
286        }
287        // §4.12.2.1: "For the first message of a new exchange, the base interval, i, SHALL
288        // be set according to the idle state of the peer … For all subsequent messages of
289        // the exchange, the base interval … according to the active state."
290        let base = self.params.base_interval(self.peer_active(now));
291        let deadline = now.saturating_add(with_jitter(backoff(base, 0), randomness));
292        self.pending_tx = Some(PendingTx {
293            counter,
294            sent: 1,
295            deadline,
296        });
297        Ok(())
298    }
299
300    /// The counter that should be piggybacked on the next outbound message, if any.
301    ///
302    /// Taking it clears the pending acknowledgement: §4.12.2.2's "piggybacking outstanding
303    /// acknowledgments on messages that it needs to send back".
304    pub fn take_piggyback(&mut self) -> Option<u32> {
305        self.pending_ack.take().map(|a| a.counter)
306    }
307
308    /// Records an arriving reliable message that must be acknowledged.
309    ///
310    /// `duplicate` says whether the message layer judged it a replay. §4.12.2.2: "The
311    /// receiver SHALL send an acknowledgment message to the sender for each instance of
312    /// an authenticated, reliable message, **including duplicates**" — so a duplicate
313    /// still schedules an acknowledgement; it is only the *payload* that is dropped.
314    pub fn on_reliable_received(&mut self, counter: u32, now: Instant, _duplicate: bool) {
315        self.note_peer_activity(now);
316        self.pending_ack = Some(PendingAck {
317            counter,
318            deadline: now.saturating_add(MRP_STANDALONE_ACK_TIMEOUT),
319        });
320    }
321
322    /// Records an acknowledgement from the peer.
323    ///
324    /// Returns `true` if it acknowledged the message that was pending. An acknowledgement
325    /// for anything else is ignored, not an error: a delayed duplicate acknowledgement for
326    /// an earlier message is a normal thing to receive.
327    pub fn on_ack(&mut self, counter: u32, now: Instant) -> bool {
328        self.note_peer_activity(now);
329        match self.pending_tx {
330            Some(tx) if tx.counter == counter => {
331                self.pending_tx = None;
332                true
333            }
334            _ => false,
335        }
336    }
337
338    /// The next instant at which [`Mrp::on_timeout`] has something to do.
339    #[must_use]
340    pub fn poll_deadline(&self) -> Option<Instant> {
341        match (self.pending_tx, self.pending_ack) {
342            (Some(tx), Some(ack)) => Some(min_instant(tx.deadline, ack.deadline)),
343            (Some(tx), None) => Some(tx.deadline),
344            (None, Some(ack)) => Some(ack.deadline),
345            (None, None) => None,
346        }
347    }
348
349    /// Handles a deadline that has passed.
350    ///
351    /// Call it whenever [`Mrp::poll_deadline`] has come and gone; call it again until it
352    /// returns [`OnTimeout::Nothing`], since a retransmission and a standalone
353    /// acknowledgement can both be due at once.
354    pub fn on_timeout(&mut self, now: Instant, randomness: u32) -> OnTimeout {
355        // The standalone acknowledgement first: it is cheap, and the peer is waiting on it
356        // before it will send anything this node could have piggybacked on.
357        if let Some(ack) = self.pending_ack
358            && ack.deadline.is_elapsed_at(now)
359        {
360            self.pending_ack = None;
361            return OnTimeout::SendStandaloneAck {
362                counter: ack.counter,
363            };
364        }
365
366        if let Some(tx) = self.pending_tx
367            && tx.deadline.is_elapsed_at(now)
368        {
369            if tx.sent >= MRP_MAX_TRANSMISSIONS {
370                self.pending_tx = None;
371                return OnTimeout::GiveUp {
372                    counter: tx.counter,
373                };
374            }
375            // `sent` is how many have gone out, which is exactly the `n` of §4.12.2.1 for
376            // the attempt about to be made.
377            let base = self.params.base_interval(self.peer_active(now));
378            let wait = with_jitter(backoff(base, tx.sent), randomness);
379            let attempt = tx.sent;
380            self.pending_tx = Some(PendingTx {
381                counter: tx.counter,
382                sent: tx.sent.saturating_add(1),
383                deadline: now.saturating_add(wait),
384            });
385            return OnTimeout::Retransmit {
386                counter: tx.counter,
387                attempt,
388            };
389        }
390
391        OnTimeout::Nothing
392    }
393
394    /// Abandons everything pending — what closing an exchange does.
395    pub fn close(&mut self) {
396        self.pending_tx = None;
397        self.pending_ack = None;
398    }
399}
400
401const fn min_instant(a: Instant, b: Instant) -> Instant {
402    if a.as_micros() <= b.as_micros() { a } else { b }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    /// The base interval Core Table 21 is computed with: the *active* interval of 300 ms
410    /// scaled by the 1.1 margin.
411    fn table_21_base() -> Duration {
412        MrpParams::default().base_interval(true)
413    }
414
415    #[test]
416    fn the_margin_is_applied_to_the_peer_interval() {
417        let p = MrpParams::default();
418        assert_eq!(p.base_interval(true).as_millis(), 330, "1.1 * 300");
419        assert_eq!(p.base_interval(false).as_millis(), 550, "1.1 * 500");
420    }
421
422    /// Milliseconds, rounded to nearest — which is how Core Table 21 is printed.
423    ///
424    /// The arithmetic here is exact microseconds: the fourth transmission is 844 800 µs,
425    /// and the table shows it as 845. Truncating instead of rounding makes that look like
426    /// an off-by-one in the backoff curve, when it is only how the table was typeset.
427    fn round_ms(d: Duration) -> u64 {
428        d.as_micros().saturating_add(500).wrapping_div(1_000)
429    }
430
431    #[test]
432    fn the_backoff_curve_matches_core_table_21() {
433        // "Min Jitter": 330, 330, 528, 845, 1352 for transmissions 0..4.
434        let base = table_21_base();
435        let expected = [330u64, 330, 528, 845, 1352];
436        for (n, want) in expected.iter().enumerate() {
437            let got = backoff(base, n as u32);
438            assert_eq!(round_ms(got), *want, "transmission #{n}");
439        }
440        // And the exact values, so a change to the arithmetic is visible rather than
441        // hidden inside a rounding tolerance.
442        assert_eq!(backoff(base, 0).as_micros(), 330_000);
443        assert_eq!(backoff(base, 2).as_micros(), 528_000);
444        assert_eq!(backoff(base, 3).as_micros(), 844_800);
445        assert_eq!(backoff(base, 4).as_micros(), 1_351_680);
446    }
447
448    #[test]
449    fn maximum_jitter_matches_core_table_21() {
450        // "Max Jitter": 413, 413, 660, 1056, 1690 — the min row times 1.25.
451        let base = table_21_base();
452        let expected = [413u64, 413, 660, 1056, 1690];
453        for (n, want) in expected.iter().enumerate() {
454            // The largest draw the resolution allows.
455            let got = round_ms(with_jitter(backoff(base, n as u32), u32::MAX));
456            // Within a millisecond of the table: the draw is `< 1`, never `== 1`.
457            assert!(
458                got.abs_diff(*want) <= 1,
459                "transmission #{n}: got {got}, table says {want}"
460            );
461        }
462    }
463
464    #[test]
465    fn jitter_only_ever_adds() {
466        // The specification's term is `(1.0 + random * 0.25)`, so the plain backoff is a
467        // floor. A jitter that could subtract would retry sooner than the peer allows.
468        let base = table_21_base();
469        for n in 0..MRP_MAX_TRANSMISSIONS {
470            let plain = backoff(base, n);
471            for r in [0u32, 1, 1000, u32::MAX / 2, u32::MAX] {
472                let jittered = with_jitter(plain, r);
473                assert!(jittered >= plain, "n={n} r={r}");
474                assert!(
475                    jittered <= plain.saturating_add(plain.mul_ratio(1, 4)),
476                    "n={n} r={r}: more than 25% added"
477                );
478            }
479        }
480    }
481
482    #[test]
483    fn a_zero_draw_is_the_unjittered_backoff() {
484        let base = table_21_base();
485        assert_eq!(with_jitter(backoff(base, 0), 0), backoff(base, 0));
486    }
487
488    #[test]
489    fn an_acknowledgement_stops_the_timer() {
490        let mut mrp = Mrp::new(MrpParams::default());
491        let t0 = Instant::ZERO;
492        mrp.on_send(7, t0, 0).expect("first send");
493        assert!(mrp.is_awaiting_ack());
494        assert_eq!(mrp.awaiting(), Some(7));
495        assert!(mrp.poll_deadline().is_some());
496
497        assert!(mrp.on_ack(7, t0), "the pending message is acknowledged");
498        assert!(!mrp.is_awaiting_ack());
499        assert_eq!(mrp.poll_deadline(), None);
500    }
501
502    #[test]
503    fn an_acknowledgement_for_something_else_is_ignored() {
504        let mut mrp = Mrp::new(MrpParams::default());
505        mrp.on_send(7, Instant::ZERO, 0).expect("send");
506        assert!(!mrp.on_ack(6, Instant::ZERO), "not the pending counter");
507        assert!(mrp.is_awaiting_ack(), "still waiting");
508    }
509
510    #[test]
511    fn one_pending_retransmission_per_exchange() {
512        // §4.12.3.
513        let mut mrp = Mrp::new(MrpParams::default());
514        mrp.on_send(1, Instant::ZERO, 0).expect("first");
515        assert_eq!(
516            mrp.on_send(2, Instant::ZERO, 0).unwrap_err().code(),
517            ErrorCode::Busy
518        );
519    }
520
521    #[test]
522    fn the_ladder_is_five_transmissions_then_give_up() {
523        let mut mrp = Mrp::new(MrpParams::default());
524        let mut now = Instant::ZERO;
525        mrp.on_send(42, now, 0).expect("send");
526
527        let mut attempts = heapless::Vec::<u32, 8>::new();
528        while let Some(deadline) = mrp.poll_deadline() {
529            now = deadline;
530            match mrp.on_timeout(now, 0) {
531                OnTimeout::Retransmit { counter, attempt } => {
532                    assert_eq!(counter, 42, "the counter never changes");
533                    let _ = attempts.push(attempt);
534                }
535                OnTimeout::GiveUp { counter } => {
536                    assert_eq!(counter, 42);
537                    break;
538                }
539                other => panic!("unexpected {other:?}"),
540            }
541        }
542        // The original plus four retransmissions is MRP_MAX_TRANSMISSIONS attempts.
543        assert_eq!(&attempts[..], &[1, 2, 3, 4]);
544        assert!(!mrp.is_awaiting_ack(), "giving up clears the state");
545    }
546
547    #[test]
548    fn the_cumulative_time_matches_core_table_21() {
549        // "Min Total": 330, 660, 1188, 2033, 3385.
550        let mut mrp = Mrp::new(MrpParams::default());
551        // Make the peer active, which is what Table 21 is computed for.
552        mrp.note_peer_activity(Instant::ZERO);
553        let mut now = Instant::ZERO;
554        mrp.on_send(1, now, 0).expect("send");
555
556        // Table 21's "Min Total" row is the running sum of its own *rounded* "Min
557        // Jitter" row, so it accumulates a little rounding: 330 + 330 + 528 + 845 + 1352.
558        // The sum of the exact values is 3 384 480 µs, which the table prints as 3385.
559        let expected = [330u64, 660, 1188, 2033, 3385];
560        let mut totals = heapless::Vec::<u64, 8>::new();
561        let mut rounded_sum = 0u64;
562        let mut previous = Instant::ZERO;
563        while let Some(deadline) = mrp.poll_deadline() {
564            now = deadline;
565            rounded_sum =
566                rounded_sum.saturating_add(round_ms(now.saturating_duration_since(previous)));
567            previous = now;
568            let _ = totals.push(rounded_sum);
569            if matches!(mrp.on_timeout(now, 0), OnTimeout::GiveUp { .. }) {
570                break;
571            }
572        }
573        assert_eq!(
574            &totals[..],
575            &expected[..],
576            "cumulative retransmission times"
577        );
578        assert_eq!(
579            now.saturating_duration_since(Instant::ZERO).as_micros(),
580            3_384_480,
581            "the exact total, before the table's per-step rounding"
582        );
583    }
584
585    #[test]
586    fn a_reliable_message_schedules_a_standalone_acknowledgement() {
587        let mut mrp = Mrp::new(MrpParams::default());
588        let t0 = Instant::ZERO;
589        mrp.on_reliable_received(9, t0, false);
590
591        let deadline = mrp.poll_deadline().expect("an ack deadline");
592        assert_eq!(
593            deadline.saturating_duration_since(t0),
594            MRP_STANDALONE_ACK_TIMEOUT
595        );
596        assert_eq!(
597            mrp.on_timeout(deadline, 0),
598            OnTimeout::SendStandaloneAck { counter: 9 }
599        );
600        assert_eq!(mrp.poll_deadline(), None, "and then nothing is pending");
601    }
602
603    #[test]
604    fn a_piggyback_cancels_the_standalone_acknowledgement() {
605        let mut mrp = Mrp::new(MrpParams::default());
606        mrp.on_reliable_received(9, Instant::ZERO, false);
607        assert_eq!(mrp.take_piggyback(), Some(9));
608        assert_eq!(mrp.poll_deadline(), None, "nothing left to send alone");
609        assert_eq!(mrp.take_piggyback(), None, "and only once");
610    }
611
612    #[test]
613    fn a_duplicate_is_still_acknowledged() {
614        // §4.12.2.2: "for each instance of an authenticated, reliable message, including
615        // duplicates". Not acknowledging one makes the peer retransmit until it gives up.
616        let mut mrp = Mrp::new(MrpParams::default());
617        mrp.on_reliable_received(9, Instant::ZERO, true);
618        assert_eq!(mrp.take_piggyback(), Some(9));
619    }
620
621    #[test]
622    fn an_idle_peer_gets_the_idle_interval() {
623        let mut mrp = Mrp::new(MrpParams::default());
624        let t0 = Instant::ZERO;
625        mrp.on_send(1, t0, 0).expect("send");
626        let deadline = mrp.poll_deadline().expect("a deadline");
627        assert_eq!(
628            deadline.saturating_duration_since(t0).as_millis(),
629            550,
630            "a peer never heard from is idle: 1.1 * 500"
631        );
632    }
633
634    #[test]
635    fn an_active_peer_gets_the_active_interval() {
636        let mut mrp = Mrp::new(MrpParams::default());
637        let t0 = Instant::ZERO;
638        mrp.note_peer_activity(t0);
639        mrp.on_send(1, t0, 0).expect("send");
640        let deadline = mrp.poll_deadline().expect("a deadline");
641        assert_eq!(deadline.saturating_duration_since(t0).as_millis(), 330);
642    }
643
644    #[test]
645    fn a_peer_goes_idle_after_the_active_threshold() {
646        let mut mrp = Mrp::new(MrpParams::default());
647        mrp.note_peer_activity(Instant::ZERO);
648        assert!(mrp.peer_active(Instant::from_micros(0)));
649        let just_inside = Instant::ZERO
650            .saturating_add(SESSION_ACTIVE_THRESHOLD)
651            .saturating_sub(Duration::from_micros(1));
652        assert!(mrp.peer_active(just_inside));
653        let at_threshold = Instant::ZERO.saturating_add(SESSION_ACTIVE_THRESHOLD);
654        assert!(!mrp.peer_active(at_threshold), "the comparison is strict");
655    }
656
657    #[test]
658    fn peer_parameters_from_the_network_are_clamped() {
659        // These are numbers a stranger sets, and they decide how long this node waits.
660        let hostile = MrpParams {
661            idle_interval: Duration::from_secs(86_400),
662            active_interval: Duration::from_secs(86_400),
663            active_threshold: Duration::from_secs(86_400),
664        };
665        let safe = hostile.clamped();
666        assert_eq!(safe.idle_interval.as_millis(), 3_600_000);
667        assert_eq!(safe.active_interval.as_millis(), 3_600_000);
668        assert_eq!(safe.active_threshold.as_millis(), 65_535);
669        // And a node built with them uses the clamped values.
670        assert_eq!(Mrp::new(hostile).params(), safe);
671    }
672
673    #[test]
674    fn both_a_retransmission_and_an_acknowledgement_can_be_due() {
675        let mut mrp = Mrp::new(MrpParams::default());
676        let t0 = Instant::ZERO;
677        mrp.on_send(1, t0, 0).expect("send");
678        mrp.on_reliable_received(2, t0, false);
679
680        // The acknowledgement is due first (200 ms against 550 ms).
681        let first = mrp.poll_deadline().expect("a deadline");
682        assert_eq!(
683            first.saturating_duration_since(t0),
684            MRP_STANDALONE_ACK_TIMEOUT
685        );
686        assert!(matches!(
687            mrp.on_timeout(first, 0),
688            OnTimeout::SendStandaloneAck { counter: 2 }
689        ));
690        // The retransmission is still scheduled.
691        assert!(mrp.poll_deadline().is_some());
692        assert!(mrp.is_awaiting_ack());
693    }
694
695    #[test]
696    fn an_early_timeout_does_nothing() {
697        let mut mrp = Mrp::new(MrpParams::default());
698        mrp.on_send(1, Instant::ZERO, 0).expect("send");
699        assert_eq!(
700            mrp.on_timeout(Instant::from_micros(1), 0),
701            OnTimeout::Nothing
702        );
703        assert!(mrp.is_awaiting_ack(), "and changes nothing");
704    }
705
706    #[test]
707    fn closing_abandons_everything() {
708        let mut mrp = Mrp::new(MrpParams::default());
709        mrp.on_send(1, Instant::ZERO, 0).expect("send");
710        mrp.on_reliable_received(2, Instant::ZERO, false);
711        mrp.close();
712        assert_eq!(mrp.poll_deadline(), None);
713        assert!(!mrp.is_awaiting_ack());
714    }
715}