Skip to main content

confluent_kafka/common/
node.rs

1// Copyright 2025 Confluent Inc.
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//! Information about a Kafka node.
16
17use std::fmt;
18
19/// Information about a Kafka node.
20#[derive(Clone, Debug)]
21#[doc(alias = "org.apache.kafka.common.Node")]
22pub struct Node {
23    id: i32,
24    id_string: String,
25    host: String,
26    port: i32,
27    rack: Option<String>,
28    is_fenced: bool,
29}
30
31/// A sentinel node representing no node.
32static NO_NODE: std::sync::LazyLock<Node> = std::sync::LazyLock::new(|| Node::new(-1, String::new(), -1));
33
34impl Node {
35    /// Creates a new `Node` with no rack and not fenced.
36    ///
37    /// # Arguments
38    ///
39    /// - `id` - the node id
40    /// - `host` - the host name
41    /// - `port` - the port
42    #[doc(alias = "org.apache.kafka.common.Node#Node(int,String,int)")]
43    pub fn new(id: i32, host: String, port: i32) -> Self {
44        Self::with_rack(id, host, port, None)
45    }
46
47    /// Creates a new `Node` with the given rack.
48    ///
49    /// # Arguments
50    ///
51    /// - `id` - the node id
52    /// - `host` - the host name
53    /// - `port` - the port
54    /// - `rack` - the rack, or `None` if unknown
55    #[doc(alias = "org.apache.kafka.common.Node#Node(int,String,int,String)")]
56    pub fn with_rack(id: i32, host: String, port: i32, rack: Option<String>) -> Self {
57        Self::with_rack_is_fenced(id, host, port, rack, false)
58    }
59
60    /// Creates a new `Node` with the given rack and fenced status.
61    ///
62    /// # Arguments
63    ///
64    /// - `id` - the node id
65    /// - `host` - the host name
66    /// - `port` - the port
67    /// - `rack` - the rack, or `None` if unknown
68    /// - `is_fenced` - whether the broker is fenced
69    #[doc(alias = "org.apache.kafka.common.Node#Node(int,String,int,String,boolean)")]
70    pub fn with_rack_is_fenced(id: i32, host: String, port: i32, rack: Option<String>, is_fenced: bool) -> Self {
71        Self::with_rack_is_fenced_id_string(id, host, port, rack, is_fenced, id.to_string())
72    }
73
74    /// Creates a new `Node` whose [`id_string`](Self::id_string) is given
75    /// explicitly instead of being derived from `id`.
76    ///
77    /// Java's `protected` constructor (KAFKA-20246 3/N),
78    /// whose only caller is the consumer's `GroupCoordinatorNode` subclass,
79    /// hence crate-private here.
80    #[doc(alias = "org.apache.kafka.common.Node#Node(int,String,int,String,boolean,String)")]
81    pub(crate) fn with_rack_is_fenced_id_string(
82        id: i32,
83        host: String,
84        port: i32,
85        rack: Option<String>,
86        is_fenced: bool,
87        id_string: String,
88    ) -> Self {
89        Self { id, id_string, host, port, rack, is_fenced }
90    }
91
92    /// Returns a sentinel node representing no node.
93    #[doc(alias = "org.apache.kafka.common.Node#noNode")]
94    pub fn no_node() -> &'static Node {
95        &NO_NODE
96    }
97
98    /// Check whether this node is empty, which may be the case if `no_node()` is used
99    /// as a placeholder in a response payload with an error.
100    ///
101    /// # Returns
102    ///
103    /// true if it is, false otherwise
104    #[doc(alias = "org.apache.kafka.common.Node#isEmpty")]
105    pub fn is_empty(&self) -> bool {
106        self.host.is_empty() || self.port < 0
107    }
108
109    /// Returns the node id of this node.
110    #[doc(alias = "org.apache.kafka.common.Node#id")]
111    pub fn id(&self) -> i32 {
112        self.id
113    }
114
115    /// Returns the string representation of the node id.
116    /// Typically, the integer id is used to serialize over the wire, the string
117    /// representation is used as an identifier with NetworkClient code.
118    #[doc(alias = "org.apache.kafka.common.Node#idString")]
119    pub fn id_string(&self) -> &str {
120        &self.id_string
121    }
122
123    /// Returns the host name for this node.
124    #[doc(alias = "org.apache.kafka.common.Node#host")]
125    pub fn host(&self) -> &str {
126        &self.host
127    }
128
129    /// Returns the port for this node.
130    #[doc(alias = "org.apache.kafka.common.Node#port")]
131    pub fn port(&self) -> i32 {
132        self.port
133    }
134
135    /// Returns true if this node has a defined rack.
136    #[doc(alias = "org.apache.kafka.common.Node#hasRack")]
137    pub fn has_rack(&self) -> bool {
138        self.rack.is_some()
139    }
140
141    /// Returns the rack for this node.
142    #[doc(alias = "org.apache.kafka.common.Node#rack")]
143    pub fn rack(&self) -> Option<&str> {
144        self.rack.as_deref()
145    }
146
147    /// Returns whether this node is fenced.
148    ///
149    /// This applies to broker nodes only. For controller quorum nodes, this field
150    /// is not relevant and is defined to be `false`.
151    #[doc(alias = "org.apache.kafka.common.Node#isFenced")]
152    pub fn is_fenced(&self) -> bool {
153        self.is_fenced
154    }
155}
156
157/// Java's `Node.equals` first requires
158/// `getClass() == obj.getClass()`, so a `GroupCoordinatorNode` never equals a
159/// plain `Node` with the same fields. Rust has no subclass to compare, so
160/// `id_string` stands in for the class: a plain node's is `id.to_string()` and
161/// a group coordinator's is `"+" + id`, so for equal ids the two `id_string`s
162/// are equal exactly when the Java classes are. `Hash` leaves it out, as Java's
163/// `hashCode` leaves the class out; equal values still hash equally.
164impl PartialEq for Node {
165    fn eq(&self, other: &Self) -> bool {
166        self.id_string == other.id_string
167            && self.id == other.id
168            && self.port == other.port
169            && self.host == other.host
170            && self.rack == other.rack
171            && self.is_fenced == other.is_fenced
172    }
173}
174
175impl Eq for Node {}
176
177impl std::hash::Hash for Node {
178    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
179        self.host.hash(state);
180        self.id.hash(state);
181        self.port.hash(state);
182        self.rack.hash(state);
183        self.is_fenced.hash(state);
184    }
185}
186
187impl fmt::Display for Node {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(
190            f,
191            "{}:{} (id: {} rack: {:?} isFenced: {})",
192            self.host, self.port, self.id_string, self.rack, self.is_fenced
193        )
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn test_node_creation() {
203        let node = Node::new(1, "localhost".to_string(), 9092);
204        assert_eq!(node.id(), 1);
205        assert_eq!(node.host(), "localhost");
206        assert_eq!(node.port(), 9092);
207        assert_eq!(node.id_string(), "1");
208        assert!(!node.has_rack());
209        assert!(node.rack().is_none());
210        assert!(!node.is_fenced());
211    }
212
213    #[test]
214    fn test_node_with_rack() {
215        let node = Node::with_rack(1, "localhost".to_string(), 9092, Some("rack1".to_string()));
216        assert!(node.has_rack());
217        assert_eq!(node.rack(), Some("rack1"));
218    }
219
220    #[test]
221    fn test_node_with_fenced() {
222        let node = Node::with_rack_is_fenced(1, "localhost".to_string(), 9092, None, true);
223        assert!(node.is_fenced());
224    }
225
226    #[test]
227    fn test_no_node() {
228        let node = Node::no_node();
229        assert_eq!(node.id(), -1);
230        assert!(node.is_empty());
231    }
232
233    #[test]
234    fn test_node_is_empty() {
235        let empty1 = Node::new(-1, String::new(), -1);
236        assert!(empty1.is_empty());
237
238        let empty2 = Node::new(0, "host".to_string(), -1);
239        assert!(empty2.is_empty());
240
241        let not_empty = Node::new(0, "host".to_string(), 9092);
242        assert!(!not_empty.is_empty());
243    }
244
245    #[test]
246    fn test_node_equality() {
247        let n1 = Node::new(1, "host".to_string(), 9092);
248        let n2 = Node::new(1, "host".to_string(), 9092);
249        let n3 = Node::new(2, "host".to_string(), 9092);
250        assert_eq!(n1, n2);
251        assert_ne!(n1, n3);
252    }
253
254    #[test]
255    fn test_node_hash() {
256        use std::collections::HashSet;
257        let mut set = HashSet::new();
258        set.insert(Node::new(1, "host".to_string(), 9092));
259        set.insert(Node::new(1, "host".to_string(), 9092));
260        assert_eq!(set.len(), 1);
261    }
262
263    /// The protected `idString` constructor (7be741d08b) keeps every other
264    /// field, and an explicit `idString` makes the node differ from a plain one
265    /// with the same fields, as Java's class check does.
266    #[test]
267    fn test_node_with_explicit_id_string() {
268        let node = Node::with_rack_is_fenced_id_string(1, "host".to_string(), 9092, None, false, "+1".to_string());
269        assert_eq!(node.id(), 1);
270        assert_eq!(node.id_string(), "+1");
271        assert_eq!(node.host(), "host");
272        assert_eq!(node.port(), 9092);
273        assert_eq!(node.to_string(), "host:9092 (id: +1 rack: None isFenced: false)");
274        assert_ne!(node, Node::new(1, "host".to_string(), 9092));
275        assert_eq!(
276            node,
277            Node::with_rack_is_fenced_id_string(1, "host".to_string(), 9092, None, false, "+1".to_string())
278        );
279    }
280
281    #[test]
282    fn test_node_display() {
283        let node = Node::with_rack(1, "localhost".to_string(), 9092, Some("rack1".to_string()));
284        let display = node.to_string();
285        assert!(display.contains("localhost:9092"));
286        assert!(display.contains("id: 1"));
287    }
288}