rocketmq_common/common/consistenthash/virtual_node.rs
1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Virtual node implementation for consistent hashing
16//!
17//! Virtual nodes are used to improve the distribution of keys across
18//! physical nodes in a consistent hash ring.
19
20use std::fmt;
21
22use super::Node;
23
24/// Virtual node wrapper for consistent hashing
25///
26/// A virtual node represents one of multiple replicas of a physical node
27/// on the hash ring. By creating multiple virtual nodes for each physical
28/// node, the key distribution becomes more uniform.
29///
30/// # Type Parameters
31/// * `T` - The type of the physical node, must implement `Node` trait
32///
33/// # Example
34/// ```
35/// use rocketmq_common::common::consistenthash::Node;
36/// use rocketmq_common::common::consistenthash::VirtualNode;
37///
38/// struct ServerNode {
39/// address: String,
40/// }
41///
42/// impl Node for ServerNode {
43/// fn get_key(&self) -> &str {
44/// &self.address
45/// }
46/// }
47///
48/// let physical = ServerNode {
49/// address: "192.168.1.1:8080".to_string(),
50/// };
51///
52/// let virtual_node = VirtualNode::new(physical, 0);
53/// assert_eq!(virtual_node.get_key(), "192.168.1.1:8080-0");
54/// assert_eq!(virtual_node.replica_index(), 0);
55/// ```
56#[derive(Debug, Clone)]
57pub struct VirtualNode<T: Node> {
58 /// The physical node this virtual node represents
59 physical_node: T,
60 /// The replica index of this virtual node
61 replica_index: i32,
62 /// Cached key combining physical node key and replica index
63 key: String,
64}
65
66impl<T: Node> VirtualNode<T> {
67 /// Create a new virtual node
68 ///
69 /// # Arguments
70 /// * `physical_node` - The physical node to create a virtual node for
71 /// * `replica_index` - The replica index (typically 0, 1, 2, ...)
72 ///
73 /// # Returns
74 /// A new VirtualNode instance
75 pub fn new(physical_node: T, replica_index: i32) -> Self {
76 let key = format!("{}-{}", physical_node.get_key(), replica_index);
77 Self {
78 physical_node,
79 replica_index,
80 key,
81 }
82 }
83
84 /// Check if this virtual node belongs to the given physical node
85 ///
86 /// # Arguments
87 /// * `physical_node` - The physical node to check against
88 ///
89 /// # Returns
90 /// `true` if this virtual node represents the given physical node
91 pub fn is_virtual_node_of(&self, physical_node: &T) -> bool {
92 self.physical_node.get_key() == physical_node.get_key()
93 }
94
95 /// Get a reference to the physical node
96 ///
97 /// # Returns
98 /// A reference to the underlying physical node
99 pub fn physical_node(&self) -> &T {
100 &self.physical_node
101 }
102
103 /// Get the replica index
104 ///
105 /// # Returns
106 /// The replica index of this virtual node
107 pub fn replica_index(&self) -> i32 {
108 self.replica_index
109 }
110}
111
112impl<T: Node> Node for VirtualNode<T> {
113 /// Returns the virtual node's key, which is the physical node's key
114 /// combined with the replica index
115 ///
116 /// # Returns
117 /// A string combining the physical node key and replica index (e.g., "node1-0")
118 fn get_key(&self) -> &str {
119 &self.key
120 }
121}
122
123impl<T: Node + fmt::Display> fmt::Display for VirtualNode<T> {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 write!(
126 f,
127 "VirtualNode{{physicalNode={}, replicaIndex={}}}",
128 self.physical_node, self.replica_index
129 )
130 }
131}