Skip to main content

confluent_kafka/common/
partition_info.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//! Per-partition state in the MetadataResponse.
16
17use std::fmt;
18
19use super::Node;
20
21/// This is used to describe per-partition state in the MetadataResponse.
22#[derive(Clone, Debug)]
23#[doc(alias = "org.apache.kafka.common.PartitionInfo")]
24pub struct PartitionInfo {
25    topic: String,
26    partition: i32,
27    leader: Option<Node>,
28    replicas: Vec<Node>,
29    in_sync_replicas: Vec<Node>,
30    offline_replicas: Vec<Node>,
31}
32
33impl PartitionInfo {
34    /// Creates a new `PartitionInfo` with no offline replicas.
35    ///
36    /// # Arguments
37    ///
38    /// - `topic` - the topic name
39    /// - `partition` - the partition id
40    /// - `leader` - the leader, or `None` if there is no leader
41    /// - `replicas` - all the replicas, the preferred one first
42    /// - `in_sync_replicas` - the in-sync replicas
43    #[doc(alias = "org.apache.kafka.common.PartitionInfo#PartitionInfo")]
44    pub fn new(
45        topic: String,
46        partition: i32,
47        leader: Option<Node>,
48        replicas: Vec<Node>,
49        in_sync_replicas: Vec<Node>,
50    ) -> Self {
51        Self::with_offline_replicas(topic, partition, leader, replicas, in_sync_replicas, vec![])
52    }
53
54    /// Creates a new `PartitionInfo` with offline replicas.
55    ///
56    /// # Arguments
57    ///
58    /// - `topic` - the topic name
59    /// - `partition` - the partition id
60    /// - `leader` - the leader, or `None` if there is no leader
61    /// - `replicas` - all the replicas, the preferred one first
62    /// - `in_sync_replicas` - the in-sync replicas
63    /// - `offline_replicas` - the offline replicas
64    #[doc(alias = "org.apache.kafka.common.PartitionInfo#PartitionInfo")]
65    pub fn with_offline_replicas(
66        topic: String,
67        partition: i32,
68        leader: Option<Node>,
69        replicas: Vec<Node>,
70        in_sync_replicas: Vec<Node>,
71        offline_replicas: Vec<Node>,
72    ) -> Self {
73        Self { topic, partition, leader, replicas, in_sync_replicas, offline_replicas }
74    }
75
76    /// Returns the topic name.
77    #[doc(alias = "org.apache.kafka.common.PartitionInfo#topic")]
78    pub fn topic(&self) -> &str {
79        &self.topic
80    }
81
82    /// Returns the partition id.
83    #[doc(alias = "org.apache.kafka.common.PartitionInfo#partition")]
84    pub fn partition(&self) -> i32 {
85        self.partition
86    }
87
88    /// Returns the node currently acting as a leader for this partition, or `None` if there is no leader.
89    #[doc(alias = "org.apache.kafka.common.PartitionInfo#leader")]
90    pub fn leader(&self) -> Option<&Node> {
91        self.leader.as_ref()
92    }
93
94    /// Returns the complete set of replicas for this partition regardless of whether they are alive or up-to-date. The preferred replica
95    /// is the head of the list.
96    #[doc(alias = "org.apache.kafka.common.PartitionInfo#replicas")]
97    pub fn replicas(&self) -> &[Node] {
98        &self.replicas
99    }
100
101    /// Returns the subset of the replicas that are in sync, that is caught-up to the leader and ready to
102    /// take over as leader if the leader should fail.
103    #[doc(alias = "org.apache.kafka.common.PartitionInfo#inSyncReplicas")]
104    pub fn in_sync_replicas(&self) -> &[Node] {
105        &self.in_sync_replicas
106    }
107
108    /// Returns the subset of the replicas that are offline.
109    #[doc(alias = "org.apache.kafka.common.PartitionInfo#offlineReplicas")]
110    pub fn offline_replicas(&self) -> &[Node] {
111        &self.offline_replicas
112    }
113}
114
115impl PartialEq for PartitionInfo {
116    fn eq(&self, other: &Self) -> bool {
117        self.topic == other.topic
118            && self.partition == other.partition
119            && self.leader == other.leader
120            && self.replicas == other.replicas
121            && self.in_sync_replicas == other.in_sync_replicas
122            && self.offline_replicas == other.offline_replicas
123    }
124}
125
126impl Eq for PartitionInfo {}
127
128impl std::hash::Hash for PartitionInfo {
129    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
130        self.topic.hash(state);
131        self.partition.hash(state);
132        self.leader.hash(state);
133        self.replicas.hash(state);
134        self.in_sync_replicas.hash(state);
135        self.offline_replicas.hash(state);
136    }
137}
138
139/// Format node ids from a slice for display.
140#[doc(alias = "org.apache.kafka.common.PartitionInfo#formatNodeIds")]
141fn format_node_ids(nodes: &[Node]) -> String {
142    let mut b = String::from("[");
143    for (i, node) in nodes.iter().enumerate() {
144        b.push_str(node.id_string());
145        if i < nodes.len() - 1 {
146            b.push(',');
147        }
148    }
149    b.push(']');
150    b
151}
152
153impl fmt::Display for PartitionInfo {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        let leader_str = match &self.leader {
156            Some(l) => l.id_string().to_string(),
157            None => "none".to_string(),
158        };
159        write!(
160            f,
161            "Partition(topic = {}, partition = {}, leader = {}, replicas = {}, isr = {}, offlineReplicas = {})",
162            self.topic,
163            self.partition,
164            leader_str,
165            format_node_ids(&self.replicas),
166            format_node_ids(&self.in_sync_replicas),
167            format_node_ids(&self.offline_replicas),
168        )
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn make_node(id: i32) -> Node {
177        Node::new(id, format!("host{id}"), 9092)
178    }
179
180    #[test]
181    fn test_partition_info_creation() {
182        let leader = make_node(0);
183        let replicas = vec![make_node(0), make_node(1), make_node(2)];
184        let isr = vec![make_node(0), make_node(1)];
185
186        let pi = PartitionInfo::new("test".to_string(), 0, Some(leader), replicas, isr);
187        assert_eq!(pi.topic(), "test");
188        assert_eq!(pi.partition(), 0);
189        assert_eq!(pi.leader().unwrap().id(), 0);
190        assert_eq!(pi.replicas().len(), 3);
191        assert_eq!(pi.in_sync_replicas().len(), 2);
192        assert!(pi.offline_replicas().is_empty());
193    }
194
195    #[test]
196    fn test_partition_info_no_leader() {
197        let pi = PartitionInfo::new("test".to_string(), 0, None, vec![], vec![]);
198        assert!(pi.leader().is_none());
199    }
200
201    #[test]
202    fn test_partition_info_display() {
203        let leader = make_node(0);
204        let replicas = vec![make_node(0), make_node(1)];
205        let isr = vec![make_node(0)];
206        let pi = PartitionInfo::new("test".to_string(), 0, Some(leader), replicas, isr);
207        let display = pi.to_string();
208        assert!(display.contains("topic = test"));
209        assert!(display.contains("partition = 0"));
210        assert!(display.contains("leader = 0"));
211    }
212}