Skip to main content

confluent_kafka/admin/
delete_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 the `Admin::delete_topics_with_*` methods.
16
17use std::collections::HashMap;
18
19use crate::common::{KafkaFuture, Uuid};
20
21/// The result of the `Admin::delete_topics_with_*` methods.
22// Exactly one of the two maps is present, the one matching the kind of
23// `TopicCollection` the request used.
24#[derive(Clone, Debug)]
25#[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult")]
26pub struct DeleteTopicsResult {
27    topic_id_futures: Option<HashMap<Uuid, KafkaFuture<()>>>,
28    name_futures: Option<HashMap<String, KafkaFuture<()>>>,
29}
30
31impl DeleteTopicsResult {
32    /// Creates a result keyed by topic id or by topic name.
33    ///
34    /// # Panics
35    ///
36    /// If both maps or neither are given, as Java throws
37    /// `IllegalArgumentException`.
38    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#DeleteTopicsResult")]
39    pub(crate) fn with_topic_id_futures_name_futures(
40        topic_id_futures: Option<HashMap<Uuid, KafkaFuture<()>>>,
41        name_futures: Option<HashMap<String, KafkaFuture<()>>>,
42    ) -> Self {
43        assert!(
44            topic_id_futures.is_none() || name_futures.is_none(),
45            "topicIdFutures and nameFutures cannot both be specified."
46        );
47        assert!(
48            topic_id_futures.is_some() || name_futures.is_some(),
49            "topicIdFutures and nameFutures cannot both be null."
50        );
51        DeleteTopicsResult { topic_id_futures, name_futures }
52    }
53
54    /// Creates a result keyed by topic id.
55    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#ofTopicIds")]
56    pub(crate) fn of_topic_ids(topic_id_futures: HashMap<Uuid, KafkaFuture<()>>) -> Self {
57        Self::with_topic_id_futures_name_futures(Some(topic_id_futures), None)
58    }
59
60    /// Creates a result keyed by topic name.
61    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#ofTopicNames")]
62    pub(crate) fn of_topic_names(name_futures: HashMap<String, KafkaFuture<()>>) -> Self {
63        Self::with_topic_id_futures_name_futures(None, Some(name_futures))
64    }
65
66    /// Use when `Admin::delete_topics_with_topic_collection_options` used a `TopicCollection`
67    /// of ids.
68    ///
69    /// # Returns
70    ///
71    /// a map from topic IDs to futures which can be used to check the status of individual
72    /// deletions if the deleteTopics request used topic IDs. Otherwise return `None`.
73    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#topicIdValues")]
74    pub fn topic_id_values(&self) -> Option<&HashMap<Uuid, KafkaFuture<()>>> {
75        self.topic_id_futures.as_ref()
76    }
77
78    /// Use when `Admin::delete_topics_with_topic_collection_options` used a `TopicCollection`
79    /// of names.
80    ///
81    /// # Returns
82    ///
83    /// a map from topic names to futures which can be used to check the status of individual
84    /// deletions if the deleteTopics request used topic names. Otherwise return `None`.
85    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#topicNameValues")]
86    pub fn topic_name_values(&self) -> Option<&HashMap<String, KafkaFuture<()>>> {
87        self.name_futures.as_ref()
88    }
89
90    /// Returns a future which succeeds only if all the topic deletions succeed.
91    #[doc(alias = "org.apache.kafka.clients.admin.DeleteTopicsResult#all")]
92    pub fn all(&self) -> KafkaFuture<()> {
93        match &self.topic_id_futures {
94            None => KafkaFuture::all_of(self.name_futures.iter().flat_map(HashMap::values).cloned().collect()),
95            Some(topic_id_futures) => KafkaFuture::all_of(topic_id_futures.values().cloned().collect()),
96        }
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103    use crate::common::Error;
104    use crate::common::internals::KafkaFutureImpl;
105
106    #[tokio::test]
107    async fn by_names_all_succeeds() {
108        let h1: KafkaFutureImpl<()> = KafkaFutureImpl::new();
109        let h2: KafkaFutureImpl<()> = KafkaFutureImpl::new();
110        let mut map = HashMap::new();
111        map.insert("a".to_string(), h1.future());
112        map.insert("b".to_string(), h2.future());
113        let result = DeleteTopicsResult::of_topic_names(map);
114        assert!(result.topic_id_values().is_none());
115        assert!(result.topic_name_values().is_some());
116        h1.complete(());
117        h2.complete(());
118        assert_eq!(result.all().get().await.unwrap(), ());
119    }
120
121    #[tokio::test]
122    async fn by_ids_all_fails_if_one_fails() {
123        let h1: KafkaFutureImpl<()> = KafkaFutureImpl::new();
124        let mut map = HashMap::new();
125        map.insert(Uuid::new(1, 1), h1.future());
126        let result = DeleteTopicsResult::of_topic_ids(map);
127        assert!(result.topic_name_values().is_none());
128        h1.complete_with_error(Error::local_illegal_state("gone".to_string()));
129        assert!(result.all().get().await.is_err());
130    }
131
132    /// The message of the panic `f` raises.
133    fn panic_message(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
134        let payload = std::panic::catch_unwind(f).expect_err("expected a panic");
135        payload
136            .downcast_ref::<&str>()
137            .map(ToString::to_string)
138            .or_else(|| payload.downcast_ref::<String>().cloned())
139            .unwrap()
140    }
141
142    fn completed() -> KafkaFuture<()> {
143        let future: KafkaFutureImpl<()> = KafkaFutureImpl::new();
144        future.complete(());
145        future.future()
146    }
147
148    /// `DeleteTopicsResultTest.testDeleteTopicsResultWithNames`.
149    #[test]
150    fn test_delete_topics_result_with_names() {
151        let topic_names = HashMap::from([("foo".to_string(), completed())]);
152        let topic_name_futures = DeleteTopicsResult::of_topic_names(topic_names);
153        let values = topic_name_futures.topic_name_values().unwrap();
154        assert_eq!(values.keys().collect::<Vec<_>>(), ["foo"]);
155        assert!(values["foo"].is_done());
156        assert!(topic_name_futures.topic_id_values().is_none());
157        assert!(topic_name_futures.all().is_done());
158    }
159
160    /// `DeleteTopicsResultTest.testDeleteTopicsResultWithIds`.
161    #[test]
162    fn test_delete_topics_result_with_ids() {
163        let id = Uuid::random_uuid();
164        let topic_ids = HashMap::from([(id, completed())]);
165        let topic_id_futures = DeleteTopicsResult::of_topic_ids(topic_ids);
166        let values = topic_id_futures.topic_id_values().unwrap();
167        assert_eq!(values.keys().collect::<Vec<_>>(), [&id]);
168        assert!(values[&id].is_done());
169        assert!(topic_id_futures.topic_name_values().is_none());
170        assert!(topic_id_futures.all().is_done());
171    }
172
173    /// `DeleteTopicsResultTest.testInvalidConfigurations`.
174    #[test]
175    fn test_invalid_configurations() {
176        assert_eq!(
177            panic_message(|| {
178                DeleteTopicsResult::with_topic_id_futures_name_futures(None, None);
179            }),
180            "topicIdFutures and nameFutures cannot both be null."
181        );
182        assert_eq!(
183            panic_message(|| {
184                DeleteTopicsResult::with_topic_id_futures_name_futures(Some(HashMap::new()), Some(HashMap::new()));
185            }),
186            "topicIdFutures and nameFutures cannot both be specified."
187        );
188    }
189}