ringlet_hash/cluster_manager.rs
1use std::hash::{BuildHasher, Hash};
2
3use crate::{ConsistentRing, PhysicalRingNode, RingConfig, RingError, TokenRangeMigration};
4
5/// Manages physical node membership through a [`ConsistentRing`].
6///
7/// The ring borrows each physical value and stores its weight once. Callers
8/// must keep values alive while the manager uses them. This type provides
9/// checked membership changes and delegates placement to the ring.
10///
11/// # Example
12///
13/// ```
14/// use xxhash_rust::xxh3::Xxh3Builder;
15/// use ringlet_hash::{ClusterManager, RingConfig};
16///
17/// let mut cluster = ClusterManager::try_new(RingConfig {
18/// virtual_node_base_count: 50,
19/// build_hasher: Xxh3Builder::new().with_seed(0),
20/// })?;
21///
22/// let server_a = String::from("server-a");
23/// let server_b = String::from("server-b");
24/// cluster.add_node(&server_a, "a", 1)?;
25/// cluster.add_node(&server_b, "b", 2)?;
26///
27/// let moves = cluster.calculate_migration_on_remove("a")?;
28/// assert!(!moves.is_empty());
29///
30/// cluster.remove_node("a")?;
31/// assert_eq!(cluster.get_node(&"customer-42"), Some(&server_b));
32///
33/// Ok::<(), ringlet_hash::RingError>(())
34/// ```
35#[derive(Clone)]
36pub struct ClusterManager<'a, T, BH: BuildHasher> {
37 ring: ConsistentRing<'a, T, BH>,
38}
39
40impl<'a, T, BH: BuildHasher> ClusterManager<'a, T, BH> {
41 /// Creates a manager with an empty ring.
42 ///
43 /// Returns [`RingError::EmptyRing`] if the base virtual node count is zero.
44 pub fn try_new(config: RingConfig<BH>) -> Result<Self, RingError> {
45 Ok(Self {
46 ring: ConsistentRing::try_new(config)?,
47 })
48 }
49
50 /// Returns physical nodes and weights in insertion order.
51 pub fn nodes(&self) -> &[PhysicalRingNode<'a, T>] {
52 self.ring.physical_nodes()
53 }
54
55 /// Returns the ring for read-only lookups and token inspection.
56 pub fn ring(&self) -> &ConsistentRing<'a, T, BH> {
57 &self.ring
58 }
59
60 /// Adds a physical node with the given identifier and replica multiplier.
61 ///
62 /// The multiplier is a relative placement weight, not a replica count.
63 /// The caller must choose a weight that reflects the node's capacity.
64 /// Returns [`RingError::NodeAlreadyExists`] for a duplicate identifier or
65 /// [`RingError::ZeroWeight`] for a zero multiplier.
66 pub fn add_node(
67 &mut self,
68 node: &'a T,
69 identifier: &str,
70 replica_multiplier: usize,
71 ) -> Result<(), RingError> {
72 self.ring.add_node(node, identifier, replica_multiplier)?;
73 Ok(())
74 }
75
76 /// Removes a physical node and all its virtual nodes.
77 ///
78 /// Returns [`RingError::NodeNotFound`] for an unknown identifier.
79 pub fn remove_node(&mut self, identifier: &str) -> Result<(), RingError> {
80 if !self.ring.contains_identifier(identifier) {
81 return Err(RingError::NodeNotFound(identifier.to_owned()));
82 }
83
84 self.ring.remove_node(identifier);
85 Ok(())
86 }
87
88 /// Previews migration ranges for adding a node without changing membership.
89 ///
90 /// Returns [`RingError::NodeAlreadyExists`] for a duplicate identifier or
91 /// [`RingError::ZeroWeight`] for a zero multiplier.
92 pub fn calculate_migration_on_add(
93 &self,
94 new_node: &'a T,
95 identifier: &str,
96 replica_multiplier: usize,
97 ) -> Result<Vec<TokenRangeMigration<T>>, RingError>
98 where
99 T: Clone,
100 BH: Clone,
101 {
102 if self.ring.contains_identifier(identifier) {
103 return Err(RingError::NodeAlreadyExists(identifier.to_owned()));
104 }
105
106 self.ring
107 .calculate_migration_on_add(new_node, identifier, replica_multiplier)
108 }
109
110 /// Previews migration ranges for removing a node without changing membership.
111 ///
112 /// Returns [`RingError::NodeNotFound`] for an unknown identifier. Removing
113 /// the last node has no migration destination and returns an empty list.
114 pub fn calculate_migration_on_remove(
115 &self,
116 identifier: &str,
117 ) -> Result<Vec<TokenRangeMigration<T>>, RingError>
118 where
119 T: Clone,
120 BH: Clone,
121 {
122 if !self.ring.contains_identifier(identifier) {
123 return Err(RingError::NodeNotFound(identifier.to_owned()));
124 }
125
126 Ok(self.ring.calculate_migration_on_remove(identifier))
127 }
128
129 /// Returns the primary owner of `key`, or `None` for an empty cluster.
130 pub fn get_node<K: Hash>(&self, key: &K) -> Option<&'a T> {
131 self.ring.get_node(key)
132 }
133
134 /// Returns up to `count` distinct physical owners for `key`.
135 /// The caller must check the returned length and store any desired copies.
136 pub fn get_nodes<K: Hash>(&self, key: &K, count: usize) -> Vec<&'a T> {
137 self.ring.get_nodes(key, count)
138 }
139
140 /// Returns the number of registered physical nodes.
141 pub fn len(&self) -> usize {
142 self.ring.physical_nodes().len()
143 }
144
145 /// Returns whether no physical nodes are registered.
146 pub fn is_empty(&self) -> bool {
147 self.ring.physical_nodes().is_empty()
148 }
149}