Skip to main content

iroh_live_node/link/
path.rs

1//! A summary of one network path of a session, for display.
2
3use std::{fmt, time::Duration};
4
5use iroh::{
6    TransportAddr,
7    endpoint::{PathId, PathStats},
8};
9
10/// One open network path of a [`Session`](crate::Session), as returned by
11/// [`Session::network_paths`](crate::Session::network_paths).
12///
13/// The counters run from the path's start, so rates and loss are the
14/// difference between two readings with the same [`id`](Self::id). A path
15/// that is closed and reopened gets a new id.
16#[derive(Debug, Clone, PartialEq)]
17#[non_exhaustive]
18pub struct NetworkPath {
19    /// The path's id within the connection, stable while the path is open.
20    pub id: PathId,
21    /// The remote address as iroh holds it.
22    pub remote: TransportAddr,
23    /// Whether application data goes over this path.
24    pub selected: bool,
25    /// The round trip time estimate.
26    pub rtt: Duration,
27    /// The UDP payload bytes sent on the path, including path MTU probes
28    /// and acknowledgement-only packets.
29    pub sent_bytes: u64,
30    /// The UDP payload bytes received on the path.
31    pub received_bytes: u64,
32    /// The QUIC packets sent on the path, without path MTU probes.
33    pub sent_packets: u64,
34    /// The QUIC packets lost on the path, without path MTU probes.
35    pub lost_packets: u64,
36    /// The congestion window, in bytes.
37    pub cwnd: u64,
38    /// The congestion controller's bandwidth estimate in bits per second,
39    /// if it makes one.
40    pub bandwidth: Option<u64>,
41}
42
43impl NetworkPath {
44    /// Builds the summary of the path `id` to `remote` from its statistics.
45    pub(crate) fn new(
46        id: PathId,
47        remote: &TransportAddr,
48        selected: bool,
49        stats: &PathStats,
50    ) -> Self {
51        Self {
52            id,
53            remote: remote.clone(),
54            selected,
55            rtt: stats.rtt,
56            sent_bytes: stats.udp_tx.bytes,
57            received_bytes: stats.udp_rx.bytes,
58            sent_packets: stats.sent_packets.saturating_sub(stats.sent_plpmtud_probes),
59            lost_packets: stats.lost_packets.saturating_sub(stats.lost_plpmtud_probes),
60            cwnd: stats.cwnd,
61            bandwidth: stats.bandwidth_estimate,
62        }
63    }
64
65    /// Returns the kind of address the path goes to.
66    #[must_use]
67    pub fn kind(&self) -> NetworkPathKind {
68        match &self.remote {
69            TransportAddr::Ip(addr) if addr.is_ipv4() => NetworkPathKind::Ipv4,
70            TransportAddr::Ip(_) => NetworkPathKind::Ipv6,
71            TransportAddr::Relay(_) => NetworkPathKind::Relay,
72            _ => NetworkPathKind::Other,
73        }
74    }
75
76    /// Returns the remote address for display: `ip:port`, or the host of an
77    /// iroh relay.
78    ///
79    /// The format may change; use [`remote`](Self::remote) to act on the
80    /// address.
81    #[must_use]
82    pub fn addr(&self) -> impl fmt::Display + '_ {
83        DisplayAddr(&self.remote)
84    }
85}
86
87/// Shows a [`TransportAddr`] as [`NetworkPath::addr`] describes.
88struct DisplayAddr<'a>(&'a TransportAddr);
89
90impl fmt::Display for DisplayAddr<'_> {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        match self.0 {
93            TransportAddr::Ip(addr) => write!(f, "{addr}"),
94            TransportAddr::Relay(url) => match url.host_str() {
95                Some(host) => f.write_str(host.trim_end_matches('.')),
96                None => write!(f, "{url}"),
97            },
98            other => write!(f, "{other:?}"),
99        }
100    }
101}
102
103/// The kind of address a [`NetworkPath`] goes to.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105#[non_exhaustive]
106pub enum NetworkPathKind {
107    /// A direct path to an IPv4 address.
108    Ipv4,
109    /// A direct path to an IPv6 address.
110    Ipv6,
111    /// A path through an iroh relay.
112    Relay,
113    /// A path over a custom transport.
114    Other,
115}
116
117impl fmt::Display for NetworkPathKind {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.write_str(match self {
120            Self::Ipv4 => "IPv4",
121            Self::Ipv6 => "IPv6",
122            Self::Relay => "relay",
123            Self::Other => "other",
124        })
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn stats() -> PathStats {
133        let mut stats = PathStats::default();
134        stats.rtt = Duration::from_millis(30);
135        stats.udp_tx.bytes = 5_000;
136        stats.udp_rx.bytes = 2_000;
137        stats.sent_packets = 12;
138        stats.sent_plpmtud_probes = 2;
139        stats.lost_packets = 3;
140        stats.lost_plpmtud_probes = 1;
141        stats.cwnd = 64_000;
142        stats.bandwidth_estimate = Some(8_000_000);
143        stats
144    }
145
146    #[test]
147    fn the_counters_leave_out_mtu_probes() {
148        let addr = TransportAddr::Ip("192.0.2.1:4433".parse().unwrap());
149        let path = NetworkPath::new(PathId::ZERO, &addr, true, &stats());
150        assert_eq!(path.id, PathId::ZERO);
151        assert_eq!(path.kind(), NetworkPathKind::Ipv4);
152        assert_eq!(path.addr().to_string(), "192.0.2.1:4433");
153        assert!(path.selected);
154        assert_eq!(path.rtt, Duration::from_millis(30));
155        assert_eq!((path.sent_bytes, path.received_bytes), (5_000, 2_000));
156        assert_eq!((path.sent_packets, path.lost_packets), (10, 2));
157        assert_eq!(path.cwnd, 64_000);
158        assert_eq!(path.bandwidth, Some(8_000_000));
159    }
160
161    #[test]
162    fn an_ipv6_path_shows_its_address() {
163        let addr = TransportAddr::Ip("[2001:db8::1]:4433".parse().unwrap());
164        let path = NetworkPath::new(PathId::ZERO, &addr, false, &PathStats::default());
165        assert_eq!(path.kind(), NetworkPathKind::Ipv6);
166        assert_eq!(path.addr().to_string(), "[2001:db8::1]:4433");
167    }
168
169    #[test]
170    fn a_relay_path_shows_the_relay_host() {
171        let url = "https://euc1-1.relay.n0.iroh.link./".parse().unwrap();
172        let addr = TransportAddr::Relay(url);
173        let path = NetworkPath::new(PathId::ZERO, &addr, false, &PathStats::default());
174        assert_eq!(path.kind(), NetworkPathKind::Relay);
175        assert_eq!(path.addr().to_string(), "euc1-1.relay.n0.iroh.link");
176        assert_eq!(path.kind().to_string(), "relay");
177    }
178}