Skip to main content

confluent_kafka/admin/
topic_description.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//! A detailed description of a single topic in the cluster.
16
17use std::collections::BTreeSet;
18
19use crate::common::acl::AclOperation;
20use crate::common::{TopicPartitionInfo, Uuid};
21
22/// A detailed description of a single topic in the cluster.
23// `authorized_operations` uses `BTreeSet` for a deterministic ordering; Java
24// uses an unordered `Set<AclOperation>`. It is `Option` because Java's field is
25// nullable: `KafkaAdminClient` fills it from `AdminUtils.validAclOperations`,
26// which returns `null` when the broker did not report the operations — distinct
27// from a broker reporting an empty set.
28//
29// Equality mirrors Java's `TopicDescription.equals`, which compares `name`,
30// `internal`, `partitions` and `authorized_operations` but **not** `topic_id`
31// — see the manual [`PartialEq`] impl below.
32#[derive(Clone, Debug, Eq)]
33#[doc(alias = "org.apache.kafka.clients.admin.TopicDescription")]
34pub struct TopicDescription {
35    name: String,
36    internal: bool,
37    partitions: Vec<TopicPartitionInfo>,
38    authorized_operations: Option<BTreeSet<AclOperation>>,
39    topic_id: Uuid,
40}
41
42impl PartialEq for TopicDescription {
43    fn eq(&self, other: &Self) -> bool {
44        self.internal == other.internal
45            && self.name == other.name
46            && self.partitions == other.partitions
47            && self.authorized_operations == other.authorized_operations
48    }
49}
50
51impl std::hash::Hash for TopicDescription {
52    // Hashes the fields [`PartialEq`] compares, leaving out `topic_id` as
53    // Java's `TopicDescription.hashCode()` does.
54    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
55        self.name.hash(state);
56        self.internal.hash(state);
57        self.partitions.hash(state);
58        self.authorized_operations.hash(state);
59    }
60}
61
62impl TopicDescription {
63    /// Create an instance with the specified parameters.
64    ///
65    /// # Arguments
66    ///
67    /// - `name` - The topic name
68    /// - `internal` - Whether the topic is internal to Kafka
69    /// - `partitions` - A list of partitions where the index represents the partition id and the
70    ///   element contains leadership and replica information for that partition.
71    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#TopicDescription")]
72    pub fn new(name: impl Into<String>, internal: bool, partitions: Vec<TopicPartitionInfo>) -> Self {
73        Self::with_authorized_operations(name, internal, partitions, Some(BTreeSet::new()))
74    }
75
76    /// Create an instance with the specified parameters.
77    ///
78    /// # Arguments
79    ///
80    /// - `name` - The topic name
81    /// - `internal` - Whether the topic is internal to Kafka
82    /// - `partitions` - A list of partitions where the index represents the partition id and the
83    ///   element contains leadership and replica information for that partition.
84    /// - `authorized_operations` - authorized operations for this topic, or `None` if this is
85    ///   not known.
86    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#TopicDescription")]
87    pub fn with_authorized_operations(
88        name: impl Into<String>,
89        internal: bool,
90        partitions: Vec<TopicPartitionInfo>,
91        authorized_operations: Option<BTreeSet<AclOperation>>,
92    ) -> Self {
93        Self::with_authorized_operations_topic_id(name, internal, partitions, authorized_operations, Uuid::zero())
94    }
95
96    /// Create an instance with the specified parameters.
97    ///
98    /// # Arguments
99    ///
100    /// - `name` - The topic name
101    /// - `internal` - Whether the topic is internal to Kafka
102    /// - `partitions` - A list of partitions where the index represents the partition id and the
103    ///   element contains leadership and replica information for that partition.
104    /// - `authorized_operations` - authorized operations for this topic, or `None` if this is
105    ///   not known.
106    /// - `topic_id` - the topic id
107    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#TopicDescription")]
108    pub fn with_authorized_operations_topic_id(
109        name: impl Into<String>,
110        internal: bool,
111        partitions: Vec<TopicPartitionInfo>,
112        authorized_operations: Option<BTreeSet<AclOperation>>,
113        topic_id: Uuid,
114    ) -> Self {
115        Self { name: name.into(), internal, partitions, authorized_operations, topic_id }
116    }
117
118    /// Returns the name of the topic.
119    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#name")]
120    pub fn name(&self) -> &str {
121        &self.name
122    }
123
124    /// Returns whether the topic is internal to Kafka. An example of an internal topic
125    /// is the offsets and group management topic: `__consumer_offsets`.
126    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#isInternal")]
127    pub fn is_internal(&self) -> bool {
128        self.internal
129    }
130
131    /// Returns the topic id.
132    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#topicId")]
133    pub fn topic_id(&self) -> Uuid {
134        self.topic_id
135    }
136
137    /// Returns a list of partitions where the index represents the partition id and the
138    /// element contains leadership and replica information for that partition.
139    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#partitions")]
140    pub fn partitions(&self) -> &[TopicPartitionInfo] {
141        &self.partitions
142    }
143
144    /// The partition list, for appending in place.
145    ///
146    /// Java's `partitions()` returns the mutable backing list, and
147    /// `KafkaAdminClient` appends each continuation page of a paginated
148    /// `DescribeTopicPartitions` response to it
149    /// (`partiallyFinishedTopicDescription.partitions().addAll(...)` in
150    /// `KafkaAdminClient#generateDescribeTopicsCallWithDescribeTopicPartitionsApi`).
151    /// The public [`partitions`](Self::partitions) getter stays read-only.
152    pub(crate) fn partitions_mut(&mut self) -> &mut Vec<TopicPartitionInfo> {
153        &mut self.partitions
154    }
155
156    /// Returns the authorized operations for this topic, or `None` if this is not known.
157    #[doc(alias = "org.apache.kafka.clients.admin.TopicDescription#authorizedOperations")]
158    pub fn authorized_operations(&self) -> Option<&BTreeSet<AclOperation>> {
159        self.authorized_operations.as_ref()
160    }
161}
162
163impl std::fmt::Display for TopicDescription {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        let partitions = self.partitions.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(",");
166        // Java concatenates the nullable set directly, so an absent set prints
167        // as "null".
168        let operations = match &self.authorized_operations {
169            Some(operations) => format!("{operations:?}"),
170            None => "null".to_string(),
171        };
172        write!(
173            f,
174            "(name={}, internal={}, partitions={}, authorizedOperations={})",
175            self.name, self.internal, partitions, operations
176        )
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn simple_constructor_defaults() {
186        let desc = TopicDescription::new("t", false, vec![]);
187        assert_eq!(desc.name(), "t");
188        assert!(!desc.is_internal());
189        assert!(desc.partitions().is_empty());
190        // Java's 3-arg constructor passes an empty set, not null.
191        assert_eq!(desc.authorized_operations(), Some(&BTreeSet::new()));
192        assert_eq!(desc.topic_id(), Uuid::zero());
193    }
194
195    #[test]
196    fn four_arg_constructor_defaults_the_topic_id() {
197        // Java's 4-arg constructor forwards with Uuid.ZERO_UUID.
198        let ops = BTreeSet::from([AclOperation::Describe]);
199        let desc = TopicDescription::with_authorized_operations("t", true, vec![], Some(ops.clone()));
200        assert_eq!(desc.name(), "t");
201        assert!(desc.is_internal());
202        assert_eq!(desc.authorized_operations(), Some(&ops));
203        assert_eq!(desc.topic_id(), Uuid::zero());
204    }
205
206    #[test]
207    fn equality_ignores_topic_id_like_java() {
208        // Java TopicDescription.equals does NOT compare topicId.
209        let a = TopicDescription::with_authorized_operations_topic_id(
210            "t",
211            false,
212            vec![],
213            Some(BTreeSet::new()),
214            Uuid::new(1, 1),
215        );
216        let b = TopicDescription::with_authorized_operations_topic_id(
217            "t",
218            false,
219            vec![],
220            Some(BTreeSet::new()),
221            Uuid::new(2, 2),
222        );
223        // Only topic_id differs, which equals() ignores -> equal.
224        assert_eq!(a, b);
225    }
226
227    #[test]
228    fn equality_compares_name_and_partitions() {
229        let a = TopicDescription::new("t", false, vec![]);
230        let b = TopicDescription::new("other", false, vec![]);
231        assert_ne!(a, b);
232    }
233
234    #[test]
235    fn equality_separates_unreported_from_reported_empty_operations() {
236        // Java's equals uses Objects.equals on the nullable set, so null and an
237        // empty set are different topics.
238        let unreported = TopicDescription::with_authorized_operations_topic_id("t", false, vec![], None, Uuid::zero());
239        let reported_empty = TopicDescription::with_authorized_operations_topic_id(
240            "t",
241            false,
242            vec![],
243            Some(BTreeSet::new()),
244            Uuid::zero(),
245        );
246        assert_ne!(unreported, reported_empty);
247        assert_eq!(unreported.authorized_operations(), None);
248        assert_eq!(reported_empty.authorized_operations(), Some(&BTreeSet::new()));
249    }
250}