Skip to main content

confluent_kafka/admin/
list_transactions_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_transactions`.
16
17use std::collections::HashMap;
18
19use crate::admin::TransactionListing;
20use crate::common::KafkaFuture;
21use crate::common::internals::KafkaFutureImpl;
22
23/// The (top-level) future value: a map from broker id to that broker's listing
24/// future, produced once the broker list is discovered.
25type BrokerFutures = HashMap<i32, KafkaFuture<Vec<TransactionListing>>>;
26
27/// The result of `Admin::list_transactions`.
28// The wrapped future completes when the broker list is discovered, yielding a map from broker id
29// to that broker's per-request future (mirroring Java's `KafkaFuture<Map<Integer,
30// KafkaFutureImpl<Collection<TransactionListing>>>>`).
31#[derive(Clone, Debug)]
32#[doc(alias = "org.apache.kafka.clients.admin.ListTransactionsResult")]
33pub struct ListTransactionsResult {
34    future: KafkaFuture<BrokerFutures>,
35}
36
37impl ListTransactionsResult {
38    /// Creates a result wrapping the top-level broker-discovery future.
39    #[doc(alias = "org.apache.kafka.clients.admin.ListTransactionsResult#ListTransactionsResult")]
40    pub(crate) fn new(future: KafkaFuture<BrokerFutures>) -> Self {
41        Self { future }
42    }
43
44    /// Get all transaction listings. If any of the underlying requests fail,
45    /// the returned future also fails with the first encountered error.
46    ///
47    /// # Returns
48    ///
49    /// A future containing the collection of transaction listings. The future completes when all
50    /// transaction listings are available and fails after any non-retriable error.
51    #[doc(alias = "org.apache.kafka.clients.admin.ListTransactionsResult#all")]
52    pub fn all(&self) -> KafkaFuture<Vec<TransactionListing>> {
53        self.all_by_broker_id()
54            .then_apply(|map: HashMap<i32, Vec<TransactionListing>>| {
55                Ok(map.into_values().flatten().collect::<Vec<TransactionListing>>())
56            })
57    }
58
59    /// Get a future returning the per-broker listing futures. Useful for a
60    /// partial listing or more granular error details.
61    ///
62    /// # Returns
63    ///
64    /// A future containing a map of futures by broker which complete individually when their
65    /// respective transaction listings are available. The top-level future returned from this
66    /// method may fail if the admin client is unable to lookup the available brokers in the
67    /// cluster.
68    #[doc(alias = "org.apache.kafka.clients.admin.ListTransactionsResult#byBrokerId")]
69    pub fn by_broker_id(&self) -> KafkaFuture<BrokerFutures> {
70        self.future.clone()
71    }
72
73    /// Get all transaction listings keyed by the broker id currently managing
74    /// them. If any underlying request fails, the returned future also fails.
75    ///
76    /// # Returns
77    ///
78    /// A future containing a map from the broker ID to the transactions hosted by that broker
79    /// respectively. This future completes when all transaction listings are available and fails
80    /// after any non-retriable error.
81    #[doc(alias = "org.apache.kafka.clients.admin.ListTransactionsResult#allByBrokerId")]
82    pub fn all_by_broker_id(&self) -> KafkaFuture<HashMap<i32, Vec<TransactionListing>>> {
83        let all = KafkaFutureImpl::new();
84        let completer = all.clone();
85        self.future.on_complete(move |broker_futures| match broker_futures {
86            Err(error) => _ = completer.complete_with_error(error.clone()),
87            Ok(broker_futures) => {
88                let listings = KafkaFuture::join_map(broker_futures.clone().into_iter().collect());
89                listings.on_complete(move |listings| match listings {
90                    Ok(listings) => _ = completer.complete(listings.clone()),
91                    Err(error) => _ = completer.complete_with_error(error.clone()),
92                });
93            },
94        });
95        all.future()
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::admin::TransactionState;
103    use crate::common::Error;
104    use crate::common::internals::KafkaFutureImpl;
105    use std::collections::HashSet;
106
107    fn listing(id: &str, producer_id: i64, state: TransactionState) -> TransactionListing {
108        TransactionListing::new(id, producer_id, state)
109    }
110
111    // Mirrors `ListTransactionsResultTest.testAllFuturesFailIfLookupFails`.
112    #[tokio::test]
113    async fn all_futures_fail_if_lookup_fails() {
114        let top: KafkaFutureImpl<BrokerFutures> = KafkaFutureImpl::new();
115        let result = ListTransactionsResult::new(top.future());
116        top.complete_with_error(Error::new(crate::common::protocol::Errors::UnknownServerError));
117        assert!(result.all().get().await.is_err());
118        assert!(result.all_by_broker_id().get().await.is_err());
119        assert!(result.by_broker_id().get().await.is_err());
120    }
121
122    // Mirrors `ListTransactionsResultTest.testAllFuturesSucceed`.
123    #[tokio::test]
124    async fn all_futures_succeed() {
125        let top: KafkaFutureImpl<BrokerFutures> = KafkaFutureImpl::new();
126        let result = ListTransactionsResult::new(top.future());
127
128        let f1: KafkaFutureImpl<Vec<TransactionListing>> = KafkaFutureImpl::new();
129        let f2: KafkaFutureImpl<Vec<TransactionListing>> = KafkaFutureImpl::new();
130        top.complete(HashMap::from([(1, f1.future()), (2, f2.future())]));
131
132        let broker1 = vec![
133            listing("foo", 12345, TransactionState::Ongoing),
134            listing("bar", 98765, TransactionState::PrepareAbort),
135        ];
136        f1.complete(broker1.clone());
137        let broker2 = vec![listing("baz", 13579, TransactionState::CompleteCommit)];
138        f2.complete(broker2.clone());
139
140        let by_broker = result.by_broker_id().get().await.unwrap();
141        assert_eq!(by_broker.keys().copied().collect::<HashSet<_>>(), HashSet::from([1, 2]));
142        assert_eq!(by_broker[&1].get().await.unwrap(), broker1);
143        assert_eq!(by_broker[&2].get().await.unwrap(), broker2);
144
145        let all_by_broker = result.all_by_broker_id().get().await.unwrap();
146        assert_eq!(all_by_broker[&1], broker1);
147        assert_eq!(all_by_broker[&2], broker2);
148
149        let mut all_expected: HashSet<TransactionListing> = HashSet::new();
150        all_expected.extend(broker1);
151        all_expected.extend(broker2);
152        assert_eq!(
153            result.all().get().await.unwrap().into_iter().collect::<HashSet<_>>(),
154            all_expected
155        );
156    }
157
158    // Mirrors `ListTransactionsResultTest.testPartialFailure`.
159    #[tokio::test]
160    async fn partial_failure() {
161        let top: KafkaFutureImpl<BrokerFutures> = KafkaFutureImpl::new();
162        let result = ListTransactionsResult::new(top.future());
163
164        let f1: KafkaFutureImpl<Vec<TransactionListing>> = KafkaFutureImpl::new();
165        let f2: KafkaFutureImpl<Vec<TransactionListing>> = KafkaFutureImpl::new();
166        top.complete(HashMap::from([(1, f1.future()), (2, f2.future())]));
167
168        let broker1 = vec![listing("foo", 12345, TransactionState::Ongoing)];
169        f1.complete(broker1.clone());
170        f2.complete_with_error(Error::new(crate::common::protocol::Errors::UnknownServerError));
171
172        let by_broker = result.by_broker_id().get().await.unwrap();
173        assert_eq!(by_broker.keys().copied().collect::<HashSet<_>>(), HashSet::from([1, 2]));
174        assert_eq!(by_broker[&1].get().await.unwrap(), broker1);
175
176        assert!(result.all().get().await.is_err());
177        assert!(result.all_by_broker_id().get().await.is_err());
178        assert!(by_broker[&2].get().await.is_err());
179    }
180}