Skip to main content

iroh_live_node/
link.rs

1//! Link identity and measurement: the latest sample of each link, and its monitors.
2//!
3//! A monitor reads its link every [`SAMPLE_INTERVAL`] through a
4//! [`LinkSampler`], which turns the session's statistics into a
5//! [`NetworkSample`].
6
7mod path;
8mod sampler;
9
10use std::{
11    sync::{Arc, Mutex},
12    time::Instant,
13};
14
15use moq_ext_access::LinkKind;
16use moq_ext_adaptive::NetworkSample;
17use tracing::trace;
18
19pub use self::path::{NetworkPath, NetworkPathKind};
20use self::sampler::{LinkSampler, SAMPLE_INTERVAL};
21
22/// The id of one link of a node: a session or a media relay.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
24#[display("link-{_0}")]
25pub struct LinkId(pub(crate) u64);
26
27/// The link serving a subscription, and its latest reading.
28#[derive(Debug, Clone, PartialEq)]
29pub struct ServingLink {
30    /// The session's or relay link's id.
31    pub id: LinkId,
32    /// What kind of link that is.
33    pub kind: LinkKind,
34    /// The link's latest reading.
35    pub sample: NetworkSample,
36}
37
38/// The latest sample of a link, shared with every handle on it.
39#[derive(Debug, Clone, Default)]
40pub(crate) struct LatestSample(Arc<Mutex<NetworkSample>>);
41
42impl LatestSample {
43    /// Returns the latest reading.
44    pub(crate) fn get(&self) -> NetworkSample {
45        *self.0.lock().expect("poisoned")
46    }
47
48    /// Empties the reading, as between sessions, keeping `path_generation`.
49    pub(crate) fn clear(&self, path_generation: u64) {
50        self.set(NetworkSample {
51            path_generation,
52            ..NetworkSample::default()
53        });
54    }
55
56    /// Replaces the reading with `sample`.
57    pub(crate) fn set(&self, sample: NetworkSample) {
58        trace!(
59            path_generation = sample.path_generation,
60            relayed = sample.relayed,
61            rtt_ms = ?sample.rtt.map(|rtt| rtt.as_millis()),
62            min_rtt_ms = ?sample.min_rtt.map(|rtt| rtt.as_millis()),
63            loss = ?sample.loss,
64            throughput_kbps = ?sample.throughput.map(|bps| bps / 1000),
65            send_rate_kbps = ?sample.send_rate.map(|bps| bps / 1000),
66            delivery_kbps = ?sample.delivery.map(|bps| bps / 1000),
67            "link sample",
68        );
69        *self.0.lock().expect("poisoned") = sample;
70    }
71}
72
73/// A sampler shared by the monitors of one link's successive sessions.
74pub(crate) type SharedSampler = Arc<Mutex<LinkSampler>>;
75
76/// Reads a direct session into `latest` until its connection closes.
77///
78/// A sampler shared across the sessions of one link carries the path
79/// generation on from one to the next. The monitor holds the session's
80/// receive-bandwidth handle while it runs, and that handle asks the peer to
81/// send probes.
82pub(crate) async fn monitor_direct(
83    session: moq_net::Session,
84    connection: iroh::endpoint::Connection,
85    latest: LatestSample,
86    sampler: SharedSampler,
87) {
88    let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
89    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
90    let recv = session.recv_bandwidth();
91    loop {
92        interval.tick().await;
93        if connection.close_reason().is_some() {
94            return;
95        }
96        let delivery = recv.as_ref().and_then(|recv| recv.peek());
97        let sample = sampler.lock().expect("poisoned").sample_connection(
98            &session,
99            &connection,
100            delivery,
101            Instant::now(),
102        );
103        if let Some(sample) = sample {
104            latest.set(sample);
105        }
106    }
107}
108
109/// Reads a relay link into `latest` across its reconnects.
110pub(crate) async fn monitor_relay(monitor: moq_tokio::connection::Monitor, latest: LatestSample) {
111    let mut sampler = LinkSampler::default();
112    let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
113    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
114    loop {
115        interval.tick().await;
116        let sample = match monitor.stats() {
117            Some(stats) => {
118                let session = monitor.presence().sessions_started;
119                sampler.sample_session(session, &stats, Instant::now())
120            }
121            // Between sessions nothing is measured.
122            None => NetworkSample {
123                path_generation: sampler.path_generation(),
124                ..NetworkSample::default()
125            },
126        };
127        latest.set(sample);
128    }
129}