Skip to main content

waratah_router/
ring.rs

1//! Consistent hash ring with Murmur3-32 virtual nodes.
2
3use crate::NodeId;
4use crate::hash::murmur3_32;
5
6/// Sorted Murmur3 ring of virtual nodes.
7#[derive(Debug, Clone)]
8pub struct HashRing {
9    /// `(hash, physical node)` entries sorted by hash.
10    entries: Vec<(u32, NodeId)>,
11}
12
13impl HashRing {
14    /// Build a ring from `nodes`, placing `vnodes_per_node` virtual nodes each.
15    ///
16    /// Virtual node `i` of `node` is hashed as `"{node_id}:{i}"`.
17    pub fn new(nodes: impl IntoIterator<Item = NodeId>, vnodes_per_node: u32) -> Self {
18        assert!(vnodes_per_node > 0, "vnodes_per_node must be > 0");
19        let mut entries = Vec::new();
20        for node in nodes {
21            for i in 0..vnodes_per_node {
22                let key = format!("{node}:{i}");
23                entries.push((murmur3_32(key.as_bytes()), node.clone()));
24            }
25        }
26        entries.sort_by_key(|(h, _)| *h);
27        Self { entries }
28    }
29
30    /// Virtual nodes placed for each physical node when this ring was built.
31    pub fn vnodes_per_node(&self) -> u32 {
32        if self.entries.is_empty() {
33            return 0;
34        }
35        let physical = self.physical_nodes().len().max(1);
36        (self.entries.len() / physical) as u32
37    }
38
39    /// Number of virtual node slots on the ring.
40    pub fn len(&self) -> usize {
41        self.entries.len()
42    }
43
44    /// Whether the ring has no nodes.
45    pub fn is_empty(&self) -> bool {
46        self.entries.is_empty()
47    }
48
49    /// Distinct physical nodes, first-seen order.
50    pub fn physical_nodes(&self) -> Vec<NodeId> {
51        let mut seen = std::collections::BTreeSet::new();
52        let mut out = Vec::new();
53        for (_, node) in &self.entries {
54            if seen.insert(node.clone()) {
55                out.push(node.clone());
56            }
57        }
58        out
59    }
60
61    /// Locate the physical node owning `key_hash` (clockwise successor).
62    ///
63    /// Returns `None` if the ring is empty.
64    pub fn locate(&self, key_hash: u32) -> Option<&NodeId> {
65        if self.entries.is_empty() {
66            return None;
67        }
68        let idx = self.entries.partition_point(|(h, _)| *h < key_hash) % self.entries.len();
69        Some(&self.entries[idx].1)
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use std::collections::HashMap;
77
78    #[test]
79    fn locate_is_stable_for_same_key() {
80        let ring = HashRing::new([NodeId::new("a"), NodeId::new("b"), NodeId::new("c")], 16);
81        let h = murmur3_32(b"routing-key");
82        let n1 = ring.locate(h).unwrap().clone();
83        let n2 = ring.locate(h).unwrap().clone();
84        assert_eq!(n1, n2);
85    }
86
87    #[test]
88    fn vnode_count_changes_mapping() {
89        let nodes = [NodeId::new("a"), NodeId::new("b")];
90        let ring_low = HashRing::new(nodes.clone(), 1);
91        let ring_high = HashRing::new(nodes, 64);
92        assert_eq!(ring_low.len(), 2);
93        assert_eq!(ring_high.len(), 128);
94
95        // With more vnodes, keys should still map to a registered node.
96        let sample = murmur3_32(b"sample-key");
97        assert!(ring_high.locate(sample).is_some());
98    }
99
100    #[test]
101    fn keys_distribute_across_nodes() {
102        let ring = HashRing::new(
103            [NodeId::new("n0"), NodeId::new("n1"), NodeId::new("n2")],
104            32,
105        );
106        let mut counts: HashMap<NodeId, usize> = HashMap::new();
107        for i in 0..300u32 {
108            let h = murmur3_32(&i.to_le_bytes());
109            let node = ring.locate(h).unwrap().clone();
110            *counts.entry(node).or_default() += 1;
111        }
112        assert_eq!(counts.len(), 3, "all physical nodes should receive keys");
113        for count in counts.values() {
114            assert!(
115                *count > 20,
116                "distribution should not be degenerate: {counts:?}"
117            );
118        }
119    }
120
121    #[test]
122    fn empty_ring_returns_none() {
123        let ring = HashRing::new(std::iter::empty::<NodeId>(), 8);
124        assert!(ring.is_empty());
125        assert!(ring.locate(0).is_none());
126        assert_eq!(ring.vnodes_per_node(), 0);
127        assert!(ring.physical_nodes().is_empty());
128    }
129
130    #[test]
131    fn physical_nodes_are_unique() {
132        let ring = HashRing::new([NodeId::new("a"), NodeId::new("b")], 16);
133        let mut nodes = ring.physical_nodes();
134        nodes.sort();
135        assert_eq!(nodes, vec![NodeId::new("a"), NodeId::new("b")]);
136        assert_eq!(ring.vnodes_per_node(), 16);
137        assert_eq!(ring.len(), 32);
138    }
139}