Skip to main content

weirdnet_sync/
hlc.rs

1//! Hybrid logical clock: `(physical_ms, counter, node_id)`.
2use serde::{Deserialize, Serialize};
3use std::cmp::Ordering;
4use std::fmt;
5
6/// A node's id in the log and on the clock (the peer id string).
7#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
8pub struct NodeId(pub String);
9
10impl NodeId {
11    pub fn new(s: impl Into<String>) -> Self {
12        Self(s.into())
13    }
14}
15
16impl fmt::Display for NodeId {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.write_str(&self.0)
19    }
20}
21
22impl From<&str> for NodeId {
23    fn from(s: &str) -> Self {
24        Self(s.to_string())
25    }
26}
27
28/// Hybrid logical clock. `physical_ms` is the caller's Unix-ms (`now_ms` in tests).
29#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
30pub struct Hlc {
31    pub physical_ms: u64,
32    pub counter: u32,
33    pub node_id: NodeId,
34}
35
36impl Hlc {
37    pub fn new(physical_ms: u64, counter: u32, node_id: NodeId) -> Self {
38        Self { physical_ms, counter, node_id }
39    }
40
41    /// Total order: physical, then counter, then node id. Used for LWW of a single field.
42    pub fn cmp_total(&self, other: &Self) -> Ordering {
43        self.physical_ms.cmp(&other.physical_ms).then(self.counter.cmp(&other.counter)).then(self.node_id.cmp(&other.node_id))
44    }
45
46    /// Causal / "strictly later" order: physical, then counter, ignoring node id.
47    /// Two events with the same `(physical_ms, counter)` on different nodes are concurrent.
48    pub fn cmp_causal(&self, other: &Self) -> Ordering {
49        self.physical_ms.cmp(&other.physical_ms).then(self.counter.cmp(&other.counter))
50    }
51
52    pub fn strictly_later_than(&self, other: &Self) -> bool {
53        self.cmp_causal(other) == Ordering::Greater
54    }
55
56    pub fn concurrent_with(&self, other: &Self) -> bool {
57        self.cmp_causal(other) == Ordering::Equal && self.node_id != other.node_id
58    }
59
60    /// A local write at `wall_ms` after `last` (or the first write, if `last` is `None`).
61    pub fn tick(last: Option<&Self>, wall_ms: u64, node_id: NodeId) -> Self {
62        match last {
63            None => Self { physical_ms: wall_ms, counter: 0, node_id },
64            Some(last) if wall_ms > last.physical_ms => Self { physical_ms: wall_ms, counter: 0, node_id },
65            Some(last) => Self { physical_ms: last.physical_ms, counter: last.counter.saturating_add(1), node_id },
66        }
67    }
68
69    /// Advance after seeing `other`, then issuing a local event at `wall_ms`.
70    pub fn receive(last: Option<&Self>, other: &Self, wall_ms: u64, node_id: NodeId) -> Self {
71        let last_phys = last.map(|l| l.physical_ms).unwrap_or(0);
72        let last_ctr = last.map(|l| l.counter).unwrap_or(0);
73        let physical_ms = wall_ms.max(last_phys).max(other.physical_ms);
74        let counter = if physical_ms == last_phys && physical_ms == other.physical_ms {
75            last_ctr.max(other.counter).saturating_add(1)
76        } else if physical_ms == last_phys {
77            last_ctr.saturating_add(1)
78        } else if physical_ms == other.physical_ms {
79            other.counter.saturating_add(1)
80        } else {
81            0
82        };
83        Self { physical_ms, counter, node_id }
84    }
85}
86
87impl PartialOrd for Hlc {
88    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
89        Some(Ord::cmp(self, other))
90    }
91}
92
93impl Ord for Hlc {
94    fn cmp(&self, other: &Self) -> Ordering {
95        self.cmp_total(other)
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    fn n(s: &str) -> NodeId {
104        NodeId::new(s)
105    }
106
107    #[test]
108    fn tick_advances_physical_or_bumps_the_counter() {
109        let a = Hlc::tick(None, 1000, n("a"));
110        assert_eq!(a, Hlc::new(1000, 0, n("a")));
111        let b = Hlc::tick(Some(&a), 2000, n("a"));
112        assert_eq!(b, Hlc::new(2000, 0, n("a")));
113        let c = Hlc::tick(Some(&b), 2000, n("a"));
114        assert_eq!(c, Hlc::new(2000, 1, n("a")));
115        let d = Hlc::tick(Some(&c), 1500, n("a"));
116        assert_eq!(d, Hlc::new(2000, 2, n("a")));
117    }
118
119    #[test]
120    fn receive_tracks_the_other_clock() {
121        let last = Hlc::new(1000, 0, n("a"));
122        let other = Hlc::new(3000, 4, n("b"));
123        let r = Hlc::receive(Some(&last), &other, 2000, n("a"));
124        assert_eq!(r, Hlc::new(3000, 5, n("a")));
125        let same = Hlc::receive(Some(&last), &Hlc::new(1000, 2, n("b")), 1000, n("a"));
126        assert_eq!(same, Hlc::new(1000, 3, n("a")));
127    }
128
129    #[test]
130    fn concurrent_is_same_physical_and_counter_on_different_nodes() {
131        let a = Hlc::new(5, 1, n("a"));
132        let b = Hlc::new(5, 1, n("b"));
133        assert!(a.concurrent_with(&b));
134        assert!(!a.strictly_later_than(&b));
135        assert!(!b.strictly_later_than(&a));
136        let later = Hlc::new(5, 2, n("b"));
137        assert!(later.strictly_later_than(&a));
138        assert!(!later.concurrent_with(&a));
139    }
140
141    #[test]
142    fn total_order_breaks_ties_on_node_id() {
143        let a = Hlc::new(5, 1, n("a"));
144        let b = Hlc::new(5, 1, n("b"));
145        assert!(a < b);
146    }
147}