Skip to main content

confluent_kafka/admin/
fence_producers_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::fence_producers`.
16
17use std::collections::HashMap;
18
19use crate::common::utils::internals::ProducerIdAndEpoch;
20use crate::common::{Error, KafkaFuture};
21
22/// The result of `Admin::fence_producers`.
23// Java keys the per-producer futures by `CoordinatorKey`; since `CoordinatorKey` is an internal
24// (`pub(crate)`) type, the Rust result keys them by the transactional id string, following the
25// `DescribeConsumerGroupsResult` precedent.
26#[derive(Clone, Debug)]
27#[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult")]
28pub struct FenceProducersResult {
29    futures: HashMap<String, KafkaFuture<ProducerIdAndEpoch>>,
30}
31
32impl FenceProducersResult {
33    /// Creates a result from the per-transactional-id futures.
34    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#FenceProducersResult")]
35    pub(crate) fn new(futures: HashMap<String, KafkaFuture<ProducerIdAndEpoch>>) -> Self {
36        Self { futures }
37    }
38
39    /// Returns a map from transactional id to futures which can be used to check
40    /// the status of individual fencings.
41    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#fencedProducers")]
42    pub fn fenced_producers(&self) -> HashMap<String, KafkaFuture<()>> {
43        self.futures
44            .iter()
45            .map(|(id, f)| (id.clone(), f.then_apply(|_| Ok(()))))
46            .collect()
47    }
48
49    /// Returns a future that provides the producer id generated while
50    /// initializing the given transaction when the request completes.
51    ///
52    /// # Arguments
53    ///
54    /// - `transactional_id` - the transactional id of the transaction.
55    ///
56    /// # Errors
57    ///
58    /// Returns an error answering `Error::is_local_illegal_argument_error` if `transactional_id`
59    /// was not
60    /// included in the request.
61    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#producerId")]
62    pub fn producer_id(&self, transactional_id: &str) -> Result<KafkaFuture<i64>, Error> {
63        self.find_and_apply(transactional_id, |p| p.producer_id)
64    }
65
66    /// Returns a future that provides the epoch generated while initializing the
67    /// given transaction when the request completes.
68    ///
69    /// # Arguments
70    ///
71    /// - `transactional_id` - the transactional id of the transaction.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error answering `Error::is_local_illegal_argument_error` if `transactional_id`
76    /// was not
77    /// included in the request.
78    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#epochId")]
79    pub fn epoch_id(&self, transactional_id: &str) -> Result<KafkaFuture<i16>, Error> {
80        self.find_and_apply(transactional_id, |p| p.epoch)
81    }
82
83    /// Returns a future which succeeds only if all the producer fencings succeed.
84    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#all")]
85    pub fn all(&self) -> KafkaFuture<()> {
86        KafkaFuture::all_of(self.futures.values().cloned().collect())
87    }
88
89    /// Mirrors `FenceProducersResult.findAndApply`.
90    #[doc(alias = "org.apache.kafka.clients.admin.FenceProducersResult#findAndApply")]
91    fn find_and_apply<T, F>(&self, transactional_id: &str, followup: F) -> Result<KafkaFuture<T>, Error>
92    where
93        T: Clone + Send + Sync + 'static,
94        F: Fn(&ProducerIdAndEpoch) -> T + Send + Sync + 'static,
95    {
96        self.futures
97            .get(transactional_id)
98            .map(|future| future.then_apply(move |p| Ok(followup(&p))))
99            .ok_or_else(|| {
100                Error::local_illegal_argument(format!(
101                    "TransactionalId `{transactional_id}` was not included in the request"
102                ))
103            })
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::common::internals::KafkaFutureImpl;
111
112    #[tokio::test]
113    async fn producer_id_and_epoch_id_project_the_future() {
114        let h: KafkaFutureImpl<ProducerIdAndEpoch> = KafkaFutureImpl::new();
115        let result = FenceProducersResult::new(HashMap::from([("t".to_string(), h.future())]));
116        h.complete(ProducerIdAndEpoch::new(7, 57));
117        assert_eq!(result.producer_id("t").unwrap().get().await.unwrap(), 7);
118        assert_eq!(result.epoch_id("t").unwrap().get().await.unwrap(), 57);
119        assert_eq!(result.fenced_producers()["t"].get().await.unwrap(), ());
120        result.all().get().await.unwrap();
121    }
122
123    #[test]
124    fn projections_error_for_unknown_id() {
125        let result = FenceProducersResult::new(HashMap::new());
126        assert!(
127            result
128                .producer_id("t")
129                .unwrap_err()
130                .message()
131                .contains("was not included in the request")
132        );
133        assert!(
134            result
135                .epoch_id("t")
136                .unwrap_err()
137                .message()
138                .contains("was not included in the request")
139        );
140    }
141}