Skip to main content

rtci_shared/stream/
happy_eyeballs.rs

1//! Happy Eyeballs (RFC 8305) for a sans-I/O engine: the order in which a server's addresses
2//! are tried and when the next attempt starts. The driver resolves names
3//! ([`StreamCommand::Resolve`](super::StreamCommand::Resolve)), answering both families at
4//! once ([`StreamEvent::Resolved`](super::StreamEvent::Resolved)) or each as it arrives
5//! ([`StreamEvent::ResolvedFamily`](super::StreamEvent::ResolvedFamily)); the engine sorts and
6//! staggers the attempts with [`HappyEyeballs`] and keeps the first that succeeds. With answers
7//! per family the race starts on the first one (RFC 8305 section 3): at once on IPv6, after the
8//! Resolution Delay on IPv4 while IPv6 is outstanding, and a late answer joins the addresses
9//! not yet tried.
10
11use std::collections::{HashMap, HashSet, VecDeque};
12use std::net::{IpAddr, SocketAddr};
13use std::time::{Duration, Instant};
14
15/// RFC 8305 section 8: the recommended Connection Attempt Delay.
16pub const CONNECTION_ATTEMPT_DELAY: Duration = Duration::from_millis(250);
17/// RFC 8305 section 5: an attempt never starts within 10 ms of the previous one.
18pub const MIN_CONNECTION_ATTEMPT_DELAY: Duration = Duration::from_millis(10);
19/// RFC 8305 section 5: the upper bound of the delay ("Maximum Connection Attempt Delay").
20pub const MAX_CONNECTION_ATTEMPT_DELAY: Duration = Duration::from_secs(2);
21/// RFC 8305 section 8: the recommended Resolution Delay, how long an IPv4 answer waits for the
22/// IPv6 one before the race starts on it.
23pub const RESOLUTION_DELAY: Duration = Duration::from_millis(50);
24
25/// RFC 8305 section 4: addresses interleaved by family, the preferred family first ("First
26/// Address Family Count" of one), each family keeping its own order. IPv6 is preferred, as
27/// the RFC's default; duplicates are dropped.
28pub fn sort_addresses(addresses: &[SocketAddr], prefer_ipv6: bool) -> Vec<SocketAddr> {
29    sort_addresses_ranked(addresses, prefer_ipv6, |_| AddressRank::default())
30}
31
32/// What the history says of one address, for the order of the attempts
33/// ([`AddressHistory::rank`]): lower first. The default (nothing known) sorts after an
34/// address that answered and before one whose last attempt failed.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
36pub struct AddressRank {
37    /// The last attempt on the address failed (RFC 6724 rule 1, "Avoid unusable
38    /// destinations").
39    failed: bool,
40    /// The time the last successful attempt took to its first answer; `Duration::MAX` for an
41    /// address never used (RFC 8305 section 4: lower RTTs first, used addresses before unused
42    /// ones).
43    rtt: Duration,
44}
45
46impl Default for AddressRank {
47    fn default() -> Self {
48        Self {
49            failed: false,
50            rtt: Duration::MAX,
51        }
52    }
53}
54
55/// As [`sort_addresses`], each family ordered first by `rank` (lower first; the given order
56/// among equal ranks).
57pub fn sort_addresses_ranked(
58    addresses: &[SocketAddr],
59    prefer_ipv6: bool,
60    rank: impl Fn(&SocketAddr) -> AddressRank,
61) -> Vec<SocketAddr> {
62    let mut ranked: Vec<SocketAddr> = vec![];
63    for a in addresses {
64        if !ranked.contains(a) {
65            ranked.push(*a);
66        }
67    }
68    ranked.sort_by_key(|a| rank(a));
69    let mut first: VecDeque<SocketAddr> = VecDeque::new();
70    let mut second: VecDeque<SocketAddr> = VecDeque::new();
71    for a in &ranked {
72        if first.contains(a) || second.contains(a) {
73            continue;
74        }
75        if a.is_ipv6() == prefer_ipv6 {
76            first.push_back(*a);
77        } else {
78            second.push_back(*a);
79        }
80    }
81    let mut out = Vec::with_capacity(first.len() + second.len());
82    loop {
83        match (first.pop_front(), second.pop_front()) {
84            (None, None) => break,
85            (a, b) => {
86                out.extend(a);
87                out.extend(b);
88            }
89        }
90    }
91    out
92}
93
94/// What attempts on a server's addresses came to, for the order of later attempts (RFC 8305
95/// section 4): "If the client is stateful and has a history of expected round-trip times
96/// (RTTs) for the routes to access each address, it SHOULD add a Destination Address Selection
97/// rule between rules 8 and 9 that prefers addresses with lower RTTs. If the client keeps
98/// track of which addresses it used in the past, it SHOULD add another Destination Address
99/// Selection rule between the RTT rule and rule 9, which prefers used addresses over unused
100/// ones." An address whose last attempt failed goes last (RFC 6724 rule 1).
101///
102/// "This historical data MUST NOT be used across different network interfaces and SHOULD be
103/// flushed whenever a device changes the network to which it is attached." Every outcome is
104/// kept under the local address it was had from (the interface), and read back only for that
105/// local address; [`interface`](Self::interface) flushes the history when a local address not
106/// seen before appears once any is known.
107#[derive(Debug, Clone, Default)]
108pub struct AddressHistory {
109    entries: HashMap<(IpAddr, SocketAddr), AddressRank>,
110    interfaces: HashSet<IpAddr>,
111}
112
113impl AddressHistory {
114    /// An attempt from `local` to `remote` was answered, `rtt` after it started.
115    pub fn succeeded(&mut self, local: IpAddr, remote: SocketAddr, rtt: Duration) {
116        self.entries.insert(
117            (local, remote),
118            AddressRank {
119                failed: false,
120                rtt: rtt.min(Duration::MAX - Duration::from_nanos(1)),
121            },
122        );
123    }
124
125    /// An attempt from `local` to `remote` failed (went unanswered, or its connection or
126    /// handshake failed). What the address took when it last answered is kept.
127    pub fn failed(&mut self, local: IpAddr, remote: SocketAddr) {
128        self.entries.entry((local, remote)).or_default().failed = true;
129    }
130
131    /// The rank of `remote` for attempts from `local` (nothing known: the default).
132    pub fn rank(&self, local: IpAddr, remote: SocketAddr) -> AddressRank {
133        self.entries
134            .get(&(local, remote))
135            .copied()
136            .unwrap_or_default()
137    }
138
139    /// A local address of a host interface the application gave: the first ones are noted;
140    /// one not seen before once any is known means the device's network changed, and the
141    /// history is flushed (RFC 8305 section 4).
142    pub fn interface(&mut self, local: IpAddr) {
143        if self.interfaces.contains(&local) {
144            return;
145        }
146        if !self.interfaces.is_empty() {
147            self.entries.clear();
148        }
149        self.interfaces.insert(local);
150    }
151
152    /// Whether nothing is known.
153    pub fn is_empty(&self) -> bool {
154        self.entries.is_empty()
155    }
156}
157
158/// One Happy Eyeballs race over sorted addresses: [`next_attempt`](Self::next_attempt) says
159/// which address to try when, a failure moves to the next at once, the first success ends it
160/// (the attempts still running are to be cancelled, the rest ignored).
161#[derive(Debug, Clone)]
162pub struct HappyEyeballs {
163    remaining: VecDeque<SocketAddr>,
164    delay: Duration,
165    last_start: Option<Instant>,
166    running: usize,
167    done: bool,
168    /// Families still to answer (IPv6, IPv4); none for a race made from a complete list.
169    awaiting: (bool, bool),
170    /// Every address ever given, so a late answer adds only new ones.
171    known: Vec<SocketAddr>,
172    /// The race does not start before this (the Resolution Delay of an IPv4 answer).
173    hold_until: Option<Instant>,
174    /// Whether the last address tried was IPv6.
175    last_ipv6: Option<bool>,
176    /// The ranks of the addresses that arrived by [`Self::answer_ranked`].
177    ranks: Vec<(SocketAddr, AddressRank)>,
178    /// When each address tried was started.
179    started: Vec<(SocketAddr, Instant)>,
180}
181
182impl HappyEyeballs {
183    /// A race over `addresses` (already sorted, [`sort_addresses`]) with the Connection
184    /// Attempt Delay `delay`, held between 10 ms and 2 s (RFC 8305 section 5).
185    pub fn new(addresses: Vec<SocketAddr>, delay: Duration) -> Self {
186        Self {
187            known: addresses.clone(),
188            remaining: addresses.into(),
189            delay: delay.clamp(MIN_CONNECTION_ATTEMPT_DELAY, MAX_CONNECTION_ATTEMPT_DELAY),
190            last_start: None,
191            running: 0,
192            done: false,
193            awaiting: (false, false),
194            hold_until: None,
195            last_ipv6: None,
196            ranks: vec![],
197            started: vec![],
198        }
199    }
200
201    /// A race whose addresses arrive per family ([`Self::answer`]): it is not lost while a
202    /// family is outstanding.
203    pub fn awaiting_answers(delay: Duration) -> Self {
204        Self {
205            awaiting: (true, true),
206            ..Self::new(vec![], delay)
207        }
208    }
209
210    /// The answer of one family at `now` (RFC 8305 section 3): the race starts on the first
211    /// answer, at once for IPv6 and after [`RESOLUTION_DELAY`] for IPv4 while IPv6 is still
212    /// outstanding; an answer that comes once the race has started is sorted into the
213    /// addresses not yet tried, the families still alternating (`prefer_ipv6`: the family
214    /// that goes first before any attempt).
215    pub fn answer(
216        &mut self,
217        now: Instant,
218        ipv6: bool,
219        addresses: &[SocketAddr],
220        prefer_ipv6: bool,
221    ) {
222        self.answer_ranked(now, ipv6, addresses, prefer_ipv6, |_| {
223            AddressRank::default()
224        });
225    }
226
227    /// As [`Self::answer`], each family of the addresses not yet tried ordered by `rank` first
228    /// ([`sort_addresses_ranked`]; the ranks of earlier answers are kept).
229    pub fn answer_ranked(
230        &mut self,
231        now: Instant,
232        ipv6: bool,
233        addresses: &[SocketAddr],
234        prefer_ipv6: bool,
235        rank: impl Fn(&SocketAddr) -> AddressRank,
236    ) {
237        for a in addresses {
238            if !self.ranks.iter().any(|(r, _)| r == a) {
239                self.ranks.push((*a, rank(a)));
240            }
241        }
242        if ipv6 {
243            self.awaiting.0 = false;
244            // The IPv6 answer ends any wait for it.
245            self.hold_until = None;
246        } else {
247            self.awaiting.1 = false;
248            if self.awaiting.0 && self.last_start.is_none() && self.hold_until.is_none() {
249                self.hold_until = Some(now + RESOLUTION_DELAY);
250            }
251        }
252        if self.done {
253            return;
254        }
255        let fresh: Vec<SocketAddr> = addresses
256            .iter()
257            .filter(|a| !self.known.contains(a))
258            .copied()
259            .collect();
260        self.known.extend(&fresh);
261        let mut pending: Vec<SocketAddr> = self.remaining.drain(..).collect();
262        pending.extend(fresh);
263        let first = self.last_ipv6.map_or(prefer_ipv6, |last| !last);
264        let ranks = &self.ranks;
265        self.remaining = sort_addresses_ranked(&pending, first, |a| {
266            ranks
267                .iter()
268                .find(|(r, _)| r == a)
269                .map_or_else(AddressRank::default, |(_, rank)| *rank)
270        })
271        .into();
272    }
273
274    /// Whether an attempt was started.
275    pub fn started(&self) -> bool {
276        self.last_start.is_some()
277    }
278
279    /// When the attempt on `address` was started, if it was.
280    pub fn started_at(&self, address: SocketAddr) -> Option<Instant> {
281        self.started
282            .iter()
283            .rev()
284            .find(|(a, _)| *a == address)
285            .map(|(_, at)| *at)
286    }
287
288    /// Whether a family has yet to answer.
289    pub fn awaiting(&self) -> bool {
290        self.awaiting.0 || self.awaiting.1
291    }
292
293    /// The address to try now, if one is due: the first at once; the next when the delay since
294    /// the previous start has passed, or when nothing is running (the previous failed), but
295    /// never within 10 ms of the previous start.
296    pub fn next_attempt(&mut self, now: Instant) -> Option<SocketAddr> {
297        if self.done || self.hold_until.is_some_and(|until| now < until) {
298            return None;
299        }
300        let due = match self.last_start {
301            None => true,
302            Some(last) => {
303                let since = now.saturating_duration_since(last);
304                since >= self.delay || (self.running == 0 && since >= MIN_CONNECTION_ATTEMPT_DELAY)
305            }
306        };
307        if !due {
308            return None;
309        }
310        let address = self.remaining.pop_front()?;
311        self.last_ipv6 = Some(address.is_ipv6());
312        self.last_start = Some(now);
313        self.started.push((address, now));
314        self.running += 1;
315        Some(address)
316    }
317
318    /// When [`next_attempt`](Self::next_attempt) will next have something, once an attempt
319    /// has started (before that, at once).
320    pub fn poll_timeout(&self) -> Option<Instant> {
321        if self.done || self.remaining.is_empty() {
322            return None;
323        }
324        if let Some(until) = self.hold_until
325            && self.last_start.is_none()
326        {
327            return Some(until);
328        }
329        Some(match self.last_start {
330            // Nothing started: the first attempt is due at once, on the next call.
331            None => return None,
332            Some(last) if self.running == 0 => last + MIN_CONNECTION_ATTEMPT_DELAY,
333            Some(last) => last + self.delay,
334        })
335    }
336
337    /// An attempt failed.
338    pub fn failed(&mut self) {
339        self.running = self.running.saturating_sub(1);
340    }
341
342    /// An attempt connected: the race is over.
343    pub fn succeeded(&mut self) {
344        self.done = true;
345        self.remaining.clear();
346    }
347
348    /// Every address was tried and nothing is running or left: the race is lost.
349    pub fn exhausted(&self) -> bool {
350        !self.done && self.running == 0 && self.remaining.is_empty() && !self.awaiting()
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    fn a(s: &str) -> SocketAddr {
359        s.parse().unwrap()
360    }
361
362    #[test]
363    fn families_interleave_preferred_first_each_in_its_order() {
364        let list = [
365            a("192.0.2.1:3478"),
366            a("192.0.2.2:3478"),
367            a("192.0.2.3:3478"),
368            a("[2001:db8::1]:3478"),
369            a("[2001:db8::2]:3478"),
370            a("192.0.2.1:3478"),
371        ];
372        assert_eq!(
373            sort_addresses(&list, true),
374            vec![
375                a("[2001:db8::1]:3478"),
376                a("192.0.2.1:3478"),
377                a("[2001:db8::2]:3478"),
378                a("192.0.2.2:3478"),
379                a("192.0.2.3:3478"),
380            ]
381        );
382        assert_eq!(sort_addresses(&list, false)[0], a("192.0.2.1:3478"));
383        assert_eq!(sort_addresses(&[], true), vec![]);
384    }
385
386    /// RFC 8305 section 4: within each family, an address that answered goes first (the
387    /// faster first), an unknown one next, one whose last attempt failed last; the families
388    /// still alternate, the preferred one first. History is read back only for the local
389    /// address it was had from, and a new interface flushes it.
390    #[test]
391    fn history_orders_each_family_and_stays_with_its_interface() {
392        let base = a("10.0.0.1:0").ip();
393        let other = a("10.0.1.1:0").ip();
394        let list = [
395            a("192.0.2.1:3478"),
396            a("192.0.2.2:3478"),
397            a("192.0.2.3:3478"),
398            a("192.0.2.4:3478"),
399            a("[2001:db8::1]:3478"),
400            a("[2001:db8::2]:3478"),
401        ];
402        let mut h = AddressHistory::default();
403        h.interface(base);
404        h.interface(other);
405        h.failed(base, a("192.0.2.1:3478"));
406        h.succeeded(base, a("192.0.2.3:3478"), Duration::from_millis(80));
407        h.succeeded(base, a("192.0.2.4:3478"), Duration::from_millis(20));
408        h.succeeded(base, a("[2001:db8::2]:3478"), Duration::from_millis(30));
409        assert_eq!(
410            sort_addresses_ranked(&list, true, |r| h.rank(base, *r)),
411            vec![
412                a("[2001:db8::2]:3478"),
413                a("192.0.2.4:3478"),
414                a("[2001:db8::1]:3478"),
415                a("192.0.2.3:3478"),
416                a("192.0.2.2:3478"),
417                a("192.0.2.1:3478"),
418            ]
419        );
420        // Another interface: nothing of `base`'s history.
421        assert_eq!(
422            sort_addresses_ranked(&list, true, |r| h.rank(other, *r)),
423            sort_addresses(&list, true)
424        );
425        // A failure after a success: last again.
426        h.failed(base, a("192.0.2.4:3478"));
427        assert_eq!(
428            sort_addresses_ranked(&list, false, |r| h.rank(base, *r))[..2],
429            [a("192.0.2.3:3478"), a("[2001:db8::2]:3478")]
430        );
431        // A new interface: the network changed, the history is gone.
432        h.interface(a("10.0.2.1:0").ip());
433        assert!(h.is_empty());
434    }
435
436    /// Answers per family keep the ranks: a late IPv4 answer is ranked into the addresses not
437    /// yet tried, and the start of each attempt is remembered.
438    #[test]
439    fn answers_are_ranked_and_starts_remembered() {
440        let t0 = Instant::now();
441        let mut race = HappyEyeballs::awaiting_answers(CONNECTION_ATTEMPT_DELAY);
442        let bad = a("192.0.2.1:1");
443        let good = a("192.0.2.2:1");
444        let rank = |r: &SocketAddr| {
445            let mut h = AddressHistory::default();
446            h.failed(a("10.0.0.1:0").ip(), bad);
447            h.rank(a("10.0.0.1:0").ip(), *r)
448        };
449        race.answer_ranked(t0, true, &[], true, rank);
450        race.answer_ranked(t0, false, &[bad, good], true, rank);
451        assert_eq!(race.next_attempt(t0), Some(good));
452        assert_eq!(race.started_at(good), Some(t0));
453        assert_eq!(race.started_at(bad), None);
454    }
455
456    #[test]
457    fn attempts_are_staggered_by_the_delay_and_a_failure_moves_on_at_once() {
458        let t0 = Instant::now();
459        let mut race = HappyEyeballs::new(
460            vec![a("[2001:db8::1]:1"), a("192.0.2.1:1"), a("192.0.2.2:1")],
461            CONNECTION_ATTEMPT_DELAY,
462        );
463        assert_eq!(race.next_attempt(t0), Some(a("[2001:db8::1]:1")));
464        assert_eq!(race.next_attempt(t0 + Duration::from_millis(100)), None);
465        assert_eq!(race.poll_timeout(), Some(t0 + CONNECTION_ATTEMPT_DELAY));
466        assert_eq!(
467            race.next_attempt(t0 + CONNECTION_ATTEMPT_DELAY),
468            Some(a("192.0.2.1:1"))
469        );
470        // Both fail: the next starts at once, though not within 10 ms of the last start.
471        race.failed();
472        race.failed();
473        let t1 = t0 + CONNECTION_ATTEMPT_DELAY;
474        assert_eq!(race.next_attempt(t1 + Duration::from_millis(5)), None);
475        assert_eq!(
476            race.next_attempt(t1 + Duration::from_millis(10)),
477            Some(a("192.0.2.2:1"))
478        );
479        race.failed();
480        assert!(race.exhausted());
481    }
482
483    #[test]
484    fn the_first_success_ends_the_race() {
485        let t0 = Instant::now();
486        let mut race = HappyEyeballs::new(
487            vec![a("[2001:db8::1]:1"), a("192.0.2.1:1")],
488            Duration::from_millis(1),
489        );
490        assert!(race.next_attempt(t0).is_some());
491        race.succeeded();
492        assert_eq!(race.next_attempt(t0 + Duration::from_secs(1)), None);
493        assert_eq!(race.poll_timeout(), None);
494        assert!(!race.exhausted());
495    }
496
497    #[test]
498    fn an_ipv6_answer_starts_the_race_at_once_and_a_late_ipv4_answer_joins_it() {
499        let t0 = Instant::now();
500        let mut race = HappyEyeballs::awaiting_answers(CONNECTION_ATTEMPT_DELAY);
501        assert_eq!(
502            race.next_attempt(t0),
503            None,
504            "nothing to try before an answer"
505        );
506        assert!(
507            !race.exhausted(),
508            "not lost while both families are outstanding"
509        );
510        race.answer(
511            t0,
512            true,
513            &[a("[2001:db8::1]:3478"), a("[2001:db8::2]:3478")],
514            true,
515        );
516        assert_eq!(
517            race.next_attempt(t0),
518            Some(a("[2001:db8::1]:3478")),
519            "RFC 8305 section 3: no wait for the A answer"
520        );
521        // The A answer arrives while the race runs: it is interleaved with what is left.
522        race.answer(
523            t0 + Duration::from_millis(5),
524            false,
525            &[a("192.0.2.1:3478")],
526            true,
527        );
528        let t1 = t0 + CONNECTION_ATTEMPT_DELAY;
529        assert_eq!(race.next_attempt(t1), Some(a("192.0.2.1:3478")));
530        let t2 = t1 + CONNECTION_ATTEMPT_DELAY;
531        assert_eq!(race.next_attempt(t2), Some(a("[2001:db8::2]:3478")));
532    }
533
534    #[test]
535    fn an_ipv4_answer_first_waits_the_resolution_delay_for_ipv6() {
536        let t0 = Instant::now();
537        let mut race = HappyEyeballs::awaiting_answers(CONNECTION_ATTEMPT_DELAY);
538        race.answer(t0, false, &[a("192.0.2.1:3478")], true);
539        assert_eq!(race.next_attempt(t0), None, "held for the AAAA answer");
540        assert_eq!(race.poll_timeout(), Some(t0 + RESOLUTION_DELAY));
541        assert_eq!(
542            race.next_attempt(t0 + RESOLUTION_DELAY),
543            Some(a("192.0.2.1:3478")),
544            "the AAAA answer did not come in time: IPv4 goes"
545        );
546
547        // An IPv6 answer within the delay goes first.
548        let mut race = HappyEyeballs::awaiting_answers(CONNECTION_ATTEMPT_DELAY);
549        race.answer(t0, false, &[a("192.0.2.1:3478")], true);
550        let t1 = t0 + Duration::from_millis(20);
551        race.answer(t1, true, &[a("[2001:db8::1]:3478")], true);
552        assert_eq!(race.next_attempt(t1), Some(a("[2001:db8::1]:3478")));
553        // Both families answered and every attempt failed: the race is lost.
554        race.failed();
555        let t2 = t1 + MIN_CONNECTION_ATTEMPT_DELAY;
556        assert_eq!(race.next_attempt(t2), Some(a("192.0.2.1:3478")));
557        race.failed();
558        assert!(race.exhausted());
559    }
560
561    #[test]
562    fn the_delay_is_held_between_ten_milliseconds_and_two_seconds() {
563        let t0 = Instant::now();
564        let mut race = HappyEyeballs::new(vec![a("192.0.2.1:1"), a("192.0.2.2:1")], Duration::ZERO);
565        race.next_attempt(t0);
566        assert_eq!(race.next_attempt(t0 + Duration::from_millis(9)), None);
567        assert!(race.next_attempt(t0 + Duration::from_millis(10)).is_some());
568        let slow = HappyEyeballs::new(vec![a("192.0.2.1:1")], Duration::from_secs(60));
569        assert_eq!(slow.delay, MAX_CONNECTION_ATTEMPT_DELAY);
570    }
571}