Skip to main content

confluent_kafka/admin/
create_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::create_topics`.
16
17use std::collections::HashMap;
18
19use crate::admin::Config;
20use crate::common::{Error, KafkaFuture, Uuid};
21
22/// Topic metadata and configuration returned per created topic.
23///
24/// Carries either the metadata or a stored error; the accessors return the
25/// stored error.
26#[derive(Clone, Debug)]
27#[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig")]
28pub struct TopicMetadataAndConfig {
29    error: Option<Error>,
30    topic_id: Uuid,
31    num_partitions: i32,
32    replication_factor: i32,
33    config: Option<Config>,
34}
35
36impl TopicMetadataAndConfig {
37    /// Creates a successful metadata-and-config holder.
38    ///
39    /// # Arguments
40    ///
41    /// - `topic_id` - the topic id.
42    /// - `num_partitions` - the number of partitions of the topic.
43    /// - `replication_factor` - the replication factor of the topic.
44    /// - `config` - the topic config.
45    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#TopicMetadataAndConfig")]
46    pub fn new(topic_id: Uuid, num_partitions: i32, replication_factor: i32, config: Config) -> Self {
47        Self { error: None, topic_id, num_partitions, replication_factor, config: Some(config) }
48    }
49
50    /// Creates a holder representing a failure; every accessor returns the
51    /// error.
52    ///
53    /// # Arguments
54    ///
55    /// - `error` - the error every accessor returns.
56    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#TopicMetadataAndConfig")]
57    pub fn with_error(error: Error) -> Self {
58        Self {
59            error: Some(error),
60            topic_id: Uuid::zero(),
61            num_partitions: CreateTopicsResult::UNKNOWN,
62            replication_factor: CreateTopicsResult::UNKNOWN,
63            config: None,
64        }
65    }
66
67    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#ensureSuccess")]
68    fn ensure_success(&self) -> Result<(), Error> {
69        match &self.error {
70            Some(e) => Err(e.clone()),
71            None => Ok(()),
72        }
73    }
74
75    /// Returns the topic id, or the stored error.
76    ///
77    /// # Errors
78    ///
79    /// The error the topic creation failed with, if any.
80    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#topicId")]
81    pub fn topic_id(&self) -> Result<Uuid, Error> {
82        self.ensure_success()?;
83        Ok(self.topic_id)
84    }
85
86    /// Returns the number of partitions, or the stored error.
87    ///
88    /// # Errors
89    ///
90    /// The error the topic creation failed with, if any.
91    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#numPartitions")]
92    pub fn num_partitions(&self) -> Result<i32, Error> {
93        self.ensure_success()?;
94        Ok(self.num_partitions)
95    }
96
97    /// Returns the replication factor, or the stored error.
98    ///
99    /// # Errors
100    ///
101    /// The error the topic creation failed with, if any.
102    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#replicationFactor")]
103    pub fn replication_factor(&self) -> Result<i32, Error> {
104        self.ensure_success()?;
105        Ok(self.replication_factor)
106    }
107
108    /// Returns the topic config, or the stored error.
109    ///
110    /// # Errors
111    ///
112    /// The error the topic creation failed with, if any.
113    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult$TopicMetadataAndConfig#config")]
114    pub fn config(&self) -> Result<Config, Error> {
115        self.ensure_success()?;
116        // Only `None` when an exception is present, already handled above.
117        Ok(self.config.clone().expect("config present on success"))
118    }
119}
120
121/// The result of `Admin::create_topics`.
122#[derive(Clone, Debug)]
123#[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult")]
124pub struct CreateTopicsResult {
125    futures: HashMap<String, KafkaFuture<TopicMetadataAndConfig>>,
126}
127
128impl CreateTopicsResult {
129    /// Sentinel used when the broker did not return partition/replication metadata.
130    pub(crate) const UNKNOWN: i32 = -1;
131
132    /// Creates a result from a map of topic name to per-topic future.
133    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#CreateTopicsResult")]
134    pub(crate) fn new(futures: HashMap<String, KafkaFuture<TopicMetadataAndConfig>>) -> Self {
135        Self { futures }
136    }
137
138    /// Returns a map from topic names to futures, which can be used to check the
139    /// status of individual topic creations.
140    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#values")]
141    pub fn values(&self) -> HashMap<String, KafkaFuture<()>> {
142        self.futures
143            .iter()
144            .map(|(name, future)| (name.clone(), future.then_apply(|_| Ok(()))))
145            .collect()
146    }
147
148    /// Returns a future which succeeds if all the topic creations succeed.
149    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#all")]
150    pub fn all(&self) -> KafkaFuture<()> {
151        KafkaFuture::all_of(self.futures.values().cloned().collect())
152    }
153
154    /// Returns a future that provides topic configs for the topic when the
155    /// request completes.
156    ///
157    /// If broker version doesn't support replication factor in the response, the future
158    /// completes with an error answering `Error::is_unsupported_version_error`. If broker
159    /// returned an error for topic configs, it completes with the appropriate error, for
160    /// example one answering `Error::is_topic_authorization_error` if user does not have
161    /// permission to describe topic configs. Note that the values for the type and documentation
162    /// fields will be `None`.
163    ///
164    /// # Arguments
165    ///
166    /// - `topic` - the topic name.
167    ///
168    /// # Panics
169    ///
170    /// Panics with `Topic <topic> was not part of the createTopics request` if
171    /// `topic` was not part of the original request, where Java's
172    /// `futures.get(topic)` is `null` and the call throws
173    /// `NullPointerException`. Asking for a
174    /// topic the caller did not request is a programming error the caller can
175    /// rule out, so the accessor keeps its plain `KafkaFuture` signature;
176    /// read the requested topics from
177    /// [`values`](Self::values) to avoid it.
178    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#config")]
179    pub fn config(&self, topic: &str) -> KafkaFuture<Config> {
180        self.future_for(topic).then_apply(|tmac: TopicMetadataAndConfig| tmac.config())
181    }
182
183    /// Returns a future that provides the topic id for the topic when the request completes.
184    ///
185    /// If broker version doesn't support replication factor in the response, the future
186    /// completes with an error answering `Error::is_unsupported_version_error`. If broker
187    /// returned an error for topic configs, it completes with the appropriate error, for
188    /// example one answering `Error::is_topic_authorization_error` if user does not have
189    /// permission to describe topic configs.
190    ///
191    /// # Arguments
192    ///
193    /// - `topic` - the topic name.
194    ///
195    /// # Panics
196    ///
197    /// Panics with `Topic <topic> was not part of the createTopics request` if
198    /// `topic` was not part of the original request, where Java's
199    /// `futures.get(topic)` is `null` and the call throws
200    /// `NullPointerException`. Asking for a
201    /// topic the caller did not request is a programming error the caller can
202    /// rule out, so the accessor keeps its plain `KafkaFuture` signature;
203    /// read the requested topics from
204    /// [`values`](Self::values) to avoid it.
205    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#topicId")]
206    pub fn topic_id(&self, topic: &str) -> KafkaFuture<Uuid> {
207        self.future_for(topic)
208            .then_apply(|tmac: TopicMetadataAndConfig| tmac.topic_id())
209    }
210
211    /// Returns a future that provides the number of partitions for the topic when the request
212    /// completes.
213    ///
214    /// If broker version doesn't support replication factor in the response, the future
215    /// completes with an error answering `Error::is_unsupported_version_error`. If broker
216    /// returned an error for topic configs, it completes with the appropriate error, for
217    /// example one answering `Error::is_topic_authorization_error` if user does not have
218    /// permission to describe topic configs.
219    ///
220    /// # Arguments
221    ///
222    /// - `topic` - the topic name.
223    ///
224    /// # Panics
225    ///
226    /// Panics with `Topic <topic> was not part of the createTopics request` if
227    /// `topic` was not part of the original request, where Java's
228    /// `futures.get(topic)` is `null` and the call throws
229    /// `NullPointerException`. Asking for a
230    /// topic the caller did not request is a programming error the caller can
231    /// rule out, so the accessor keeps its plain `KafkaFuture` signature;
232    /// read the requested topics from
233    /// [`values`](Self::values) to avoid it.
234    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#numPartitions")]
235    pub fn num_partitions(&self, topic: &str) -> KafkaFuture<i32> {
236        self.future_for(topic)
237            .then_apply(|tmac: TopicMetadataAndConfig| tmac.num_partitions())
238    }
239
240    /// Returns a future that provides the replication factor for the topic when the request
241    /// completes.
242    ///
243    /// If broker version doesn't support replication factor in the response, the future
244    /// completes with an error answering `Error::is_unsupported_version_error`. If broker
245    /// returned an error for topic configs, it completes with the appropriate error, for
246    /// example one answering `Error::is_topic_authorization_error` if user does not have
247    /// permission to describe topic configs.
248    ///
249    /// # Arguments
250    ///
251    /// - `topic` - the topic name.
252    ///
253    /// # Panics
254    ///
255    /// Panics with `Topic <topic> was not part of the createTopics request` if
256    /// `topic` was not part of the original request, where Java's
257    /// `futures.get(topic)` is `null` and the call throws
258    /// `NullPointerException`. Asking for a
259    /// topic the caller did not request is a programming error the caller can
260    /// rule out, so the accessor keeps its plain `KafkaFuture` signature;
261    /// read the requested topics from
262    /// [`values`](Self::values) to avoid it.
263    #[doc(alias = "org.apache.kafka.clients.admin.CreateTopicsResult#replicationFactor")]
264    pub fn replication_factor(&self, topic: &str) -> KafkaFuture<i32> {
265        self.future_for(topic)
266            .then_apply(|tmac: TopicMetadataAndConfig| tmac.replication_factor())
267    }
268
269    fn future_for(&self, topic: &str) -> &KafkaFuture<TopicMetadataAndConfig> {
270        self.futures
271            .get(topic)
272            .unwrap_or_else(|| panic!("Topic {topic} was not part of the createTopics request"))
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use crate::admin::ConfigEntry;
280    use crate::common::internals::KafkaFutureImpl;
281
282    fn config() -> Config {
283        Config::new([ConfigEntry::new("k".to_string(), Some("v".to_string()))])
284    }
285
286    /// New test, no Java original: each per-topic accessor panics, as its
287    /// `# Panics` section documents, for a topic the request did not name,
288    /// where Java's `futures.get(topic)` is `null` and the call throws
289    /// `NullPointerException`.
290    #[test]
291    fn accessors_panic_for_a_topic_not_in_the_request() {
292        let handle: KafkaFutureImpl<TopicMetadataAndConfig> = KafkaFutureImpl::new();
293        let result = CreateTopicsResult::new(HashMap::from([("t".to_string(), handle.future())]));
294        let message = |accessor: &dyn Fn(&CreateTopicsResult)| {
295            let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| accessor(&result)))
296                .expect_err("an accessor for an unrequested topic must panic");
297            payload.downcast_ref::<String>().cloned().expect("a formatted panic message")
298        };
299        let expected = "Topic nope was not part of the createTopics request";
300        assert_eq!(message(&|r| drop(r.config("nope"))), expected);
301        assert_eq!(message(&|r| drop(r.topic_id("nope"))), expected);
302        assert_eq!(message(&|r| drop(r.num_partitions("nope"))), expected);
303        assert_eq!(message(&|r| drop(r.replication_factor("nope"))), expected);
304    }
305
306    #[tokio::test]
307    async fn values_and_all_succeed() {
308        let handle: KafkaFutureImpl<TopicMetadataAndConfig> = KafkaFutureImpl::new();
309        let mut futures = HashMap::new();
310        futures.insert("t".to_string(), handle.future());
311        let result = CreateTopicsResult::new(futures);
312
313        handle.complete(TopicMetadataAndConfig::new(Uuid::new(1, 2), 3, 2, config()));
314
315        assert_eq!(result.values()["t"].get().await.unwrap(), ());
316        assert_eq!(result.all().get().await.unwrap(), ());
317        assert_eq!(result.topic_id("t").get().await.unwrap(), Uuid::new(1, 2));
318        assert_eq!(result.num_partitions("t").get().await.unwrap(), 3);
319        assert_eq!(result.replication_factor("t").get().await.unwrap(), 2);
320        assert_eq!(result.config("t").get().await.unwrap().get("k").unwrap().value(), Some("v"));
321    }
322
323    #[tokio::test]
324    async fn accessors_surface_stored_error() {
325        let handle: KafkaFutureImpl<TopicMetadataAndConfig> = KafkaFutureImpl::new();
326        let mut futures = HashMap::new();
327        futures.insert("t".to_string(), handle.future());
328        let result = CreateTopicsResult::new(futures);
329
330        handle.complete(TopicMetadataAndConfig::with_error(Error::local_illegal_state("unsupported")));
331
332        assert!(matches!(result.config("t").get().await, Err(Error::LocalIllegalState(_))));
333        assert!(matches!(result.topic_id("t").get().await, Err(Error::LocalIllegalState(_))));
334        // values()/all() still succeed (they only observe completion, not the
335        // metadata accessors' stored error).
336        assert_eq!(result.all().get().await.unwrap(), ());
337    }
338}