iroh/net_report/
probes.rs

1//! The relay probes.
2//!
3//! All the probes try and establish the latency to the relay servers.  Preferably the QAD
4//! probes work and we also learn about our public IP addresses and ports.  But fallback
5//! probes for HTTPS exist as well.
6
7use std::{collections::BTreeSet, fmt, sync::Arc};
8
9use iroh_relay::{RelayConfig, RelayMap};
10use n0_future::time::Duration;
11
12use crate::net_report::Report;
13
14/// The retransmit interval used.
15const DEFAULT_INITIAL_RETRANSMIT: Duration = Duration::from_millis(100);
16
17/// The delay before starting HTTPS probes.
18const HTTPS_OFFSET: Duration = Duration::from_millis(200);
19
20/// The protocol used to time an endpoint's latency.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)]
22#[repr(u8)]
23#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
24#[non_exhaustive]
25pub enum Probe {
26    /// HTTPS
27    Https,
28    /// QUIC Address Discovery Ipv4
29    #[cfg(not(wasm_browser))]
30    QadIpv4,
31    /// QUIC Address Discovery Ipv6
32    #[cfg(not(wasm_browser))]
33    QadIpv6,
34}
35
36/// A probe set is a sequence of similar [`Probe`]s with delays between them.
37///
38/// The probes are to the same Relayer and of the same [`Probe`] but will have different
39/// delays.  The delays are effectively retries, though they do not wait for the previous
40/// probe to be finished.  The first successful probe will cancel all other probes in the
41/// set.
42///
43/// This is a lot of type-safety by convention.  It would be so much nicer to have this
44/// compile-time checked but that introduces a giant mess of generics and traits and
45/// associated exploding types.
46///
47/// A [`ProbeSet`] implements [`IntoIterator`] similar to how [`Vec`] does.
48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
49pub(super) struct ProbeSet {
50    /// The [`Probe`] all the probes in this set have.
51    proto: Probe,
52    /// The data in the set.
53    probes: Vec<(Duration, Arc<RelayConfig>)>,
54}
55
56impl ProbeSet {
57    fn new(proto: Probe) -> Self {
58        Self {
59            probes: Vec::new(),
60            proto,
61        }
62    }
63
64    pub(super) fn proto(&self) -> Probe {
65        self.proto
66    }
67
68    fn push(&mut self, delay: Duration, endpoint: Arc<RelayConfig>) {
69        self.probes.push((delay, endpoint));
70    }
71
72    fn is_empty(&self) -> bool {
73        self.probes.is_empty()
74    }
75
76    pub(super) fn params(&self) -> impl Iterator<Item = &(Duration, Arc<RelayConfig>)> {
77        self.probes.iter()
78    }
79}
80
81/// A probe plan.
82///
83/// A probe plan contains a number of [`ProbeSet`]s containing probes to be executed.
84/// Generally the first probe of of a set which completes aborts the remaining probes of a
85/// set.  Sometimes a failing probe can also abort the remaining probes of a set.
86///
87/// The [`reportgen`] actor will also abort all the remaining [`ProbeSet`]s once it has
88/// sufficient information for a report.
89///
90/// [`reportgen`]: crate::net_report::reportgen
91#[derive(Debug, Default, PartialEq, Eq)]
92pub(super) struct ProbePlan {
93    set: BTreeSet<ProbeSet>,
94}
95
96impl ProbePlan {
97    /// Creates an initial probe plan
98    pub(super) fn initial(relay_map: &RelayMap, protocols: &BTreeSet<Probe>) -> Self {
99        let mut plan = Self::default();
100
101        for relay in relay_map.relays::<Vec<_>>() {
102            let mut https_probes = ProbeSet::new(Probe::Https);
103
104            for attempt in 0u32..3 {
105                let delay = HTTPS_OFFSET + DEFAULT_INITIAL_RETRANSMIT * attempt;
106                https_probes.push(delay, relay.clone());
107            }
108
109            plan.add_if_enabled(protocols, https_probes);
110        }
111        plan
112    }
113
114    /// Creates a follow up probe plan using a previous net_report report in browsers.
115    ///
116    /// This will only schedule HTTPS probes.
117    pub(super) fn with_last_report(
118        relay_map: &RelayMap,
119        last_report: &Report,
120        protocols: &BTreeSet<Probe>,
121    ) -> Self {
122        if last_report.relay_latency.is_empty() {
123            return Self::initial(relay_map, protocols);
124        }
125
126        // TODO: is this good?
127        Self::default()
128    }
129
130    /// Returns an iterator over the [`ProbeSet`]s in this plan.
131    pub(super) fn iter(&self) -> impl Iterator<Item = &ProbeSet> {
132        self.set.iter()
133    }
134
135    /// Adds a [`ProbeSet`] if it contains probes and the protocol indicated in
136    /// the [`ProbeSet] matches a protocol in our set of [`Probe`]s.
137    fn add_if_enabled(&mut self, protocols: &BTreeSet<Probe>, set: ProbeSet) {
138        if !set.is_empty() && protocols.contains(&set.proto) {
139            self.set.insert(set);
140        }
141    }
142}
143
144impl fmt::Display for ProbePlan {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        writeln!(f, "ProbePlan {{")?;
147        for probe_set in self.set.iter() {
148            writeln!(f, r#"    ProbeSet("{}") {{"#, probe_set.proto)?;
149            for (delay, endpoint) in probe_set.probes.iter() {
150                writeln!(f, "        {delay:?} to {endpoint},")?;
151            }
152            writeln!(f, "    }}")?;
153        }
154        writeln!(f, "}}")
155    }
156}
157
158impl FromIterator<ProbeSet> for ProbePlan {
159    fn from_iter<T: IntoIterator<Item = ProbeSet>>(iter: T) -> Self {
160        Self {
161            set: iter.into_iter().collect(),
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use pretty_assertions::assert_eq;
169
170    use super::*;
171    use crate::net_report::test_utils;
172
173    /// Shorthand which declares a new ProbeSet.
174    ///
175    /// `$kind`: The `Probe`.
176    /// `$endpoint`: Expression which will be an `Arc<RelayConfig>`.
177    /// `$delays`: A `Vec` of the delays for this probe.
178    macro_rules! probeset {
179        (proto: Probe::$kind:ident, relay: $endpoint:expr, delays: $delays:expr,) => {
180            ProbeSet {
181                proto: Probe::$kind,
182                probes: $delays.iter().map(|delay| (*delay, $endpoint)).collect(),
183            }
184        };
185    }
186
187    fn default_protocols() -> BTreeSet<Probe> {
188        BTreeSet::from([Probe::QadIpv4, Probe::QadIpv6, Probe::Https])
189    }
190
191    #[tokio::test]
192    async fn test_initial_probeplan() {
193        let (_servers, relay_map) = test_utils::relay_map(2).await;
194        let relay_1 = &relay_map.relays::<Vec<_>>()[0];
195        let relay_2 = &relay_map.relays::<Vec<_>>()[1];
196        let plan = ProbePlan::initial(&relay_map, &default_protocols());
197
198        let expected_plan: ProbePlan = [
199            probeset! {
200                proto: Probe::Https,
201                relay: relay_1.clone(),
202                delays: [
203                    Duration::from_millis(200),
204                    Duration::from_millis(300),
205                    Duration::from_millis(400)
206                ],
207            },
208            probeset! {
209                proto: Probe::Https,
210                relay: relay_2.clone(),
211                delays: [
212                    Duration::from_millis(200),
213                    Duration::from_millis(300),
214                    Duration::from_millis(400)
215                ],
216            },
217        ]
218        .into_iter()
219        .collect();
220
221        println!("expected:");
222        println!("{expected_plan}");
223        println!("actual:");
224        println!("{plan}");
225        // The readable error:
226        assert_eq!(plan.to_string(), expected_plan.to_string());
227        // Just in case there's a bug in the Display impl:
228        assert_eq!(plan, expected_plan);
229    }
230
231    #[tokio::test]
232    async fn test_initial_probeplan_some_protocols() {
233        let (_servers, relay_map) = test_utils::relay_map(2).await;
234        let relay_1 = &relay_map.relays::<Vec<_>>()[0];
235        let relay_2 = &relay_map.relays::<Vec<_>>()[1];
236        let plan = ProbePlan::initial(&relay_map, &BTreeSet::from([Probe::Https]));
237
238        let expected_plan: ProbePlan = [
239            probeset! {
240                proto: Probe::Https,
241                relay: relay_1.clone(),
242                delays: [Duration::from_millis(200),
243                         Duration::from_millis(300),
244                         Duration::from_millis(400)],
245            },
246            probeset! {
247                proto: Probe::Https,
248                relay: relay_2.clone(),
249                delays: [Duration::from_millis(200),
250                         Duration::from_millis(300),
251                         Duration::from_millis(400)],
252            },
253        ]
254        .into_iter()
255        .collect();
256
257        println!("expected:");
258        println!("{expected_plan}");
259        println!("actual:");
260        println!("{plan}");
261        // The readable error:
262        assert_eq!(plan.to_string(), expected_plan.to_string());
263        // Just in case there's a bug in the Display impl:
264        assert_eq!(plan, expected_plan);
265    }
266}