Skip to main content

weirdnet_streaming/
clock.rs

1//! How far another node's clock is from this one's, and how fast the gap grows.
2//!
3//! [`serve_clock`] answers on [`CLOCK_PROTOCOL`] with the node's clock. [`measure`] sends a few requests, and from each reply
4//! takes the offset as the remote reading minus the midpoint of the local send and receive times; the sample with the shortest
5//! round trip wins, since its midpoint error is bounded by half that round trip. [`DriftFit`] fits offsets taken over time to a
6//! line, which gives the offset at any moment and the drift between the two clocks in parts per million.
7//!
8//! Clocks are functions returning nanoseconds of a monotonic clock ([`ClockFn`]), so a node can use the clock its audio runs on.
9
10use crate::types::StreamError;
11use futures::{AsyncReadExt, AsyncWriteExt};
12use std::collections::VecDeque;
13use std::sync::Arc;
14use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId};
15
16/// The clock protocol id.
17pub const CLOCK_PROTOCOL: &str = "/weirdnet/audio-clock/1";
18
19/// A monotonic clock in nanoseconds.
20pub type ClockFn = Arc<dyn Fn() -> u64 + Send + Sync>;
21
22/// A clock counting from when it was made, on the process's monotonic clock.
23pub fn monotonic() -> ClockFn {
24    let start = std::time::Instant::now();
25    Arc::new(move || start.elapsed().as_nanos() as u64)
26}
27
28/// Answering clock requests. Dropping it stops.
29pub struct ClockServer {
30    task: tokio::task::JoinHandle<()>,
31}
32
33impl Drop for ClockServer {
34    fn drop(&mut self) {
35        self.task.abort();
36    }
37}
38
39/// Answer clock requests on `node` with `clock`. Needs a tokio runtime context.
40pub fn serve_clock<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, clock: ClockFn) -> Result<ClockServer, StreamError> {
41    let mut incoming = node.accept_streams(CLOCK_PROTOCOL, Limits::default()).map_err(|e| StreamError::Net(e.to_string()))?;
42    let task = tokio::spawn(async move {
43        while let Some(mut s) = incoming.next().await {
44            let clock = clock.clone();
45            tokio::spawn(async move {
46                let mut req = [0u8; 8];
47                while s.read_exact(&mut req).await.is_ok() {
48                    let mut reply = [0u8; 16];
49                    reply[..8].copy_from_slice(&req);
50                    reply[8..].copy_from_slice(&clock().to_be_bytes());
51                    if s.write_all(&reply).await.is_err() || s.flush().await.is_err() {
52                        break;
53                    }
54                }
55            });
56        }
57    });
58    Ok(ClockServer { task })
59}
60
61/// One measurement of another clock against this one.
62#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct ClockSample {
64    /// This clock's reading at the middle of the exchange.
65    pub local_ns: u64,
66    /// The other clock minus this one.
67    pub offset_ns: i64,
68    /// The round trip of the exchange; the offset is within half of it.
69    pub rtt_ns: u64,
70}
71
72/// Measure the clock of `peer` (reached through `addrs` if not connected) with `probes` exchanges and keep the one with the
73/// shortest round trip.
74pub async fn measure<Q: Message, R: Message>(
75    node: &Node<Q, R>,
76    peer: PeerId,
77    addrs: &[Multiaddr],
78    local: &ClockFn,
79    probes: usize,
80) -> Result<ClockSample, StreamError> {
81    let net = |e: std::io::Error| StreamError::Net(e.to_string());
82    let mut s = node.open_stream_async(peer, addrs, CLOCK_PROTOCOL, Limits::default()).await.map_err(|e| StreamError::Net(e.to_string()))?;
83    let mut best: Option<ClockSample> = None;
84    for seq in 0..probes.max(1) as u64 {
85        let t0 = local();
86        s.write_all(&seq.to_be_bytes()).await.map_err(net)?;
87        s.flush().await.map_err(net)?;
88        let mut reply = [0u8; 16];
89        s.read_exact(&mut reply).await.map_err(net)?;
90        let t3 = local();
91        if reply[..8] != seq.to_be_bytes() {
92            return Err(StreamError::Protocol("a clock reply out of order".into()));
93        }
94        let remote = u64::from_be_bytes(reply[8..].try_into().expect("8 bytes"));
95        let mid = t0 + (t3 - t0) / 2;
96        let sample = ClockSample { local_ns: mid, offset_ns: remote as i64 - mid as i64, rtt_ns: t3 - t0 };
97        if best.is_none_or(|b| sample.rtt_ns < b.rtt_ns) {
98            best = Some(sample);
99        }
100    }
101    let _ = s.close().await;
102    Ok(best.expect("at least one probe"))
103}
104
105/// Clock samples over time fitted to a line: the offset at any moment, and the drift.
106#[derive(Clone, Debug)]
107pub struct DriftFit {
108    samples: VecDeque<ClockSample>,
109    keep: usize,
110}
111
112impl DriftFit {
113    /// A fit over the newest `keep` samples.
114    pub fn new(keep: usize) -> DriftFit {
115        DriftFit { samples: VecDeque::new(), keep: keep.max(2) }
116    }
117
118    /// Adds a sample.
119    pub fn push(&mut self, s: ClockSample) {
120        self.samples.push_back(s);
121        while self.samples.len() > self.keep {
122            self.samples.pop_front();
123        }
124    }
125
126    /// Adds samples.
127    pub fn extend(&mut self, samples: impl IntoIterator<Item = ClockSample>) {
128        for s in samples {
129            self.push(s);
130        }
131    }
132
133    /// Samples held.
134    pub fn len(&self) -> usize {
135        self.samples.len()
136    }
137
138    /// Whether there are none.
139    pub fn is_empty(&self) -> bool {
140        self.samples.is_empty()
141    }
142
143    /// (offset at the first sample, slope) by least squares, in ns and ns per ns.
144    fn line(&self) -> Option<(f64, f64)> {
145        let first = self.samples.front()?;
146        let n = self.samples.len() as f64;
147        let xs = self.samples.iter().map(|s| (s.local_ns - first.local_ns) as f64);
148        let ys = self.samples.iter().map(|s| s.offset_ns as f64);
149        let (mx, my) = (xs.clone().sum::<f64>() / n, ys.clone().sum::<f64>() / n);
150        let sxx: f64 = xs.clone().map(|x| (x - mx) * (x - mx)).sum();
151        if sxx <= 0.0 {
152            return Some((my, 0.0));
153        }
154        let sxy: f64 = xs.zip(ys).map(|(x, y)| (x - mx) * (y - my)).sum();
155        let slope = sxy / sxx;
156        Some((my - slope * mx, slope))
157    }
158
159    /// The offset (other minus this) at this clock's reading `local_ns`.
160    pub fn offset_at(&self, local_ns: u64) -> Option<i64> {
161        let first = self.samples.front()?.local_ns;
162        let (a, b) = self.line()?;
163        Some((a + b * (local_ns as f64 - first as f64)).round() as i64)
164    }
165
166    /// How much faster the other clock runs, in parts per million (needs two samples at different times).
167    pub fn drift_ppm(&self) -> Option<f64> {
168        if self.samples.len() < 2 {
169            return None;
170        }
171        self.line().map(|(_, b)| b * 1e6)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn the_fit_finds_the_offset_and_the_drift() {
181        let mut f = DriftFit::new(16);
182        assert_eq!(f.offset_at(0), None);
183        f.push(ClockSample { local_ns: 1_000_000_000, offset_ns: 5_000_000_000, rtt_ns: 100_000 });
184        assert_eq!(f.offset_at(9_000_000_000), Some(5_000_000_000));
185        assert_eq!(f.drift_ppm(), None);
186        // the other clock gains 200 µs a second (200 ppm), with ±20 µs of noise
187        for i in 1..10u64 {
188            let noise = if i % 2 == 0 { 20_000 } else { -20_000 };
189            f.push(ClockSample {
190                local_ns: 1_000_000_000 + i * 1_000_000_000,
191                offset_ns: 5_000_000_000 + (i * 200_000) as i64 + noise,
192                rtt_ns: 100_000,
193            });
194        }
195        assert!((f.drift_ppm().unwrap() - 200.0).abs() < 10.0, "{}", f.drift_ppm().unwrap());
196        assert!((f.offset_at(21_000_000_000).unwrap() - 5_004_000_000).abs() < 100_000);
197    }
198}