Skip to main content

confluent_kafka/admin/
elect_leaders_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::elect_leaders`.
16
17use std::collections::HashMap;
18
19use crate::common::{Error, KafkaFuture, TopicPartition};
20
21/// The result of `Admin::elect_leaders`.
22#[derive(Clone, Debug)]
23#[doc(alias = "org.apache.kafka.clients.admin.ElectLeadersResult")]
24pub struct ElectLeadersResult {
25    election_future: KafkaFuture<HashMap<TopicPartition, Option<Error>>>,
26}
27
28impl ElectLeadersResult {
29    /// Creates a result wrapping the election future.
30    #[doc(alias = "org.apache.kafka.clients.admin.ElectLeadersResult#ElectLeadersResult")]
31    pub(crate) fn new(election_future: KafkaFuture<HashMap<TopicPartition, Option<Error>>>) -> Self {
32        Self { election_future }
33    }
34
35    /// Returns a future for the topic partitions for which a leader election was
36    /// attempted. If the election succeeded then the value for a topic
37    /// partition will be `None`; otherwise the election failed and the value
38    /// will be `Some(error)`.
39    #[doc(alias = "org.apache.kafka.clients.admin.ElectLeadersResult#partitions")]
40    pub fn partitions(&self) -> KafkaFuture<HashMap<TopicPartition, Option<Error>>> {
41        self.election_future.clone()
42    }
43
44    /// Returns a future which succeeds if all the topic elections succeed.
45    #[doc(alias = "org.apache.kafka.clients.admin.ElectLeadersResult#all")]
46    pub fn all(&self) -> KafkaFuture<()> {
47        self.election_future
48            .then_apply(|topic_partitions: HashMap<TopicPartition, Option<Error>>| {
49                match topic_partitions.into_values().flatten().next() {
50                    Some(error) => Err(error),
51                    None => Ok(()),
52                }
53            })
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use crate::common::internals::KafkaFutureImpl;
61    use crate::common::protocol::Errors;
62
63    #[tokio::test]
64    async fn all_succeeds_when_no_partition_has_error() {
65        let h: KafkaFutureImpl<HashMap<TopicPartition, Option<Error>>> = KafkaFutureImpl::new();
66        let result = ElectLeadersResult::new(h.future());
67        let mut map = HashMap::new();
68        map.insert(TopicPartition::new("t", 0), None);
69        map.insert(TopicPartition::new("t", 1), None);
70        h.complete(map);
71        assert_eq!(result.all().get().await.unwrap(), ());
72    }
73
74    #[tokio::test]
75    async fn all_fails_when_any_partition_has_error() {
76        let h: KafkaFutureImpl<HashMap<TopicPartition, Option<Error>>> = KafkaFutureImpl::new();
77        let result = ElectLeadersResult::new(h.future());
78        let mut map = HashMap::new();
79        map.insert(TopicPartition::new("t", 0), None);
80        map.insert(
81            TopicPartition::new("t", 1),
82            Some(Error::new(Errors::ClusterAuthorizationFailed)),
83        );
84        h.complete(map);
85        let err = result.all().get().await.unwrap_err();
86        assert_eq!(err.error(), Errors::ClusterAuthorizationFailed);
87    }
88
89    #[tokio::test]
90    async fn partitions_exposes_per_partition_result() {
91        let h: KafkaFutureImpl<HashMap<TopicPartition, Option<Error>>> = KafkaFutureImpl::new();
92        let result = ElectLeadersResult::new(h.future());
93        let mut map = HashMap::new();
94        map.insert(
95            TopicPartition::new("t", 0),
96            Some(Error::new(Errors::ClusterAuthorizationFailed)),
97        );
98        h.complete(map);
99        let partitions = result.partitions().get().await.unwrap();
100        assert!(partitions.get(&TopicPartition::new("t", 0)).unwrap().is_some());
101    }
102}