iroh/net_report/
report.rs

1use std::{
2    collections::BTreeMap,
3    fmt,
4    net::{SocketAddr, SocketAddrV4, SocketAddrV6},
5    time::Duration,
6};
7
8use iroh_base::RelayUrl;
9use serde::{Deserialize, Serialize};
10use tracing::{trace, warn};
11
12use super::{ProbeReport, probes::Probe};
13
14/// A net_report report.
15#[derive(Default, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
16#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
17#[non_exhaustive]
18pub struct Report {
19    /// A QAD IPv4 round trip completed.
20    pub udp_v4: bool,
21    /// A QAD IPv6 round trip completed.
22    pub udp_v6: bool,
23    /// Whether the reported public address differs when probing different servers (on IPv4).
24    pub mapping_varies_by_dest_ipv4: Option<bool>,
25    /// Whether the reported public address differs when probing different servers (on IPv6).
26    pub mapping_varies_by_dest_ipv6: Option<bool>,
27    /// The relay server with the lowest latency, if any.
28    pub preferred_relay: Option<RelayUrl>,
29    /// The measured latency to each relay, keyed by relay URL.
30    pub relay_latency: RelayLatencies,
31    /// The discovered global IPv4 address and port, if any.
32    pub global_v4: Option<SocketAddrV4>,
33    /// The discovered global IPv6 address and port, if any.
34    pub global_v6: Option<SocketAddrV6>,
35    /// CaptivePortal is set when we think there's a captive portal that is
36    /// intercepting HTTP traffic.
37    pub captive_portal: Option<bool>,
38}
39
40impl fmt::Display for Report {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        fmt::Debug::fmt(&self, f)
43    }
44}
45
46impl Report {
47    /// Do we have any indication that UDP is working?
48    #[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
49    pub fn has_udp(&self) -> bool {
50        self.udp_v4 || self.udp_v6
51    }
52
53    /// Whether the reported public address differs when probing different servers.
54    #[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
55    pub fn mapping_varies_by_dest(&self) -> Option<bool> {
56        match (
57            self.mapping_varies_by_dest_ipv4,
58            self.mapping_varies_by_dest_ipv6,
59        ) {
60            (Some(v4), Some(v6)) => Some(v4 || v6),
61            (None, Some(v6)) => Some(v6),
62            (Some(v4), None) => Some(v4),
63            (None, None) => None,
64        }
65    }
66
67    /// Updates a net_report [`Report`] with a new [`ProbeReport`].
68    pub(super) fn update(&mut self, report: &ProbeReport) {
69        match report {
70            ProbeReport::Https(report) => {
71                self.relay_latency
72                    .update_relay(report.relay.clone(), report.latency, Probe::Https);
73            }
74            #[cfg(not(wasm_browser))]
75            ProbeReport::QadIpv4(report) => {
76                self.relay_latency.update_relay(
77                    report.relay.clone(),
78                    report.latency,
79                    Probe::QadIpv4,
80                );
81                let SocketAddr::V4(ipp) = report.addr else {
82                    warn!("received IPv6 address from IPv4 QAD: {}", report.addr);
83                    return;
84                };
85
86                self.udp_v4 = true;
87
88                if let Some(global) = self.global_v4 {
89                    if global == ipp {
90                        if self.mapping_varies_by_dest_ipv4.is_none() {
91                            self.mapping_varies_by_dest_ipv4 = Some(false);
92                        }
93                    } else {
94                        self.mapping_varies_by_dest_ipv4 = Some(true);
95                        warn!("IPv4 address detected by QAD varies by destination");
96                    }
97                } else {
98                    self.global_v4 = Some(ipp);
99                }
100                trace!(?self.global_v4, ?self.mapping_varies_by_dest_ipv4, %ipp, "stored report");
101            }
102            #[cfg(not(wasm_browser))]
103            ProbeReport::QadIpv6(report) => {
104                self.relay_latency.update_relay(
105                    report.relay.clone(),
106                    report.latency,
107                    Probe::QadIpv6,
108                );
109                let SocketAddr::V6(ipp) = report.addr else {
110                    warn!("received IPv4 address from IPv6 QAD: {}", report.addr);
111                    return;
112                };
113
114                self.udp_v6 = true;
115                if let Some(global) = self.global_v6 {
116                    if global == ipp {
117                        if self.mapping_varies_by_dest_ipv6.is_none() {
118                            self.mapping_varies_by_dest_ipv6 = Some(false);
119                        }
120                    } else {
121                        self.mapping_varies_by_dest_ipv6 = Some(true);
122                        warn!("IPv6 address detected by QAD varies by destination");
123                    }
124                } else {
125                    self.global_v6 = Some(ipp);
126                }
127                trace!(?self.global_v6, ?self.mapping_varies_by_dest_ipv6, %ipp, "stored report");
128            }
129        }
130    }
131}
132
133/// Latencies per relay endpoint.
134#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
135#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
136pub struct RelayLatencies {
137    #[cfg(not(wasm_browser))]
138    ipv4: BTreeMap<RelayUrl, Duration>,
139    #[cfg(not(wasm_browser))]
140    ipv6: BTreeMap<RelayUrl, Duration>,
141    https: BTreeMap<RelayUrl, Duration>,
142}
143
144impl RelayLatencies {
145    /// Updates a relay's latency, if it is faster than before.
146    pub(super) fn update_relay(&mut self, url: RelayUrl, latency: Duration, probe: Probe) {
147        let list = match probe {
148            Probe::Https => &mut self.https,
149            #[cfg(not(wasm_browser))]
150            Probe::QadIpv4 => &mut self.ipv4,
151            #[cfg(not(wasm_browser))]
152            Probe::QadIpv6 => &mut self.ipv6,
153        };
154        let old_latency = list.entry(url).or_insert(latency);
155        if latency < *old_latency {
156            *old_latency = latency;
157        }
158    }
159
160    /// Merges another [`RelayLatencies`] into this one.
161    ///
162    /// For each relay the latency is updated using [`RelayLatencies::update_relay`].
163    pub(super) fn merge(&mut self, other: &RelayLatencies) {
164        for (url, latency) in other.https.iter() {
165            self.update_relay(url.clone(), *latency, Probe::Https);
166        }
167        #[cfg(not(wasm_browser))]
168        for (url, latency) in other.ipv4.iter() {
169            self.update_relay(url.clone(), *latency, Probe::QadIpv4);
170        }
171        #[cfg(not(wasm_browser))]
172        for (url, latency) in other.ipv6.iter() {
173            self.update_relay(url.clone(), *latency, Probe::QadIpv6);
174        }
175    }
176
177    /// Returns an iterator over all the relays and their latencies.
178    #[cfg(not(wasm_browser))]
179    #[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
180    pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
181        self.https
182            .iter()
183            .map(|(url, l)| (Probe::Https, url, *l))
184            .chain(self.ipv4.iter().map(|(url, l)| (Probe::QadIpv4, url, *l)))
185            .chain(self.ipv6.iter().map(|(url, l)| (Probe::QadIpv6, url, *l)))
186    }
187
188    /// Returns an iterator over all the relays and their latencies.
189    #[cfg(wasm_browser)]
190    #[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
191    pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
192        self.https.iter().map(|(k, v)| (Probe::Https, k, *v))
193    }
194
195    #[cfg(not(wasm_browser))]
196    pub(super) fn is_empty(&self) -> bool {
197        self.https.is_empty() && self.ipv4.is_empty() && self.ipv6.is_empty()
198    }
199
200    #[cfg(wasm_browser)]
201    pub(super) fn is_empty(&self) -> bool {
202        self.https.is_empty()
203    }
204
205    /// Returns the lowest latency across records.
206    pub(super) fn get(&self, url: &RelayUrl) -> Option<Duration> {
207        let mut list = Vec::with_capacity(3);
208        if let Some(val) = self.https.get(url) {
209            list.push(*val);
210        }
211        #[cfg(not(wasm_browser))]
212        if let Some(val) = self.ipv4.get(url) {
213            list.push(*val);
214        }
215        #[cfg(not(wasm_browser))]
216        if let Some(val) = self.ipv6.get(url) {
217            list.push(*val);
218        }
219        list.into_iter().min()
220    }
221}