weirdnet_streaming/
clock.rs1use crate::types::StreamError;
11use futures::{AsyncReadExt, AsyncWriteExt};
12use std::collections::VecDeque;
13use std::sync::Arc;
14use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId};
15
16pub const CLOCK_PROTOCOL: &str = "/weirdnet/audio-clock/1";
18
19pub type ClockFn = Arc<dyn Fn() -> u64 + Send + Sync>;
21
22pub fn monotonic() -> ClockFn {
24 let start = std::time::Instant::now();
25 Arc::new(move || start.elapsed().as_nanos() as u64)
26}
27
28pub 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
39pub 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#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct ClockSample {
64 pub local_ns: u64,
66 pub offset_ns: i64,
68 pub rtt_ns: u64,
70}
71
72pub 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#[derive(Clone, Debug)]
107pub struct DriftFit {
108 samples: VecDeque<ClockSample>,
109 keep: usize,
110}
111
112impl DriftFit {
113 pub fn new(keep: usize) -> DriftFit {
115 DriftFit { samples: VecDeque::new(), keep: keep.max(2) }
116 }
117
118 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 pub fn extend(&mut self, samples: impl IntoIterator<Item = ClockSample>) {
128 for s in samples {
129 self.push(s);
130 }
131 }
132
133 pub fn len(&self) -> usize {
135 self.samples.len()
136 }
137
138 pub fn is_empty(&self) -> bool {
140 self.samples.is_empty()
141 }
142
143 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 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 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 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}