use crate::types::StreamError;
use futures::{AsyncReadExt, AsyncWriteExt};
use std::collections::VecDeque;
use std::sync::Arc;
use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId};
pub const CLOCK_PROTOCOL: &str = "/weirdnet/audio-clock/1";
pub type ClockFn = Arc<dyn Fn() -> u64 + Send + Sync>;
pub fn monotonic() -> ClockFn {
let start = std::time::Instant::now();
Arc::new(move || start.elapsed().as_nanos() as u64)
}
pub struct ClockServer {
task: tokio::task::JoinHandle<()>,
}
impl Drop for ClockServer {
fn drop(&mut self) {
self.task.abort();
}
}
pub fn serve_clock<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, clock: ClockFn) -> Result<ClockServer, StreamError> {
let mut incoming = node.accept_streams(CLOCK_PROTOCOL, Limits::default()).map_err(|e| StreamError::Net(e.to_string()))?;
let task = tokio::spawn(async move {
while let Some(mut s) = incoming.next().await {
let clock = clock.clone();
tokio::spawn(async move {
let mut req = [0u8; 8];
while s.read_exact(&mut req).await.is_ok() {
let mut reply = [0u8; 16];
reply[..8].copy_from_slice(&req);
reply[8..].copy_from_slice(&clock().to_be_bytes());
if s.write_all(&reply).await.is_err() || s.flush().await.is_err() {
break;
}
}
});
}
});
Ok(ClockServer { task })
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClockSample {
pub local_ns: u64,
pub offset_ns: i64,
pub rtt_ns: u64,
}
pub async fn measure<Q: Message, R: Message>(
node: &Node<Q, R>,
peer: PeerId,
addrs: &[Multiaddr],
local: &ClockFn,
probes: usize,
) -> Result<ClockSample, StreamError> {
let net = |e: std::io::Error| StreamError::Net(e.to_string());
let mut s = node.open_stream_async(peer, addrs, CLOCK_PROTOCOL, Limits::default()).await.map_err(|e| StreamError::Net(e.to_string()))?;
let mut best: Option<ClockSample> = None;
for seq in 0..probes.max(1) as u64 {
let t0 = local();
s.write_all(&seq.to_be_bytes()).await.map_err(net)?;
s.flush().await.map_err(net)?;
let mut reply = [0u8; 16];
s.read_exact(&mut reply).await.map_err(net)?;
let t3 = local();
if reply[..8] != seq.to_be_bytes() {
return Err(StreamError::Protocol("a clock reply out of order".into()));
}
let remote = u64::from_be_bytes(reply[8..].try_into().expect("8 bytes"));
let mid = t0 + (t3 - t0) / 2;
let sample = ClockSample { local_ns: mid, offset_ns: remote as i64 - mid as i64, rtt_ns: t3 - t0 };
if best.is_none_or(|b| sample.rtt_ns < b.rtt_ns) {
best = Some(sample);
}
}
let _ = s.close().await;
Ok(best.expect("at least one probe"))
}
#[derive(Clone, Debug)]
pub struct DriftFit {
samples: VecDeque<ClockSample>,
keep: usize,
}
impl DriftFit {
pub fn new(keep: usize) -> DriftFit {
DriftFit { samples: VecDeque::new(), keep: keep.max(2) }
}
pub fn push(&mut self, s: ClockSample) {
self.samples.push_back(s);
while self.samples.len() > self.keep {
self.samples.pop_front();
}
}
pub fn extend(&mut self, samples: impl IntoIterator<Item = ClockSample>) {
for s in samples {
self.push(s);
}
}
pub fn len(&self) -> usize {
self.samples.len()
}
pub fn is_empty(&self) -> bool {
self.samples.is_empty()
}
fn line(&self) -> Option<(f64, f64)> {
let first = self.samples.front()?;
let n = self.samples.len() as f64;
let xs = self.samples.iter().map(|s| (s.local_ns - first.local_ns) as f64);
let ys = self.samples.iter().map(|s| s.offset_ns as f64);
let (mx, my) = (xs.clone().sum::<f64>() / n, ys.clone().sum::<f64>() / n);
let sxx: f64 = xs.clone().map(|x| (x - mx) * (x - mx)).sum();
if sxx <= 0.0 {
return Some((my, 0.0));
}
let sxy: f64 = xs.zip(ys).map(|(x, y)| (x - mx) * (y - my)).sum();
let slope = sxy / sxx;
Some((my - slope * mx, slope))
}
pub fn offset_at(&self, local_ns: u64) -> Option<i64> {
let first = self.samples.front()?.local_ns;
let (a, b) = self.line()?;
Some((a + b * (local_ns as f64 - first as f64)).round() as i64)
}
pub fn drift_ppm(&self) -> Option<f64> {
if self.samples.len() < 2 {
return None;
}
self.line().map(|(_, b)| b * 1e6)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_fit_finds_the_offset_and_the_drift() {
let mut f = DriftFit::new(16);
assert_eq!(f.offset_at(0), None);
f.push(ClockSample { local_ns: 1_000_000_000, offset_ns: 5_000_000_000, rtt_ns: 100_000 });
assert_eq!(f.offset_at(9_000_000_000), Some(5_000_000_000));
assert_eq!(f.drift_ppm(), None);
for i in 1..10u64 {
let noise = if i % 2 == 0 { 20_000 } else { -20_000 };
f.push(ClockSample {
local_ns: 1_000_000_000 + i * 1_000_000_000,
offset_ns: 5_000_000_000 + (i * 200_000) as i64 + noise,
rtt_ns: 100_000,
});
}
assert!((f.drift_ppm().unwrap() - 200.0).abs() < 10.0, "{}", f.drift_ppm().unwrap());
assert!((f.offset_at(21_000_000_000).unwrap() - 5_004_000_000).abs() < 100_000);
}
}