kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! Hybrid logical clocks (PROTOCOL.md §5).
//!
//! A stamp is `wall_ms:counter:node_id`: 13 digits, 5 digits (0–65,535) and
//! 1–64 characters of `[A-Za-z0-9_-]`. Canonical stamps compare as strings.

use std::cmp::Ordering;
use std::fmt;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::error::{Error, Result};

/// The counter's maximum (a 16-bit unsigned integer).
pub const MAX_COUNTER: u32 = 65_535;

/// One parsed HLC stamp.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Hlc {
    pub wall_ms: u64,
    pub counter: u32,
    pub node: String,
}

impl Hlc {
    /// Parses a stamp, checking the exact format of PROTOCOL.md §5.1.
    pub fn parse(s: &str) -> Result<Hlc> {
        let bad = || Error::new("invalid_hlc", format!("not an HLC stamp: {s:?}"));
        let mut parts = s.splitn(3, ':');
        let (w, c, n) = match (parts.next(), parts.next(), parts.next()) {
            (Some(w), Some(c), Some(n)) => (w, c, n),
            _ => return Err(bad()),
        };
        if w.len() != 13 || !w.bytes().all(|b| b.is_ascii_digit()) {
            return Err(bad());
        }
        if c.len() != 5 || !c.bytes().all(|b| b.is_ascii_digit()) {
            return Err(bad());
        }
        if !valid_node(n) {
            return Err(bad());
        }
        let counter: u32 = c.parse().map_err(|_| bad())?;
        if counter > MAX_COUNTER {
            return Err(bad());
        }
        Ok(Hlc { wall_ms: w.parse().map_err(|_| bad())?, counter, node: n.to_string() })
    }
}

impl fmt::Display for Hlc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:013}:{:05}:{}", self.wall_ms, self.counter, self.node)
    }
}

impl PartialOrd for Hlc {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Hlc {
    fn cmp(&self, other: &Self) -> Ordering {
        self.wall_ms
            .cmp(&other.wall_ms)
            .then(self.counter.cmp(&other.counter))
            .then_with(|| self.node.as_bytes().cmp(other.node.as_bytes()))
    }
}

/// Compares two stamps. Unparseable stamps fall back to string order, which is
/// the same order for canonical stamps.
pub fn compare(a: &str, b: &str) -> Ordering {
    match (Hlc::parse(a), Hlc::parse(b)) {
        (Ok(x), Ok(y)) => x.cmp(&y),
        _ => a.cmp(b),
    }
}

/// True when `hlc` is newer than `than` (or `than` is absent).
pub fn newer(hlc: &str, than: Option<&str>) -> bool {
    match than {
        None => true,
        Some(t) => compare(hlc, t) == Ordering::Greater,
    }
}

/// A node id is 1–64 characters of `[A-Za-z0-9_-]`.
pub fn valid_node(n: &str) -> bool {
    !n.is_empty() && n.len() <= 64 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// A thread-safe clock that issues strictly increasing stamps (§5.2).
pub struct Clock {
    node: String,
    /// Remote stamps further ahead of physical time than this are refused
    /// (`clock_drift`); 0 disables the check. Default 5 minutes, as the server.
    max_drift_ms: u64,
    last: Mutex<(u64, u32)>,
    now: Box<dyn Fn() -> u64 + Send + Sync>,
}

impl fmt::Debug for Clock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Clock").field("node", &self.node).finish()
    }
}

/// Milliseconds since the Unix epoch.
pub fn now_ms() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}

impl Clock {
    pub fn new(node: impl Into<String>) -> Clock {
        Clock::with_time(node, now_ms)
    }

    /// A clock with an injected physical time source (tests).
    pub fn with_time(node: impl Into<String>, now: impl Fn() -> u64 + Send + Sync + 'static) -> Clock {
        let node = node.into();
        assert!(valid_node(&node), "invalid HLC node id {node:?}");
        Clock { node, max_drift_ms: 5 * 60 * 1000, last: Mutex::new((0, 0)), now: Box::new(now) }
    }

    /// Sets the drift limit for observed stamps (0 disables it).
    pub fn with_max_drift(mut self, ms: u64) -> Clock {
        self.max_drift_ms = ms;
        self
    }

    pub fn node(&self) -> &str {
        &self.node
    }

    /// The next local stamp.
    pub fn tick(&self) -> String {
        let pt = (self.now)();
        let mut last = self.last.lock().unwrap();
        let (w, c) = *last;
        let next = if pt > w {
            (pt, 0)
        } else if c >= MAX_COUNTER {
            (w + 1, 0) // borrow a millisecond: the clock never fails
        } else {
            (w, c + 1)
        };
        *last = next;
        Hlc { wall_ms: next.0, counter: next.1, node: self.node.clone() }.to_string()
    }

    /// Merges a received stamp, so the next local stamp orders after it. A
    /// stamp too far ahead of physical time is refused (`clock_drift`) and
    /// leaves the clock as it was.
    pub fn observe(&self, stamp: &str) -> Result<()> {
        let r = Hlc::parse(stamp)?;
        let pt = (self.now)();
        if self.max_drift_ms > 0 && r.wall_ms > pt + self.max_drift_ms {
            return Err(Error::new(
                "clock_drift",
                format!("{stamp} is more than {} ms ahead of this clock", self.max_drift_ms),
            ));
        }
        let mut last = self.last.lock().unwrap();
        let (lw, lc) = *last;
        let wall = lw.max(r.wall_ms).max(pt);
        let counter = if wall == lw && wall == r.wall_ms {
            lc.max(r.counter) + 1
        } else if wall == lw {
            lc + 1
        } else if wall == r.wall_ms {
            r.counter + 1
        } else {
            0
        };
        *last = if counter > MAX_COUNTER { (wall + 1, 0) } else { (wall, counter) };
        Ok(())
    }

    /// The latest stamp issued or merged (the high-water mark to persist).
    pub fn last(&self) -> String {
        let (w, c) = *self.last.lock().unwrap();
        Hlc { wall_ms: w, counter: c, node: self.node.clone() }.to_string()
    }

    /// Restores the high-water mark persisted before a restart.
    pub fn restore(&self, stamp: &str) {
        if let Ok(h) = Hlc::parse(stamp) {
            let mut last = self.last.lock().unwrap();
            if (h.wall_ms, h.counter) > *last {
                *last = (h.wall_ms, h.counter);
            }
        }
    }
}

/// A random node id for a new installation (`rs-` + 12 hex characters).
pub fn random_node() -> String {
    let mut b = [0u8; 6];
    let _ = getrandom::fill(&mut b);
    format!("rs-{}", hex::encode(b))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering as AO};
    use std::sync::Arc;

    #[test]
    fn format_and_parse() {
        let h = Hlc::parse("1764314700123:00002:mobile-19c2").unwrap();
        assert_eq!(h.wall_ms, 1764314700123);
        assert_eq!(h.counter, 2);
        assert_eq!(h.to_string(), "1764314700123:00002:mobile-19c2");
        assert!(Hlc::parse("1764314700123:65536:n").is_err());
        assert!(Hlc::parse("1764314700123:2:n").is_err());
        assert!(Hlc::parse("1764314700123:00002:").is_err());
        assert!(Hlc::parse("1764314700123:00002:a b").is_err());
    }

    #[test]
    fn counter_borrows_a_millisecond() {
        let t = Arc::new(AtomicU64::new(1_000_000_000_000));
        let t2 = t.clone();
        let c = Clock::with_time("n", move || t2.load(AO::SeqCst));
        c.restore("1000000000000:65534:n");
        assert_eq!(c.tick(), "1000000000000:65535:n");
        assert_eq!(c.tick(), "1000000000001:00000:n");
        let _ = t;
    }

    #[test]
    fn observe_orders_after_remote() {
        let c = Clock::with_time("n", || 1_000_000_000_000);
        c.observe("1000000000500:00007:other").unwrap();
        let s = c.tick();
        assert!(newer(&s, Some("1000000000500:00007:other")), "{s}");
    }
}