Skip to main content

confluent_kafka/admin/
describe_topics_result.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//! The result of `Admin::describe_topics_with_topics`.
16
17use std::collections::HashMap;
18use std::hash::Hash;
19
20use crate::admin::TopicDescription;
21use crate::common::{KafkaFuture, Uuid};
22
23/// The result of `Admin::describe_topics_with_topics`.
24// Exactly one of the two maps is present, the one matching the kind of
25// `TopicCollection` the request used.
26#[derive(Clone, Debug)]
27#[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult")]
28pub struct DescribeTopicsResult {
29    topic_id_futures: Option<HashMap<Uuid, KafkaFuture<TopicDescription>>>,
30    name_futures: Option<HashMap<String, KafkaFuture<TopicDescription>>>,
31}
32
33impl DescribeTopicsResult {
34    /// Creates a result keyed by topic id or by topic name.
35    ///
36    /// # Panics
37    ///
38    /// If both maps or neither are given, as Java throws
39    /// `IllegalArgumentException`.
40    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#DescribeTopicsResult")]
41    pub(crate) fn with_topic_id_futures_name_futures(
42        topic_id_futures: Option<HashMap<Uuid, KafkaFuture<TopicDescription>>>,
43        name_futures: Option<HashMap<String, KafkaFuture<TopicDescription>>>,
44    ) -> Self {
45        assert!(
46            topic_id_futures.is_none() || name_futures.is_none(),
47            "topicIdFutures and nameFutures cannot both be specified."
48        );
49        assert!(
50            topic_id_futures.is_some() || name_futures.is_some(),
51            "topicIdFutures and nameFutures cannot both be null."
52        );
53        DescribeTopicsResult { topic_id_futures, name_futures }
54    }
55
56    /// Creates a result keyed by topic id.
57    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#ofTopicIds")]
58    pub(crate) fn of_topic_ids(topic_id_futures: HashMap<Uuid, KafkaFuture<TopicDescription>>) -> Self {
59        Self::with_topic_id_futures_name_futures(Some(topic_id_futures), None)
60    }
61
62    /// Creates a result keyed by topic name.
63    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#ofTopicNames")]
64    pub(crate) fn of_topic_names(name_futures: HashMap<String, KafkaFuture<TopicDescription>>) -> Self {
65        Self::with_topic_id_futures_name_futures(None, Some(name_futures))
66    }
67
68    /// Use when `Admin::describe_topics_with_topics_options` used a
69    /// `TopicCollection` of ids.
70    ///
71    /// # Returns
72    ///
73    /// a map from topic IDs to futures which can be used to check the status of individual topics
74    /// if the request used topic IDs, otherwise return `None`.
75    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#topicIdValues")]
76    pub fn topic_id_values(&self) -> Option<&HashMap<Uuid, KafkaFuture<TopicDescription>>> {
77        self.topic_id_futures.as_ref()
78    }
79
80    /// Use when `Admin::describe_topics_with_topics_options` used a
81    /// `TopicCollection` of names.
82    ///
83    /// # Returns
84    ///
85    /// a map from topic names to futures which can be used to check the status of individual topics
86    /// if the request used topic names, otherwise return `None`.
87    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#topicNameValues")]
88    pub fn topic_name_values(&self) -> Option<&HashMap<String, KafkaFuture<TopicDescription>>> {
89        self.name_futures.as_ref()
90    }
91
92    /// Returns a future map from topic names to descriptions which can be used to check the
93    /// status of individual description if the describe topic request used topic names,
94    /// otherwise `None`. This request succeeds only if all the topic descriptions succeed.
95    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#allTopicNames")]
96    pub fn all_topic_names(&self) -> Option<KafkaFuture<HashMap<String, TopicDescription>>> {
97        Self::all(self.name_futures.as_ref())
98    }
99
100    /// Returns a future map from topic ids to descriptions which can be used to check the
101    /// status of individual description if the describe topic request used topic ids,
102    /// otherwise `None`. This request succeeds only if all the topic descriptions succeed.
103    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#allTopicIds")]
104    pub fn all_topic_ids(&self) -> Option<KafkaFuture<HashMap<Uuid, TopicDescription>>> {
105        Self::all(self.topic_id_futures.as_ref())
106    }
107
108    /// Return a future which succeeds only if all the topic descriptions
109    /// succeed.
110    #[doc(alias = "org.apache.kafka.clients.admin.DescribeTopicsResult#all")]
111    fn all<T: Clone + Eq + Hash + Send + Sync + 'static>(
112        futures: Option<&HashMap<T, KafkaFuture<TopicDescription>>>,
113    ) -> Option<KafkaFuture<HashMap<T, TopicDescription>>> {
114        let futures = futures?;
115        Some(KafkaFuture::join_map(
116            futures.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
117        ))
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use crate::common::Error;
125    use crate::common::internals::KafkaFutureImpl;
126
127    fn description(name: &str) -> TopicDescription {
128        TopicDescription::new(name, false, vec![])
129    }
130
131    #[tokio::test]
132    async fn by_names_all_collects_map() {
133        let h1: KafkaFutureImpl<TopicDescription> = KafkaFutureImpl::new();
134        let h2: KafkaFutureImpl<TopicDescription> = KafkaFutureImpl::new();
135        let mut map = HashMap::new();
136        map.insert("a".to_string(), h1.future());
137        map.insert("b".to_string(), h2.future());
138        let result = DescribeTopicsResult::of_topic_names(map);
139        assert!(result.topic_id_values().is_none());
140        assert!(result.all_topic_ids().is_none());
141
142        h1.complete(description("a"));
143        h2.complete(description("b"));
144        let all = result.all_topic_names().unwrap().get().await.unwrap();
145        assert_eq!(all.len(), 2);
146        assert_eq!(all["a"].name(), "a");
147    }
148
149    #[tokio::test]
150    async fn by_ids_all_fails_if_one_fails() {
151        let h1: KafkaFutureImpl<TopicDescription> = KafkaFutureImpl::new();
152        let mut map = HashMap::new();
153        map.insert(Uuid::new(1, 1), h1.future());
154        let result = DescribeTopicsResult::of_topic_ids(map);
155        assert!(result.all_topic_names().is_none());
156        h1.complete_with_error(Error::local_illegal_state("x".to_string()));
157        assert!(result.all_topic_ids().unwrap().get().await.is_err());
158    }
159
160    /// `DescribeTopicsResultTest.testNullAllTopicNames`.
161    #[test]
162    fn test_null_all_topic_names() {
163        let result = DescribeTopicsResult::of_topic_ids(HashMap::from([(
164            Uuid::random_uuid(),
165            KafkaFuture::completed_future(Ok(description("foo"))),
166        )]));
167        assert!(result.all_topic_names().is_none());
168    }
169
170    /// `DescribeTopicsResultTest.testNullAllTopicIds`.
171    #[test]
172    fn test_null_all_topic_ids() {
173        let result = DescribeTopicsResult::of_topic_names(HashMap::from([(
174            "foo".to_string(),
175            KafkaFuture::completed_future(Ok(description("foo"))),
176        )]));
177        assert!(result.all_topic_ids().is_none());
178    }
179
180    /// The constructor checks Java's invariant as `DeleteTopicsResult`'s does
181    /// (`DeleteTopicsResultTest.testInvalidConfigurations`).
182    #[test]
183    fn test_invalid_configurations() {
184        let both_null = std::panic::catch_unwind(|| {
185            DescribeTopicsResult::with_topic_id_futures_name_futures(None, None);
186        })
187        .expect_err("expected a panic");
188        assert_eq!(
189            both_null.downcast_ref::<&str>(),
190            Some(&"topicIdFutures and nameFutures cannot both be null.")
191        );
192        let both_set = std::panic::catch_unwind(|| {
193            DescribeTopicsResult::with_topic_id_futures_name_futures(Some(HashMap::new()), Some(HashMap::new()));
194        })
195        .expect_err("expected a panic");
196        assert_eq!(
197            both_set.downcast_ref::<&str>(),
198            Some(&"topicIdFutures and nameFutures cannot both be specified.")
199        );
200    }
201}