Skip to main content

confluent_kafka/common/
topic_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//! Leadership, replicas and ISR information for a topic partition.
16//!
17//! Corresponds to `org.apache.kafka.common.TopicPartitionInfo`.
18
19use crate::common::Node;
20
21/// A class containing leadership, replicas and ISR information for a topic
22/// partition.
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
24#[doc(alias = "org.apache.kafka.common.TopicPartitionInfo")]
25pub struct TopicPartitionInfo {
26    partition: i32,
27    leader: Option<Node>,
28    replicas: Vec<Node>,
29    isr: Vec<Node>,
30    elr: Option<Vec<Node>>,
31    last_known_elr: Option<Vec<Node>>,
32}
33
34impl TopicPartitionInfo {
35    /// Create an instance with the provided parameters.
36    ///
37    /// # Arguments
38    ///
39    /// - `partition` - the partition id
40    /// - `leader` - the leader of the partition or `None` if there is none.
41    /// - `replicas` - the replicas of the partition in the same order as the
42    ///   replica assignment (the preferred replica is the head of the list)
43    /// - `isr` - the in-sync replicas
44    /// - `elr` - the eligible leader replicas
45    /// - `last_known_elr` - the last known eligible leader replicas.
46    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#TopicPartitionInfo")]
47    pub fn with_elr_last_known_elr(
48        partition: i32,
49        leader: Option<Node>,
50        replicas: Vec<Node>,
51        isr: Vec<Node>,
52        elr: Vec<Node>,
53        last_known_elr: Vec<Node>,
54    ) -> Self {
55        Self::with_nullable_elr_last_known_elr(partition, leader, replicas, isr, Some(elr), Some(last_known_elr))
56    }
57
58    /// The six-argument constructor with Java's nullable `elr` /
59    /// `lastKnownElr` lists spelled as `Option`s: Java's constructor stores
60    /// whatever reference it is given, `null` included.
61    ///
62    /// Crate-internal: the public forms are [`Self::new`] (both `None`) and
63    /// [`Self::with_elr_last_known_elr`] (both present).
64    /// `DescribeTopicPartitionsResponse::partition_to_topic_partition_info` uses
65    /// it to keep a null wire list as `None`.
66    pub(crate) fn with_nullable_elr_last_known_elr(
67        partition: i32,
68        leader: Option<Node>,
69        replicas: Vec<Node>,
70        isr: Vec<Node>,
71        elr: Option<Vec<Node>>,
72        last_known_elr: Option<Vec<Node>>,
73    ) -> Self {
74        Self { partition, leader, replicas, isr, elr, last_known_elr }
75    }
76
77    /// Create an instance with the provided parameters, without eligible
78    /// leader replica information.
79    ///
80    /// # Arguments
81    ///
82    /// - `partition` - the partition id
83    /// - `leader` - the leader of the partition or `None` if there is none.
84    /// - `replicas` - the replicas of the partition in the same order as the
85    ///   replica assignment (the preferred replica is the head of the list)
86    /// - `isr` - the in-sync replicas
87    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#TopicPartitionInfo")]
88    pub fn new(partition: i32, leader: Option<Node>, replicas: Vec<Node>, isr: Vec<Node>) -> Self {
89        Self { partition, leader, replicas, isr, elr: None, last_known_elr: None }
90    }
91
92    /// Returns the partition id.
93    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#partition")]
94    pub fn partition(&self) -> i32 {
95        self.partition
96    }
97
98    /// Returns the leader of the partition or `None` if there is none.
99    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#leader")]
100    pub fn leader(&self) -> Option<&Node> {
101        self.leader.as_ref()
102    }
103
104    /// Returns the replicas of the partition in the same order as the replica
105    /// assignment. The preferred replica is the head of the list.
106    ///
107    /// Brokers with version lower than 0.11.0.0 return the replicas in
108    /// unspecified order due to a bug.
109    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#replicas")]
110    pub fn replicas(&self) -> &[Node] {
111        &self.replicas
112    }
113
114    /// Returns the in-sync replicas of the partition. The ordering is
115    /// unspecified.
116    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#isr")]
117    pub fn isr(&self) -> &[Node] {
118        &self.isr
119    }
120
121    /// Returns the eligible leader replicas of the partition, or `None` if
122    /// unavailable. The ordering is unspecified.
123    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#elr")]
124    pub fn elr(&self) -> Option<&[Node]> {
125        self.elr.as_deref()
126    }
127
128    /// Returns the last known eligible leader replicas of the partition, or
129    /// `None` if unavailable. The ordering is unspecified.
130    #[doc(alias = "org.apache.kafka.common.TopicPartitionInfo#lastKnownElr")]
131    pub fn last_known_elr(&self) -> Option<&[Node]> {
132        self.last_known_elr.as_deref()
133    }
134}
135
136impl std::fmt::Display for TopicPartitionInfo {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        fn join(nodes: &[Node]) -> String {
139            nodes.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(", ")
140        }
141        let leader = match &self.leader {
142            Some(n) => n.to_string(),
143            None => "null".to_string(),
144        };
145        let elr_string = self.elr.as_ref().map_or_else(|| "N/A".to_string(), |v| join(v));
146        let last_known_elr_string = self.last_known_elr.as_ref().map_or_else(|| "N/A".to_string(), |v| join(v));
147        write!(
148            f,
149            "(partition={}, leader={}, replicas={}, isr={}, elr={}, lastKnownElr={})",
150            self.partition,
151            leader,
152            join(&self.replicas),
153            join(&self.isr),
154            elr_string,
155            last_known_elr_string
156        )
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    fn node(id: i32) -> Node {
165        Node::new(id, "host".to_string(), 9092)
166    }
167
168    #[test]
169    fn accessors_full_constructor() {
170        let info = TopicPartitionInfo::with_elr_last_known_elr(
171            0,
172            Some(node(1)),
173            vec![node(1), node(2)],
174            vec![node(1)],
175            vec![node(2)],
176            vec![node(3)],
177        );
178        assert_eq!(info.partition(), 0);
179        assert_eq!(info.leader(), Some(&node(1)));
180        assert_eq!(info.replicas().len(), 2);
181        assert_eq!(info.isr(), &[node(1)]);
182        assert_eq!(info.elr(), Some(&[node(2)][..]));
183        assert_eq!(info.last_known_elr(), Some(&[node(3)][..]));
184    }
185
186    #[test]
187    fn short_constructor_leaves_elr_none() {
188        let info = TopicPartitionInfo::new(1, None, vec![node(1)], vec![node(1)]);
189        assert_eq!(info.leader(), None);
190        assert_eq!(info.elr(), None);
191        assert_eq!(info.last_known_elr(), None);
192    }
193
194    #[test]
195    fn equality() {
196        let a = TopicPartitionInfo::new(0, Some(node(1)), vec![], vec![]);
197        let b = TopicPartitionInfo::new(0, Some(node(1)), vec![], vec![]);
198        let c = TopicPartitionInfo::new(1, Some(node(1)), vec![], vec![]);
199        assert_eq!(a, b);
200        assert_ne!(a, c);
201    }
202
203    #[test]
204    fn display_uses_na_when_elr_absent() {
205        let info = TopicPartitionInfo::new(0, None, vec![], vec![]);
206        let s = info.to_string();
207        assert!(s.contains("elr=N/A"), "{s}");
208        assert!(s.contains("lastKnownElr=N/A"), "{s}");
209    }
210}