Skip to main content

confluent_kafka/admin/
list_groups_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::list_groups`.
16
17use crate::admin::GroupListing;
18use crate::common::{Error, KafkaFuture};
19
20/// The result of `Admin::list_groups`.
21// Java's constructor takes a single `KafkaFuture<Collection<Object>>` mixing
22// `GroupListing`s and `Throwable`s and, via `thenApply`, splits it into the
23// `all`/`valid`/`errors` futures. The Rust port models the mixed collection as
24// `Vec<Result<GroupListing, Error>>` (a listing is `Ok`, an error is
25// `Err`) and derives the three views lazily with `then_apply`
26// — semantically identical (`all` fails with the first error; `valid`/`errors`
27// never fail).
28#[derive(Clone, Debug)]
29#[doc(alias = "org.apache.kafka.clients.admin.ListGroupsResult")]
30pub struct ListGroupsResult {
31    source: KafkaFuture<Vec<Result<GroupListing, Error>>>,
32}
33
34impl ListGroupsResult {
35    /// Creates a result from the combined per-broker listings-or-errors future.
36    #[doc(alias = "org.apache.kafka.clients.admin.ListGroupsResult#ListGroupsResult")]
37    pub(crate) fn new(source: KafkaFuture<Vec<Result<GroupListing, Error>>>) -> Self {
38        Self { source }
39    }
40
41    /// Returns a future yielding either the first error, or the full set of listings.
42    #[doc(alias = "org.apache.kafka.clients.admin.ListGroupsResult#all")]
43    pub fn all(&self) -> KafkaFuture<Vec<GroupListing>> {
44        self.source.then_apply(|results| {
45            let mut valid = Vec::new();
46            for result in results {
47                match result {
48                    Ok(listing) => valid.push(listing),
49                    Err(error) => return Err(error),
50                }
51            }
52            Ok(valid)
53        })
54    }
55
56    /// Returns a future which yields just the valid listings.
57    ///
58    /// This future never fails with an error, no matter what happens. Errors are completely
59    /// ignored. If nothing can be fetched, an empty collection is yielded. If there is an error,
60    /// but some results can be returned, this future will yield those partial results. When
61    /// using this future, it is a good idea to also check the errors future so that errors can
62    /// be displayed and handled.
63    #[doc(alias = "org.apache.kafka.clients.admin.ListGroupsResult#valid")]
64    pub fn valid(&self) -> KafkaFuture<Vec<GroupListing>> {
65        self.source.then_apply(|results: Vec<Result<GroupListing, Error>>| {
66            Ok(results.into_iter().filter_map(Result::ok).collect())
67        })
68    }
69
70    /// Returns a future which yields just the errors which occurred.
71    ///
72    /// If this future yields a non-empty collection, it is very likely that elements are missing
73    /// from the [`valid`](Self::valid) set.
74    ///
75    /// This future itself never fails with an error. In the event of an error, this future will
76    /// successfully yield a collection containing at least one error.
77    #[doc(alias = "org.apache.kafka.clients.admin.ListGroupsResult#errors")]
78    pub fn errors(&self) -> KafkaFuture<Vec<Error>> {
79        self.source.then_apply(|results: Vec<Result<GroupListing, Error>>| {
80            Ok(results.into_iter().filter_map(Result::err).collect())
81        })
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use crate::common::GroupType;
89
90    fn listing(id: &str) -> GroupListing {
91        GroupListing::new(id, Some(GroupType::Consumer), "consumer", None)
92    }
93
94    #[tokio::test]
95    async fn valid_and_errors_split() {
96        let source = KafkaFuture::completed_future(Ok(vec![
97            Ok(listing("g1")),
98            Err(Error::local_illegal_state("boom")),
99            Ok(listing("g2")),
100        ]));
101        let result = ListGroupsResult::new(source);
102        assert_eq!(result.valid().get().await.unwrap().len(), 2);
103        assert_eq!(result.errors().get().await.unwrap().len(), 1);
104        // all() fails with the first error.
105        assert!(result.all().get().await.is_err());
106    }
107
108    #[tokio::test]
109    async fn all_succeeds_when_no_errors() {
110        let source = KafkaFuture::completed_future(Ok(vec![Ok(listing("g1"))]));
111        let result = ListGroupsResult::new(source);
112        assert_eq!(result.all().get().await.unwrap(), vec![listing("g1")]);
113    }
114}