Skip to main content

confluent_kafka/common/
cluster.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//! An immutable representation of a subset of the nodes, topics, and partitions in the Kafka cluster.
16
17use std::collections::{HashMap, HashSet};
18use std::fmt;
19use std::hash::{Hash, Hasher};
20use std::net::SocketAddr;
21
22use rand::seq::SliceRandom;
23
24use super::ClusterResource;
25use super::Node;
26use super::PartitionInfo;
27use super::TopicPartition;
28use super::Uuid;
29
30/// An immutable representation of a subset of the nodes, topics, and partitions
31/// in the Kafka cluster.
32#[derive(Clone, Debug)]
33#[doc(alias = "org.apache.kafka.common.Cluster")]
34pub struct Cluster {
35    is_bootstrap_configured: bool,
36    nodes: Vec<Node>,
37    unauthorized_topics: HashSet<String>,
38    invalid_topics: HashSet<String>,
39    internal_topics: HashSet<String>,
40    controller: Option<Node>,
41    partitions_by_topic_partition: HashMap<TopicPartition, PartitionInfo>,
42    partitions_by_topic: HashMap<String, Vec<PartitionInfo>>,
43    available_partitions_by_topic: HashMap<String, Vec<PartitionInfo>>,
44    partitions_by_node: HashMap<i32, Vec<PartitionInfo>>,
45    nodes_by_id: HashMap<i32, Node>,
46    cluster_resource: ClusterResource,
47    topic_ids: HashMap<String, Uuid>,
48    topic_names: HashMap<Uuid, String>,
49}
50
51impl Cluster {
52    /// Create a new cluster with the given id, nodes and partitions.
53    ///
54    /// # Arguments
55    ///
56    /// - `cluster_id` - the cluster id, or `None` if unknown
57    /// - `nodes` - The nodes in the cluster
58    /// - `partitions` - Information about a subset of the topic-partitions this cluster hosts
59    /// - `unauthorized_topics` - the topics the client is not authorized to access
60    /// - `internal_topics` - the internal topics
61    #[doc(alias = "org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set)")]
62    pub fn new(
63        cluster_id: Option<String>,
64        nodes: Vec<Node>,
65        partitions: Vec<PartitionInfo>,
66        unauthorized_topics: HashSet<String>,
67        internal_topics: HashSet<String>,
68    ) -> Self {
69        Self::new_internal(
70            cluster_id,
71            false,
72            nodes,
73            partitions,
74            unauthorized_topics,
75            HashSet::new(),
76            internal_topics,
77            None,
78            HashMap::new(),
79        )
80    }
81
82    /// Create a new cluster with the given id, nodes, partitions and controller.
83    ///
84    /// # Arguments
85    ///
86    /// - `cluster_id` - the cluster id, or `None` if unknown
87    /// - `nodes` - The nodes in the cluster
88    /// - `partitions` - Information about a subset of the topic-partitions this cluster hosts
89    /// - `unauthorized_topics` - the topics the client is not authorized to access
90    /// - `internal_topics` - the internal topics
91    /// - `controller` - the controller node, or `None` if unknown
92    #[doc(alias = "org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set,Node)")]
93    pub fn with_controller(
94        cluster_id: Option<String>,
95        nodes: Vec<Node>,
96        partitions: Vec<PartitionInfo>,
97        unauthorized_topics: HashSet<String>,
98        internal_topics: HashSet<String>,
99        controller: Option<Node>,
100    ) -> Self {
101        Self::new_internal(
102            cluster_id,
103            false,
104            nodes,
105            partitions,
106            unauthorized_topics,
107            HashSet::new(),
108            internal_topics,
109            controller,
110            HashMap::new(),
111        )
112    }
113
114    /// Create a new cluster with the given id, nodes, partitions, invalid topics and controller.
115    ///
116    /// # Arguments
117    ///
118    /// - `cluster_id` - the cluster id, or `None` if unknown
119    /// - `nodes` - The nodes in the cluster
120    /// - `partitions` - Information about a subset of the topic-partitions this cluster hosts
121    /// - `unauthorized_topics` - the topics the client is not authorized to access
122    /// - `invalid_topics` - the topics whose names are invalid
123    /// - `internal_topics` - the internal topics
124    /// - `controller` - the controller node, or `None` if unknown
125    #[doc(alias = "org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set,Set,Node)")]
126    pub fn with_invalid_topics_controller(
127        cluster_id: Option<String>,
128        nodes: Vec<Node>,
129        partitions: Vec<PartitionInfo>,
130        unauthorized_topics: HashSet<String>,
131        invalid_topics: HashSet<String>,
132        internal_topics: HashSet<String>,
133        controller: Option<Node>,
134    ) -> Self {
135        Self::new_internal(
136            cluster_id,
137            false,
138            nodes,
139            partitions,
140            unauthorized_topics,
141            invalid_topics,
142            internal_topics,
143            controller,
144            HashMap::new(),
145        )
146    }
147
148    /// Create a new cluster with the given id, nodes, partitions and topic ids.
149    ///
150    /// # Arguments
151    ///
152    /// - `cluster_id` - the cluster id, or `None` if unknown
153    /// - `nodes` - The nodes in the cluster
154    /// - `partitions` - Information about a subset of the topic-partitions this cluster hosts
155    /// - `unauthorized_topics` - the topics the client is not authorized to access
156    /// - `invalid_topics` - the topics whose names are invalid
157    /// - `internal_topics` - the internal topics
158    /// - `controller` - the controller node, or `None` if unknown
159    /// - `topic_ids` - the topic ids, keyed by topic name
160    #[expect(clippy::too_many_arguments)]
161    #[doc(alias = "org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set,Set,Node,Map)")]
162    pub fn with_invalid_topics_controller_topic_ids(
163        cluster_id: Option<String>,
164        nodes: Vec<Node>,
165        partitions: Vec<PartitionInfo>,
166        unauthorized_topics: HashSet<String>,
167        invalid_topics: HashSet<String>,
168        internal_topics: HashSet<String>,
169        controller: Option<Node>,
170        topic_ids: HashMap<String, Uuid>,
171    ) -> Self {
172        Self::new_internal(
173            cluster_id,
174            false,
175            nodes,
176            partitions,
177            unauthorized_topics,
178            invalid_topics,
179            internal_topics,
180            controller,
181            topic_ids,
182        )
183    }
184
185    #[expect(clippy::too_many_arguments)]
186    fn new_internal(
187        cluster_id: Option<String>,
188        is_bootstrap_configured: bool,
189        nodes: Vec<Node>,
190        partitions: Vec<PartitionInfo>,
191        unauthorized_topics: HashSet<String>,
192        invalid_topics: HashSet<String>,
193        internal_topics: HashSet<String>,
194        controller: Option<Node>,
195        topic_ids: HashMap<String, Uuid>,
196    ) -> Self {
197        let cluster_resource = ClusterResource::new(cluster_id);
198
199        // Make a randomized copy of the nodes for load balancing across brokers
200        let mut nodes = nodes;
201        nodes.shuffle(&mut rand::rng());
202
203        // Index the nodes for quick lookup
204        let mut nodes_by_id = HashMap::with_capacity(nodes.len());
205        let mut partitions_by_node: HashMap<i32, Vec<PartitionInfo>> = HashMap::with_capacity(nodes.len());
206        for node in &nodes {
207            nodes_by_id.insert(node.id(), node.clone());
208            partitions_by_node.insert(node.id(), Vec::new());
209        }
210
211        // Index the partition infos by topic, topic+partition, and node
212        let mut partitions_by_topic_partition = HashMap::with_capacity(partitions.len());
213        let mut partitions_by_topic: HashMap<String, Vec<PartitionInfo>> = HashMap::new();
214        for p in &partitions {
215            let tp = TopicPartition::new(p.topic().to_string(), p.partition());
216            partitions_by_topic_partition.insert(tp, p.clone());
217            partitions_by_topic.entry(p.topic().to_string()).or_default().push(p.clone());
218
219            // The leader may not be known
220            if let Some(leader) = p.leader() {
221                if leader.is_empty() {
222                    continue;
223                }
224                if let Some(parts) = partitions_by_node.get_mut(&leader.id()) {
225                    parts.push(p.clone());
226                }
227            }
228        }
229
230        // Populate available partitions by topic
231        let mut available_partitions_by_topic = HashMap::with_capacity(partitions_by_topic.len());
232        for (topic, topic_partitions) in &partitions_by_topic {
233            let has_unavailable = topic_partitions.iter().any(|p| p.leader().is_none());
234            if has_unavailable {
235                let available: Vec<PartitionInfo> =
236                    topic_partitions.iter().filter(|p| p.leader().is_some()).cloned().collect();
237                available_partitions_by_topic.insert(topic.clone(), available);
238            } else {
239                available_partitions_by_topic.insert(topic.clone(), topic_partitions.clone());
240            }
241        }
242
243        // Build reverse topic_names map
244        let topic_names: HashMap<Uuid, String> = topic_ids.iter().map(|(name, id)| (*id, name.clone())).collect();
245
246        Self {
247            is_bootstrap_configured,
248            nodes,
249            unauthorized_topics,
250            invalid_topics,
251            internal_topics,
252            controller,
253            partitions_by_topic_partition,
254            partitions_by_topic,
255            available_partitions_by_topic,
256            partitions_by_node,
257            nodes_by_id,
258            cluster_resource,
259            topic_ids,
260            topic_names,
261        }
262    }
263
264    /// Create an empty cluster instance with no nodes and no topic-partitions.
265    #[doc(alias = "org.apache.kafka.common.Cluster#empty")]
266    pub fn empty() -> Self {
267        Self::with_invalid_topics_controller_topic_ids(
268            None,
269            Vec::new(),
270            Vec::new(),
271            HashSet::new(),
272            HashSet::new(),
273            HashSet::new(),
274            None,
275            HashMap::new(),
276        )
277    }
278
279    /// Create a "bootstrap" cluster using the given list of host/ports.
280    ///
281    /// # Arguments
282    ///
283    /// - `addresses` - The addresses
284    ///
285    /// # Returns
286    ///
287    /// A cluster for these hosts/ports
288    #[doc(alias = "org.apache.kafka.common.Cluster#bootstrap")]
289    pub fn bootstrap(addresses: &[(String, SocketAddr)]) -> Self {
290        let mut nodes = Vec::with_capacity(addresses.len());
291        let mut node_id: i32 = -1;
292        for (host, address) in addresses {
293            nodes.push(Node::new(node_id, host.clone(), address.port() as i32));
294            node_id -= 1;
295        }
296        Self::new_internal(
297            None,
298            true,
299            nodes,
300            Vec::new(),
301            HashSet::new(),
302            HashSet::new(),
303            HashSet::new(),
304            None,
305            HashMap::new(),
306        )
307    }
308
309    /// Returns a copy of this cluster combined with `partitions`.
310    ///
311    /// # Arguments
312    ///
313    /// - `partitions` - the partitions to add, keyed by topic-partition
314    #[doc(alias = "org.apache.kafka.common.Cluster#withPartitions")]
315    pub fn with_partitions(&self, partitions: HashMap<TopicPartition, PartitionInfo>) -> Self {
316        let mut combined = self.partitions_by_topic_partition.clone();
317        combined.extend(partitions);
318        let all_partitions: Vec<PartitionInfo> = combined.into_values().collect();
319        Self::with_invalid_topics_controller_topic_ids(
320            self.cluster_resource.cluster_id().map(|s| s.to_string()),
321            self.nodes.clone(),
322            all_partitions,
323            self.unauthorized_topics.clone(),
324            self.invalid_topics.clone(),
325            self.internal_topics.clone(),
326            self.controller.clone(),
327            self.topic_ids.clone(),
328        )
329    }
330
331    /// Returns the known set of nodes.
332    #[doc(alias = "org.apache.kafka.common.Cluster#nodes")]
333    pub fn nodes(&self) -> &[Node] {
334        &self.nodes
335    }
336
337    /// Get the node by the node id (or `None` if the node is not online or does not exist).
338    ///
339    /// # Arguments
340    ///
341    /// - `id` - The id of the node
342    ///
343    /// # Returns
344    ///
345    /// The node, or `None` if the node is not online or does not exist
346    #[doc(alias = "org.apache.kafka.common.Cluster#nodeById")]
347    pub fn node_by_id(&self, id: i32) -> Option<&Node> {
348        self.nodes_by_id.get(&id)
349    }
350
351    /// Get the node by node id if the replica for the given partition is online.
352    ///
353    /// # Arguments
354    ///
355    /// - `partition` - The TopicPartition
356    /// - `id` - The node id
357    ///
358    /// # Returns
359    ///
360    /// the node
361    #[doc(alias = "org.apache.kafka.common.Cluster#nodeIfOnline")]
362    pub fn node_if_online(&self, partition: &TopicPartition, id: i32) -> Option<&Node> {
363        let node = self.nodes_by_id.get(&id)?;
364        let info = self.partitions_by_topic_partition.get(partition)?;
365
366        let is_offline = info.offline_replicas().iter().any(|n| n.id() == node.id());
367        let is_replica = info.replicas().iter().any(|n| n.id() == node.id());
368
369        if !is_offline && is_replica { Some(node) } else { None }
370    }
371
372    /// Get the current leader for the given topic-partition.
373    ///
374    /// # Arguments
375    ///
376    /// - `topic_partition` - The topic and partition we want to know the leader for
377    ///
378    /// # Returns
379    ///
380    /// The node that is the leader for this topic-partition, or `None` if there is currently no leader
381    #[doc(alias = "org.apache.kafka.common.Cluster#leaderFor")]
382    pub fn leader_for(&self, topic_partition: &TopicPartition) -> Option<&Node> {
383        self.partitions_by_topic_partition
384            .get(topic_partition)
385            .and_then(|info| info.leader())
386    }
387
388    /// Get the metadata for the specified partition.
389    ///
390    /// # Arguments
391    ///
392    /// - `topic_partition` - The topic and partition to fetch info for
393    ///
394    /// # Returns
395    ///
396    /// The metadata about the given topic and partition, or `None` if none is found
397    #[doc(alias = "org.apache.kafka.common.Cluster#partition")]
398    pub fn partition(&self, topic_partition: &TopicPartition) -> Option<&PartitionInfo> {
399        self.partitions_by_topic_partition.get(topic_partition)
400    }
401
402    /// Get the list of partitions for this topic.
403    ///
404    /// # Arguments
405    ///
406    /// - `topic` - The topic name
407    ///
408    /// # Returns
409    ///
410    /// A list of partitions
411    #[doc(alias = "org.apache.kafka.common.Cluster#partitionsForTopic")]
412    pub fn partitions_for_topic(&self, topic: &str) -> &[PartitionInfo] {
413        self.partitions_by_topic.get(topic).map(|v| v.as_slice()).unwrap_or(&[])
414    }
415
416    /// Get the number of partitions for the given topic.
417    ///
418    /// # Arguments
419    ///
420    /// - `topic` - The topic to get the number of partitions for
421    ///
422    /// # Returns
423    ///
424    /// The number of partitions or `None` if there is no corresponding metadata
425    #[doc(alias = "org.apache.kafka.common.Cluster#partitionCountForTopic")]
426    pub fn partition_count_for_topic(&self, topic: &str) -> Option<usize> {
427        self.partitions_by_topic.get(topic).map(|v| v.len())
428    }
429
430    /// Get the list of available partitions for this topic.
431    ///
432    /// # Arguments
433    ///
434    /// - `topic` - The topic name
435    ///
436    /// # Returns
437    ///
438    /// A list of partitions
439    #[doc(alias = "org.apache.kafka.common.Cluster#availablePartitionsForTopic")]
440    pub fn available_partitions_for_topic(&self, topic: &str) -> &[PartitionInfo] {
441        self.available_partitions_by_topic
442            .get(topic)
443            .map(|v| v.as_slice())
444            .unwrap_or(&[])
445    }
446
447    /// Get the list of partitions whose leader is this node.
448    ///
449    /// # Arguments
450    ///
451    /// - `node_id` - The node id
452    ///
453    /// # Returns
454    ///
455    /// A list of partitions
456    #[doc(alias = "org.apache.kafka.common.Cluster#partitionsForNode")]
457    pub fn partitions_for_node(&self, node_id: i32) -> &[PartitionInfo] {
458        self.partitions_by_node.get(&node_id).map(|v| v.as_slice()).unwrap_or(&[])
459    }
460
461    /// Get all topics.
462    ///
463    /// # Returns
464    ///
465    /// a set of all topics
466    #[doc(alias = "org.apache.kafka.common.Cluster#topics")]
467    pub fn topics(&self) -> impl Iterator<Item = &str> {
468        self.partitions_by_topic.keys().map(|s| s.as_str())
469    }
470
471    /// Returns the topics the client is not authorized to access.
472    #[doc(alias = "org.apache.kafka.common.Cluster#unauthorizedTopics")]
473    pub fn unauthorized_topics(&self) -> &HashSet<String> {
474        &self.unauthorized_topics
475    }
476
477    /// Returns the topics whose names are invalid.
478    #[doc(alias = "org.apache.kafka.common.Cluster#invalidTopics")]
479    pub fn invalid_topics(&self) -> &HashSet<String> {
480        &self.invalid_topics
481    }
482
483    /// Returns the internal topics.
484    #[doc(alias = "org.apache.kafka.common.Cluster#internalTopics")]
485    pub fn internal_topics(&self) -> &HashSet<String> {
486        &self.internal_topics
487    }
488
489    /// Returns whether this is a bootstrap cluster.
490    #[doc(alias = "org.apache.kafka.common.Cluster#isBootstrapConfigured")]
491    pub fn is_bootstrap_configured(&self) -> bool {
492        self.is_bootstrap_configured
493    }
494
495    /// Returns the cluster resource metadata.
496    #[doc(alias = "org.apache.kafka.common.Cluster#clusterResource")]
497    pub fn cluster_resource(&self) -> &ClusterResource {
498        &self.cluster_resource
499    }
500
501    /// Returns the controller node, or `None` if unknown.
502    #[doc(alias = "org.apache.kafka.common.Cluster#controller")]
503    pub fn controller(&self) -> Option<&Node> {
504        self.controller.as_ref()
505    }
506
507    /// Returns the ids of all topics.
508    #[doc(alias = "org.apache.kafka.common.Cluster#topicIds")]
509    pub fn topic_ids(&self) -> impl Iterator<Item = &Uuid> {
510        self.topic_ids.values()
511    }
512
513    /// Returns the topic id for the given topic name, `Uuid::ZERO_UUID` if unknown.
514    ///
515    /// # Arguments
516    ///
517    /// - `topic` - the topic name
518    #[doc(alias = "org.apache.kafka.common.Cluster#topicId")]
519    pub fn topic_id(&self, topic: &str) -> Uuid {
520        self.topic_ids.get(topic).copied().unwrap_or(Uuid::zero())
521    }
522
523    /// Returns the topic name for the given topic id, or `None` if unknown.
524    ///
525    /// # Arguments
526    ///
527    /// - `topic_id` - the topic id
528    #[doc(alias = "org.apache.kafka.common.Cluster#topicName")]
529    pub fn topic_name(&self, topic_id: &Uuid) -> Option<&str> {
530        self.topic_names.get(topic_id).map(|s| s.as_str())
531    }
532}
533
534impl PartialEq for Cluster {
535    fn eq(&self, other: &Self) -> bool {
536        self.is_bootstrap_configured == other.is_bootstrap_configured
537            && self.nodes == other.nodes
538            && self.unauthorized_topics == other.unauthorized_topics
539            && self.invalid_topics == other.invalid_topics
540            && self.internal_topics == other.internal_topics
541            && self.controller == other.controller
542            && self.partitions_by_topic_partition == other.partitions_by_topic_partition
543            && self.cluster_resource == other.cluster_resource
544            && self.topic_ids == other.topic_ids
545    }
546}
547
548impl Eq for Cluster {}
549
550impl Hash for Cluster {
551    fn hash<H: Hasher>(&self, state: &mut H) {
552        self.is_bootstrap_configured.hash(state);
553        // Hash nodes in a order-dependent way (matching Java's List.hashCode)
554        self.nodes.hash(state);
555        // HashSet doesn't implement Hash, so we hash the sorted elements
556        let mut unauthorized: Vec<&String> = self.unauthorized_topics.iter().collect();
557        unauthorized.sort();
558        unauthorized.hash(state);
559        let mut invalid: Vec<&String> = self.invalid_topics.iter().collect();
560        invalid.sort();
561        invalid.hash(state);
562        let mut internal: Vec<&String> = self.internal_topics.iter().collect();
563        internal.sort();
564        internal.hash(state);
565        self.controller.hash(state);
566        // Hash partitions_by_topic_partition sorted by key
567        let mut partitions: Vec<(&TopicPartition, &PartitionInfo)> =
568            self.partitions_by_topic_partition.iter().collect();
569        partitions.sort_by_key(|(k, _)| (k.topic(), k.partition()));
570        for (k, v) in &partitions {
571            k.hash(state);
572            v.hash(state);
573        }
574        self.cluster_resource.hash(state);
575        // Hash topic_ids sorted by key
576        let mut ids: Vec<(&String, &Uuid)> = self.topic_ids.iter().collect();
577        ids.sort_by_key(|(k, _)| k.as_str());
578        for (k, v) in &ids {
579            k.hash(state);
580            v.hash(state);
581        }
582    }
583}
584
585impl fmt::Display for Cluster {
586    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
587        write!(
588            f,
589            "Cluster(id = {:?}, nodes = {:?}, partitions = {:?}, controller = {:?})",
590            self.cluster_resource.cluster_id(),
591            self.nodes,
592            self.partitions_by_topic_partition.values().collect::<Vec<_>>(),
593            self.controller,
594        )
595    }
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    fn make_node(id: i32) -> Node {
603        Node::new(id, format!("host{id}"), 9092)
604    }
605
606    fn make_partition(topic: &str, partition: i32, leader_id: i32) -> PartitionInfo {
607        let leader = make_node(leader_id);
608        let replicas = vec![make_node(leader_id)];
609        let isr = vec![make_node(leader_id)];
610        PartitionInfo::new(topic.to_string(), partition, Some(leader), replicas, isr)
611    }
612
613    #[test]
614    fn test_empty_cluster() {
615        let cluster = Cluster::empty();
616        assert!(cluster.nodes().is_empty());
617        assert_eq!(cluster.topics().count(), 0);
618    }
619
620    #[test]
621    fn test_bootstrap_cluster() {
622        let addrs: Vec<(String, SocketAddr)> = vec![
623            ("broker1".to_string(), "127.0.0.1:9092".parse().unwrap()),
624            ("broker2".to_string(), "127.0.0.1:9093".parse().unwrap()),
625        ];
626        let cluster = Cluster::bootstrap(&addrs);
627        assert!(cluster.is_bootstrap_configured());
628        assert_eq!(cluster.nodes().len(), 2);
629        // Nodes are shuffled so we check by id lookup instead of order
630        assert!(cluster.node_by_id(-1).is_some());
631        assert!(cluster.node_by_id(-2).is_some());
632    }
633
634    #[test]
635    fn test_cluster_with_partitions() {
636        let nodes = vec![make_node(0), make_node(1)];
637        let partitions = vec![make_partition("test", 0, 0), make_partition("test", 1, 1)];
638        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
639            Some("cluster1".to_string()),
640            nodes,
641            partitions,
642            HashSet::new(),
643            HashSet::new(),
644            HashSet::new(),
645            None,
646            HashMap::new(),
647        );
648
649        assert_eq!(cluster.partitions_for_topic("test").len(), 2);
650        assert_eq!(cluster.partition_count_for_topic("test"), Some(2));
651        assert_eq!(cluster.partition_count_for_topic("nonexistent"), None);
652        assert_eq!(cluster.available_partitions_for_topic("test").len(), 2);
653    }
654
655    #[test]
656    fn test_node_by_id() {
657        let nodes = vec![make_node(0), make_node(1)];
658        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
659            None,
660            nodes,
661            Vec::new(),
662            HashSet::new(),
663            HashSet::new(),
664            HashSet::new(),
665            None,
666            HashMap::new(),
667        );
668
669        assert!(cluster.node_by_id(0).is_some());
670        assert!(cluster.node_by_id(1).is_some());
671        assert!(cluster.node_by_id(99).is_none());
672    }
673
674    #[test]
675    fn test_leader_for() {
676        let nodes = vec![make_node(0)];
677        let partitions = vec![make_partition("test", 0, 0)];
678        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
679            None,
680            nodes,
681            partitions,
682            HashSet::new(),
683            HashSet::new(),
684            HashSet::new(),
685            None,
686            HashMap::new(),
687        );
688
689        let tp = TopicPartition::new("test".to_string(), 0);
690        let leader = cluster.leader_for(&tp).unwrap();
691        assert_eq!(leader.id(), 0);
692
693        let tp2 = TopicPartition::new("test".to_string(), 99);
694        assert!(cluster.leader_for(&tp2).is_none());
695    }
696
697    #[test]
698    fn test_topic_ids() {
699        let mut topic_ids = HashMap::new();
700        topic_ids.insert("test".to_string(), Uuid::random_uuid());
701
702        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
703            None,
704            Vec::new(),
705            Vec::new(),
706            HashSet::new(),
707            HashSet::new(),
708            HashSet::new(),
709            None,
710            topic_ids.clone(),
711        );
712
713        let id = topic_ids["test"];
714        assert_eq!(cluster.topic_id("test"), id);
715        assert_eq!(cluster.topic_name(&id), Some("test"));
716        assert_eq!(cluster.topic_id("nonexistent"), Uuid::zero());
717    }
718
719    #[test]
720    fn test_controller() {
721        let controller = make_node(0);
722        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
723            None,
724            vec![make_node(0)],
725            Vec::new(),
726            HashSet::new(),
727            HashSet::new(),
728            HashSet::new(),
729            Some(controller),
730            HashMap::new(),
731        );
732
733        assert_eq!(cluster.controller().unwrap().id(), 0);
734    }
735
736    #[test]
737    fn test_partitions_for_node() {
738        let nodes = vec![make_node(0), make_node(1)];
739        let partitions = vec![
740            make_partition("test", 0, 0),
741            make_partition("test", 1, 0),
742            make_partition("test", 2, 1),
743        ];
744        let cluster = Cluster::with_invalid_topics_controller_topic_ids(
745            None,
746            nodes,
747            partitions,
748            HashSet::new(),
749            HashSet::new(),
750            HashSet::new(),
751            None,
752            HashMap::new(),
753        );
754
755        assert_eq!(cluster.partitions_for_node(0).len(), 2);
756        assert_eq!(cluster.partitions_for_node(1).len(), 1);
757        assert_eq!(cluster.partitions_for_node(99).len(), 0);
758    }
759
760    #[test]
761    #[doc(alias = "org.apache.kafka.common.ClusterTest#testNotEquals")]
762    fn test_not_equals() {
763        let cluster_id1 = "clusterId1";
764        let cluster_id2 = "clusterId2";
765        let node0 = Node::new(0, "host0".to_string(), 100);
766        let node1 = Node::new(1, "host1".to_string(), 100);
767        let partitions1 = vec![PartitionInfo::new(
768            "topic1".to_string(),
769            0,
770            Some(node0.clone()),
771            vec![node0.clone(), node1.clone()],
772            vec![node0.clone()],
773        )];
774        let partitions2 = vec![PartitionInfo::new(
775            "topic2".to_string(),
776            0,
777            Some(node0.clone()),
778            vec![node1.clone(), node0.clone()],
779            vec![node1.clone()],
780        )];
781        let unauthorized1: HashSet<String> = ["topic1".to_string()].into_iter().collect();
782        let unauthorized2: HashSet<String> = ["topic2".to_string()].into_iter().collect();
783        let invalid1: HashSet<String> = ["topic1".to_string()].into_iter().collect();
784        let invalid2: HashSet<String> = ["topic2".to_string()].into_iter().collect();
785        let internal1: HashSet<String> = ["topic3".to_string()].into_iter().collect();
786        let internal2: HashSet<String> = ["topic4".to_string()].into_iter().collect();
787        let controller1 = Node::new(2, "host2".to_string(), 100);
788        let controller2 = Node::new(3, "host3".to_string(), 100);
789        let topic_id1 = Uuid::random_uuid();
790        let topic_id2 = Uuid::random_uuid();
791        let topic_ids1: HashMap<String, Uuid> = [("topic1".to_string(), topic_id1)].into_iter().collect();
792        let topic_ids2: HashMap<String, Uuid> = [("topic2".to_string(), topic_id2)].into_iter().collect();
793
794        let cluster1 = Cluster::with_invalid_topics_controller_topic_ids(
795            Some(cluster_id1.to_string()),
796            vec![node0.clone()],
797            partitions1.clone(),
798            unauthorized1.clone(),
799            invalid1.clone(),
800            internal1.clone(),
801            Some(controller1.clone()),
802            topic_ids1.clone(),
803        );
804        let different_topic_ids = Cluster::with_invalid_topics_controller_topic_ids(
805            Some(cluster_id1.to_string()),
806            vec![node0.clone()],
807            partitions1.clone(),
808            unauthorized1.clone(),
809            invalid1.clone(),
810            internal1.clone(),
811            Some(controller1.clone()),
812            topic_ids2,
813        );
814        let different_controller = Cluster::with_invalid_topics_controller_topic_ids(
815            Some(cluster_id1.to_string()),
816            vec![node0.clone()],
817            partitions1.clone(),
818            unauthorized1.clone(),
819            invalid1.clone(),
820            internal1.clone(),
821            Some(controller2),
822            topic_ids1.clone(),
823        );
824        let different_internal_topics = Cluster::with_invalid_topics_controller_topic_ids(
825            Some(cluster_id1.to_string()),
826            vec![node0.clone()],
827            partitions1.clone(),
828            unauthorized1.clone(),
829            invalid1.clone(),
830            internal2,
831            Some(controller1.clone()),
832            topic_ids1.clone(),
833        );
834        let different_invalid_topics = Cluster::with_invalid_topics_controller_topic_ids(
835            Some(cluster_id1.to_string()),
836            vec![node0.clone()],
837            partitions1.clone(),
838            unauthorized1.clone(),
839            invalid2,
840            internal1.clone(),
841            Some(controller1.clone()),
842            topic_ids1.clone(),
843        );
844        let different_unauthorized_topics = Cluster::with_invalid_topics_controller_topic_ids(
845            Some(cluster_id1.to_string()),
846            vec![node0.clone()],
847            partitions1.clone(),
848            unauthorized2,
849            invalid1.clone(),
850            internal1.clone(),
851            Some(controller1.clone()),
852            topic_ids1.clone(),
853        );
854        let different_partitions = Cluster::with_invalid_topics_controller_topic_ids(
855            Some(cluster_id1.to_string()),
856            vec![node0.clone()],
857            partitions2,
858            unauthorized1.clone(),
859            invalid1.clone(),
860            internal1.clone(),
861            Some(controller1.clone()),
862            topic_ids1.clone(),
863        );
864        let different_nodes = Cluster::with_invalid_topics_controller_topic_ids(
865            Some(cluster_id1.to_string()),
866            vec![node0.clone(), node1],
867            partitions1.clone(),
868            unauthorized1.clone(),
869            invalid1.clone(),
870            internal1.clone(),
871            Some(controller1.clone()),
872            topic_ids1.clone(),
873        );
874        let different_cluster_id = Cluster::with_invalid_topics_controller_topic_ids(
875            Some(cluster_id2.to_string()),
876            vec![node0],
877            partitions1,
878            unauthorized1,
879            invalid1,
880            internal1,
881            Some(controller1),
882            topic_ids1,
883        );
884
885        assert_ne!(cluster1, different_topic_ids);
886        assert_ne!(cluster1, different_controller);
887        assert_ne!(cluster1, different_internal_topics);
888        assert_ne!(cluster1, different_invalid_topics);
889        assert_ne!(cluster1, different_unauthorized_topics);
890        assert_ne!(cluster1, different_partitions);
891        assert_ne!(cluster1, different_nodes);
892        assert_ne!(cluster1, different_cluster_id);
893    }
894
895    #[test]
896    #[doc(alias = "org.apache.kafka.common.ClusterTest#testEquals")]
897    fn test_equals() {
898        let cluster_id1 = "clusterId1";
899        let node1 = Node::new(1, "host0".to_string(), 100);
900        let node1_duplicate = Node::new(1, "host0".to_string(), 100);
901        let partitions1 = vec![PartitionInfo::new(
902            "topic1".to_string(),
903            0,
904            Some(node1.clone()),
905            vec![node1.clone()],
906            vec![node1.clone()],
907        )];
908        let partitions1_duplicate = vec![PartitionInfo::new(
909            "topic1".to_string(),
910            0,
911            Some(node1_duplicate.clone()),
912            vec![node1_duplicate.clone()],
913            vec![node1_duplicate.clone()],
914        )];
915        let unauthorized1: HashSet<String> = ["topic1".to_string()].into_iter().collect();
916        let invalid1: HashSet<String> = ["topic1".to_string()].into_iter().collect();
917        let internal1: HashSet<String> = ["topic3".to_string()].into_iter().collect();
918        let controller1 = Node::new(2, "host0".to_string(), 100);
919        let controller1_duplicate = Node::new(2, "host0".to_string(), 100);
920        let topic_id1 = Uuid::random_uuid();
921        let topic_ids1: HashMap<String, Uuid> = [("topic1".to_string(), topic_id1)].into_iter().collect();
922        let topic_ids1_duplicate: HashMap<String, Uuid> = [("topic1".to_string(), topic_id1)].into_iter().collect();
923
924        let cluster1 = Cluster::with_invalid_topics_controller_topic_ids(
925            Some(cluster_id1.to_string()),
926            vec![node1],
927            partitions1,
928            unauthorized1.clone(),
929            invalid1.clone(),
930            internal1.clone(),
931            Some(controller1),
932            topic_ids1,
933        );
934        let cluster1_duplicate = Cluster::with_invalid_topics_controller_topic_ids(
935            Some(cluster_id1.to_string()),
936            vec![node1_duplicate],
937            partitions1_duplicate,
938            unauthorized1,
939            invalid1,
940            internal1,
941            Some(controller1_duplicate),
942            topic_ids1_duplicate,
943        );
944        assert_eq!(cluster1, cluster1_duplicate);
945    }
946
947    /// The 5-argument constructor (Java `org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set)`) must agree with the
948    /// widest one given empty invalid topics, no controller and no topic ids.
949    #[test]
950    fn test_new_matches_widest_with_defaults() {
951        let nodes = vec![make_node(0), make_node(1)];
952        let partitions = vec![make_partition("test", 0, 0), make_partition("test", 1, 1)];
953        let unauthorized: HashSet<String> = ["forbidden".to_string()].into_iter().collect();
954        let internal: HashSet<String> = ["__consumer_offsets".to_string()].into_iter().collect();
955
956        let cluster = Cluster::new(
957            Some("cluster1".to_string()),
958            nodes.clone(),
959            partitions.clone(),
960            unauthorized.clone(),
961            internal.clone(),
962        );
963
964        assert_eq!(cluster.cluster_resource().cluster_id(), Some("cluster1"));
965        assert_eq!(cluster.nodes().len(), 2);
966        assert_eq!(cluster.partitions_for_topic("test").len(), 2);
967        assert_eq!(cluster.unauthorized_topics(), &unauthorized);
968        assert_eq!(cluster.internal_topics(), &internal);
969        assert!(cluster.invalid_topics().is_empty());
970        assert_eq!(cluster.controller(), None);
971        assert_eq!(cluster.topic_ids().count(), 0);
972    }
973
974    /// The 6-argument constructor (Java `org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set,Node)`) adds only the
975    /// controller.
976    #[test]
977    fn test_new_controller_carries_controller() {
978        let nodes = vec![make_node(0), make_node(1)];
979        let controller = make_node(1);
980
981        let cluster = Cluster::with_controller(
982            Some("cluster1".to_string()),
983            nodes,
984            Vec::new(),
985            HashSet::new(),
986            HashSet::new(),
987            Some(controller.clone()),
988        );
989
990        assert_eq!(cluster.controller(), Some(&controller));
991        assert!(cluster.invalid_topics().is_empty());
992        assert_eq!(cluster.topic_ids().count(), 0);
993    }
994
995    /// The 7-argument constructor (Java `org.apache.kafka.common.Cluster#Cluster(String,Collection,Collection,Set,Set,Set,Node)`) adds invalid topics
996    /// and the controller, but still no topic ids.
997    #[test]
998    fn test_new_invalid_topics_controller_carries_both() {
999        let nodes = vec![make_node(0)];
1000        let controller = make_node(0);
1001        let invalid: HashSet<String> = ["bad topic".to_string()].into_iter().collect();
1002
1003        let cluster = Cluster::with_invalid_topics_controller(
1004            Some("cluster1".to_string()),
1005            nodes,
1006            Vec::new(),
1007            HashSet::new(),
1008            invalid.clone(),
1009            HashSet::new(),
1010            Some(controller.clone()),
1011        );
1012
1013        assert_eq!(cluster.invalid_topics(), &invalid);
1014        assert_eq!(cluster.controller(), Some(&controller));
1015        assert_eq!(cluster.topic_ids().count(), 0);
1016    }
1017}