Skip to main content

kovlet/
hlc.rs

1//! Hybrid logical clocks (PROTOCOL.md §5).
2//!
3//! A stamp is `wall_ms:counter:node_id`: 13 digits, 5 digits (0–65,535) and
4//! 1–64 characters of `[A-Za-z0-9_-]`. Canonical stamps compare as strings.
5
6use std::cmp::Ordering;
7use std::fmt;
8use std::sync::Mutex;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use crate::error::{Error, Result};
12
13/// The counter's maximum (a 16-bit unsigned integer).
14pub const MAX_COUNTER: u32 = 65_535;
15
16/// One parsed HLC stamp.
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub struct Hlc {
19    pub wall_ms: u64,
20    pub counter: u32,
21    pub node: String,
22}
23
24impl Hlc {
25    /// Parses a stamp, checking the exact format of PROTOCOL.md §5.1.
26    pub fn parse(s: &str) -> Result<Hlc> {
27        let bad = || Error::new("invalid_hlc", format!("not an HLC stamp: {s:?}"));
28        let mut parts = s.splitn(3, ':');
29        let (w, c, n) = match (parts.next(), parts.next(), parts.next()) {
30            (Some(w), Some(c), Some(n)) => (w, c, n),
31            _ => return Err(bad()),
32        };
33        if w.len() != 13 || !w.bytes().all(|b| b.is_ascii_digit()) {
34            return Err(bad());
35        }
36        if c.len() != 5 || !c.bytes().all(|b| b.is_ascii_digit()) {
37            return Err(bad());
38        }
39        if !valid_node(n) {
40            return Err(bad());
41        }
42        let counter: u32 = c.parse().map_err(|_| bad())?;
43        if counter > MAX_COUNTER {
44            return Err(bad());
45        }
46        Ok(Hlc { wall_ms: w.parse().map_err(|_| bad())?, counter, node: n.to_string() })
47    }
48}
49
50impl fmt::Display for Hlc {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        write!(f, "{:013}:{:05}:{}", self.wall_ms, self.counter, self.node)
53    }
54}
55
56impl PartialOrd for Hlc {
57    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
58        Some(self.cmp(other))
59    }
60}
61
62impl Ord for Hlc {
63    fn cmp(&self, other: &Self) -> Ordering {
64        self.wall_ms
65            .cmp(&other.wall_ms)
66            .then(self.counter.cmp(&other.counter))
67            .then_with(|| self.node.as_bytes().cmp(other.node.as_bytes()))
68    }
69}
70
71/// Compares two stamps. Unparseable stamps fall back to string order, which is
72/// the same order for canonical stamps.
73pub fn compare(a: &str, b: &str) -> Ordering {
74    match (Hlc::parse(a), Hlc::parse(b)) {
75        (Ok(x), Ok(y)) => x.cmp(&y),
76        _ => a.cmp(b),
77    }
78}
79
80/// True when `hlc` is newer than `than` (or `than` is absent).
81pub fn newer(hlc: &str, than: Option<&str>) -> bool {
82    match than {
83        None => true,
84        Some(t) => compare(hlc, t) == Ordering::Greater,
85    }
86}
87
88/// A node id is 1–64 characters of `[A-Za-z0-9_-]`.
89pub fn valid_node(n: &str) -> bool {
90    !n.is_empty() && n.len() <= 64 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
91}
92
93/// A thread-safe clock that issues strictly increasing stamps (§5.2).
94pub struct Clock {
95    node: String,
96    /// Remote stamps further ahead of physical time than this are refused
97    /// (`clock_drift`); 0 disables the check. Default 5 minutes, as the server.
98    max_drift_ms: u64,
99    last: Mutex<(u64, u32)>,
100    now: Box<dyn Fn() -> u64 + Send + Sync>,
101}
102
103impl fmt::Debug for Clock {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.debug_struct("Clock").field("node", &self.node).finish()
106    }
107}
108
109/// Milliseconds since the Unix epoch.
110pub fn now_ms() -> u64 {
111    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
112}
113
114impl Clock {
115    pub fn new(node: impl Into<String>) -> Clock {
116        Clock::with_time(node, now_ms)
117    }
118
119    /// A clock with an injected physical time source (tests).
120    pub fn with_time(node: impl Into<String>, now: impl Fn() -> u64 + Send + Sync + 'static) -> Clock {
121        let node = node.into();
122        assert!(valid_node(&node), "invalid HLC node id {node:?}");
123        Clock { node, max_drift_ms: 5 * 60 * 1000, last: Mutex::new((0, 0)), now: Box::new(now) }
124    }
125
126    /// Sets the drift limit for observed stamps (0 disables it).
127    pub fn with_max_drift(mut self, ms: u64) -> Clock {
128        self.max_drift_ms = ms;
129        self
130    }
131
132    pub fn node(&self) -> &str {
133        &self.node
134    }
135
136    /// The next local stamp.
137    pub fn tick(&self) -> String {
138        let pt = (self.now)();
139        let mut last = self.last.lock().unwrap();
140        let (w, c) = *last;
141        let next = if pt > w {
142            (pt, 0)
143        } else if c >= MAX_COUNTER {
144            (w + 1, 0) // borrow a millisecond: the clock never fails
145        } else {
146            (w, c + 1)
147        };
148        *last = next;
149        Hlc { wall_ms: next.0, counter: next.1, node: self.node.clone() }.to_string()
150    }
151
152    /// Merges a received stamp, so the next local stamp orders after it. A
153    /// stamp too far ahead of physical time is refused (`clock_drift`) and
154    /// leaves the clock as it was.
155    pub fn observe(&self, stamp: &str) -> Result<()> {
156        let r = Hlc::parse(stamp)?;
157        let pt = (self.now)();
158        if self.max_drift_ms > 0 && r.wall_ms > pt + self.max_drift_ms {
159            return Err(Error::new(
160                "clock_drift",
161                format!("{stamp} is more than {} ms ahead of this clock", self.max_drift_ms),
162            ));
163        }
164        let mut last = self.last.lock().unwrap();
165        let (lw, lc) = *last;
166        let wall = lw.max(r.wall_ms).max(pt);
167        let counter = if wall == lw && wall == r.wall_ms {
168            lc.max(r.counter) + 1
169        } else if wall == lw {
170            lc + 1
171        } else if wall == r.wall_ms {
172            r.counter + 1
173        } else {
174            0
175        };
176        *last = if counter > MAX_COUNTER { (wall + 1, 0) } else { (wall, counter) };
177        Ok(())
178    }
179
180    /// The latest stamp issued or merged (the high-water mark to persist).
181    pub fn last(&self) -> String {
182        let (w, c) = *self.last.lock().unwrap();
183        Hlc { wall_ms: w, counter: c, node: self.node.clone() }.to_string()
184    }
185
186    /// Restores the high-water mark persisted before a restart.
187    pub fn restore(&self, stamp: &str) {
188        if let Ok(h) = Hlc::parse(stamp) {
189            let mut last = self.last.lock().unwrap();
190            if (h.wall_ms, h.counter) > *last {
191                *last = (h.wall_ms, h.counter);
192            }
193        }
194    }
195}
196
197/// A random node id for a new installation (`rs-` + 12 hex characters).
198pub fn random_node() -> String {
199    let mut b = [0u8; 6];
200    let _ = getrandom::fill(&mut b);
201    format!("rs-{}", hex::encode(b))
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use std::sync::atomic::{AtomicU64, Ordering as AO};
208    use std::sync::Arc;
209
210    #[test]
211    fn format_and_parse() {
212        let h = Hlc::parse("1764314700123:00002:mobile-19c2").unwrap();
213        assert_eq!(h.wall_ms, 1764314700123);
214        assert_eq!(h.counter, 2);
215        assert_eq!(h.to_string(), "1764314700123:00002:mobile-19c2");
216        assert!(Hlc::parse("1764314700123:65536:n").is_err());
217        assert!(Hlc::parse("1764314700123:2:n").is_err());
218        assert!(Hlc::parse("1764314700123:00002:").is_err());
219        assert!(Hlc::parse("1764314700123:00002:a b").is_err());
220    }
221
222    #[test]
223    fn counter_borrows_a_millisecond() {
224        let t = Arc::new(AtomicU64::new(1_000_000_000_000));
225        let t2 = t.clone();
226        let c = Clock::with_time("n", move || t2.load(AO::SeqCst));
227        c.restore("1000000000000:65534:n");
228        assert_eq!(c.tick(), "1000000000000:65535:n");
229        assert_eq!(c.tick(), "1000000000001:00000:n");
230        let _ = t;
231    }
232
233    #[test]
234    fn observe_orders_after_remote() {
235        let c = Clock::with_time("n", || 1_000_000_000_000);
236        c.observe("1000000000500:00007:other").unwrap();
237        let s = c.tick();
238        assert!(newer(&s, Some("1000000000500:00007:other")), "{s}");
239    }
240}