rtci_stun/timer.rs
1//! The retransmission timer of RFC 8489 section 6.2, as data and arithmetic without I/O.
2//!
3//! [`Client`](crate::client::Client) runs on it, and so does every other transaction layer
4//! that sends STUN requests to a server (the TURN client), so that there is one schedule:
5//!
6//! * over UDP a request is sent at 0, RTO, 3 RTO, 7 RTO and so on (the interval doubles), Rc
7//! times in all, and its transaction fails Rm x RTO after the last one (section 6.2.1);
8//! * over a reliable transport it is sent once and fails Ti after it started (section 6.2.2);
9//! * the RTO starts at a configured value and then follows the server's round-trip times as
10//! RFC 6298 computes it, kept per server and dropped after ten minutes without a
11//! transaction ([`RtoEstimator`](crate::timer::RtoEstimator)).
12
13use std::time::{Duration, Instant};
14
15/// RFC 8489 section 6.2.1: the initial RTO "SHOULD be greater than or equal to 500 ms".
16pub const DEFAULT_RTO: Duration = Duration::from_millis(500);
17/// RFC 8489 section 6.2.1: Rc, the number of times a request is sent.
18pub const DEFAULT_RC: u32 = 7;
19/// RFC 8489 section 6.2.1: Rm, the last wait in units of RTO.
20pub const DEFAULT_RM: u32 = 16;
21/// RFC 8489 section 6.2.2: Ti, how long a request over a reliable transport waits.
22pub const DEFAULT_TI: Duration = Duration::from_millis(39_500);
23/// RFC 8489 section 6.2: outstanding transactions to one server.
24pub const DEFAULT_MAX_OUTSTANDING: usize = 10;
25/// RFC 8489 section 6.2.1: a cached RTO is stale after ten minutes without a transaction.
26pub const RTO_CACHE_LIFETIME: Duration = Duration::from_secs(600);
27/// RFC 6298 section 2: the clock granularity G; RFC 8489 asks for 1 ms accuracy.
28const CLOCK_GRANULARITY: Duration = Duration::from_millis(1);
29/// RFC 6298 section 2.5: an upper bound on the RTO.
30const MAX_RTO: Duration = Duration::from_secs(60);
31
32/// `now + d`, without the panic `Instant` reserves for an overflow.
33#[must_use]
34pub fn after(now: Instant, d: Duration) -> Instant {
35 now.checked_add(d)
36 .or_else(|| now.checked_add(Duration::from_secs(86_400)))
37 .unwrap_or(now)
38}
39
40/// The parameters of the retransmission schedule (RFC 8489 sections 6.2.1 and 6.2.2). The
41/// default is the RFC's: Rc 7, Rm 16, Ti 39.5 s.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct Schedule {
44 /// Rc: how many times a request is sent over an unreliable transport. At least 1.
45 pub rc: u32,
46 /// Rm: the transaction fails Rm x RTO after the last request.
47 pub rm: u32,
48 /// Ti: how long a request waits over a reliable transport, where it is sent once.
49 pub ti: Duration,
50}
51
52impl Default for Schedule {
53 fn default() -> Self {
54 Self {
55 rc: DEFAULT_RC,
56 rm: DEFAULT_RM,
57 ti: DEFAULT_TI,
58 }
59 }
60}
61
62impl Schedule {
63 /// When a request that was just sent at `now` for the `sent`-th time (1 for the first) is
64 /// due again, or, after the last one, when its transaction fails. `start` is when the
65 /// transaction started and `rto` the RTO it started with; `reliable` says the transport
66 /// retransmits for the client.
67 #[must_use]
68 pub fn next_deadline(
69 &self,
70 reliable: bool,
71 start: Instant,
72 rto: Duration,
73 sent: u32,
74 now: Instant,
75 ) -> Instant {
76 if reliable {
77 // Sent once; the transaction fails Ti after it started.
78 after(start, self.ti)
79 } else if sent < self.rc {
80 // The interval doubles after each retransmission: RTO, 2 RTO, 4 RTO, ...
81 let doublings = 1u32.checked_shl(sent.saturating_sub(1)).unwrap_or(u32::MAX);
82 after(now, rto.saturating_mul(doublings))
83 } else {
84 // The last request waits Rm x RTO.
85 after(now, rto.saturating_mul(self.rm))
86 }
87 }
88
89 /// Whether a request that was sent `sent` times is not sent again: its next deadline ends
90 /// the transaction.
91 #[must_use]
92 pub fn is_last(&self, reliable: bool, sent: u32) -> bool {
93 reliable || sent >= self.rc
94 }
95}
96
97/// The retransmission timeout of RFC 6298, as RFC 8489 section 6.2.1 uses it: kept per
98/// server, to 1 ms, never below the configured initial value, and forgotten after ten minutes
99/// without a transaction.
100#[derive(Debug, Clone, Copy)]
101pub struct RtoEstimator {
102 initial: Duration,
103 enabled: bool,
104 /// Smoothed round-trip time and its variation, once a round trip has been measured.
105 estimate: Option<(Duration, Duration)>,
106 rto: Duration,
107 last_transaction: Option<Instant>,
108}
109
110impl RtoEstimator {
111 /// An estimator that starts at `initial`. With `enabled` false every transaction starts
112 /// at `initial` whatever the round-trip times are.
113 #[must_use]
114 pub fn new(initial: Duration, enabled: bool) -> Self {
115 Self {
116 initial,
117 enabled,
118 estimate: None,
119 rto: initial,
120 last_transaction: None,
121 }
122 }
123
124 /// The RTO the next transaction starts with.
125 #[must_use]
126 pub fn rto(&self) -> Duration {
127 self.rto
128 }
129
130 /// Whether nothing was sent to or heard from the server for ten minutes at `now`, so that
131 /// the estimate is no longer used (and the estimator can be dropped).
132 #[must_use]
133 pub fn is_stale(&self, now: Instant) -> bool {
134 self.last_transaction
135 .is_some_and(|last| now.saturating_duration_since(last) > RTO_CACHE_LIFETIME)
136 }
137
138 /// The RTO a transaction that starts at `now` uses.
139 pub fn start(&mut self, now: Instant) -> Duration {
140 if self.is_stale(now) {
141 self.estimate = None;
142 self.rto = self.initial;
143 }
144 self.last_transaction = Some(now);
145 self.rto
146 }
147
148 /// Takes the round-trip time of a request that was answered without being retransmitted
149 /// (RFC 6298 sections 2.2, 2.3 and 3; RFC 8489 section 6.2.1 has Karn's rule: no sample
150 /// from a request that was sent more than once).
151 pub fn sample(&mut self, rtt: Duration, now: Instant) {
152 self.last_transaction = Some(now);
153 if !self.enabled {
154 return;
155 }
156 let (srtt, rttvar) = match self.estimate {
157 None => (rtt, rtt / 2),
158 Some((srtt, rttvar)) => {
159 let rttvar = (rttvar * 3 + srtt.abs_diff(rtt)) / 4;
160 let srtt = (srtt * 7 + rtt) / 8;
161 (srtt, rttvar)
162 }
163 };
164 self.estimate = Some((srtt, rttvar));
165 self.rto = (srtt + (rttvar * 4).max(CLOCK_GRANULARITY))
166 .max(self.initial)
167 .min(MAX_RTO.max(self.initial));
168 }
169}
170
171/// RFC 8489 section 6.3.4: after an error response of 500 through 599 "the client MAY resend
172/// the request; clients that do so MUST limit the number of times they do this. Unless a
173/// specific error code specifies a different value, the number of retransmissions SHOULD be
174/// limited to 4." The engine's clients resend that many times by default.
175pub const DEFAULT_SERVER_ERROR_RESENDS: u32 = 4;
176
177/// Whether `code` is one of the server errors (500 through 599) after which RFC 8489 section
178/// 6.3.4 lets a client resend its request.
179#[must_use]
180pub fn is_server_error(code: u16) -> bool {
181 (500..=599).contains(&code)
182}
183
184/// How long a client waits, after the server-error response, before the `resend`-th resend
185/// of a request (1 for the first): the interval its retransmission of the same number would
186/// wait (RFC 8489 section 6.2.1: RTO, then twice that, and so on), so that four resends are
187/// spread over RTO, 2 RTO, 4 RTO and 8 RTO (7.5 s at 500 ms) and a failing server is not
188/// asked again at the rate it answers. Each resend is a new transaction, under a new
189/// transaction id, with the retransmission timer of its own.
190#[must_use]
191pub fn server_error_resend_delay(rto: Duration, resend: u32) -> Duration {
192 let doublings = 1u32
193 .checked_shl(resend.saturating_sub(1))
194 .unwrap_or(u32::MAX);
195 rto.saturating_mul(doublings)
196}
197
198#[cfg(test)]
199mod server_error_tests {
200 use super::*;
201
202 /// RFC 8489 section 6.3.4: 500 through 599 only.
203 #[test]
204 fn only_500_through_599_are_server_errors() {
205 assert!(!is_server_error(499));
206 assert!(is_server_error(500));
207 assert!(is_server_error(508));
208 assert!(is_server_error(599));
209 assert!(!is_server_error(600));
210 assert!(!is_server_error(300));
211 assert!(!is_server_error(438));
212 }
213
214 /// The resends back off as retransmissions do: RTO, 2 RTO, 4 RTO, 8 RTO.
215 #[test]
216 fn the_server_error_resends_back_off_like_retransmissions() {
217 let rto = Duration::from_millis(500);
218 let delays: Vec<Duration> = (1..=DEFAULT_SERVER_ERROR_RESENDS)
219 .map(|n| server_error_resend_delay(rto, n))
220 .collect();
221 assert_eq!(
222 delays,
223 [500, 1000, 2000, 4000].map(Duration::from_millis).to_vec()
224 );
225 assert_eq!(DEFAULT_SERVER_ERROR_RESENDS, 4);
226 assert_eq!(
227 server_error_resend_delay(rto, 40),
228 rto.saturating_mul(u32::MAX)
229 );
230 }
231}