Skip to main content

confluent_kafka/admin/
delete_consumer_group_offsets_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::delete_consumer_group_offsets`.
16
17use std::collections::{HashMap, HashSet};
18
19use crate::common::protocol::Errors;
20use crate::common::{Error, KafkaFuture, TopicPartition};
21
22/// The per-partition delete errors carried by the underlying future.
23type PartitionErrors = HashMap<TopicPartition, Errors>;
24
25/// The result of `Admin::delete_consumer_group_offsets`.
26#[derive(Clone, Debug)]
27#[doc(alias = "org.apache.kafka.clients.admin.DeleteConsumerGroupOffsetsResult")]
28pub struct DeleteConsumerGroupOffsetsResult {
29    future: KafkaFuture<PartitionErrors>,
30    partitions: HashSet<TopicPartition>,
31}
32
33impl DeleteConsumerGroupOffsetsResult {
34    /// Creates a result wrapping the single group's per-partition-error future
35    /// and the set of partitions from the original request.
36    #[doc(alias = "org.apache.kafka.clients.admin.DeleteConsumerGroupOffsetsResult#DeleteConsumerGroupOffsetsResult")]
37    pub(crate) fn new(future: KafkaFuture<PartitionErrors>, partitions: HashSet<TopicPartition>) -> Self {
38        Self { future, partitions }
39    }
40
41    /// Returns a future which can be used to check the result for a given
42    /// partition.
43    ///
44    /// # Arguments
45    ///
46    /// - `partition` - the partition to check.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error answering `Error::is_local_illegal_argument_error` immediately if the
51    /// partition was not included in the original request. The returned future
52    /// fails if the deletion for the partition failed (or the partition is
53    /// missing from the response).
54    #[doc(alias = "org.apache.kafka.clients.admin.DeleteConsumerGroupOffsetsResult#partitionResult")]
55    pub fn partition_result(&self, partition: &TopicPartition) -> Result<KafkaFuture<()>, Error> {
56        if !self.partitions.contains(partition) {
57            return Err(Error::local_illegal_argument(format!(
58                "Partition {partition} was not included in the original request"
59            )));
60        }
61        let partition = partition.clone();
62        Ok(self
63            .future
64            .then_apply(move |topic_partitions| match sub_level_error(&topic_partitions, &partition) {
65                Some(error) => Err(error),
66                None => Ok(()),
67            }))
68    }
69
70    /// Returns a future which succeeds only if all the deletions succeed.
71    /// If not, the first partition error is returned.
72    #[doc(alias = "org.apache.kafka.clients.admin.DeleteConsumerGroupOffsetsResult#all")]
73    pub fn all(&self) -> KafkaFuture<()> {
74        // Sort for a stable "first error" (Java relies on set iteration order,
75        // which is unspecified anyway).
76        let mut partitions: Vec<TopicPartition> = self.partitions.iter().cloned().collect();
77        partitions.sort_by_key(|tp| (tp.topic().to_string(), tp.partition()));
78        self.future.then_apply(move |topic_partitions| {
79            for partition in &partitions {
80                if let Some(error) = sub_level_error(&topic_partitions, partition) {
81                    return Err(error);
82                }
83            }
84            Ok(())
85        })
86    }
87}
88
89/// Mirrors `KafkaAdminClient.getSubLevelError` specialised for the delete-offsets
90/// result: an absent partition yields the "not included in the response"
91/// `IllegalArgumentException`, a present partition yields its error (or `None`
92/// when the error is `NONE`).
93fn sub_level_error(partition_level_errors: &PartitionErrors, partition: &TopicPartition) -> Option<Error> {
94    match partition_level_errors.get(partition) {
95        None => Some(Error::local_illegal_argument(format!(
96            "Offset deletion result for partition \"{partition}\" was not included in the response"
97        ))),
98        Some(&Errors::None) => None,
99        Some(&error) => Some(Error::new(error)),
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::common::internals::KafkaFutureImpl;
107
108    fn tp_zero() -> TopicPartition {
109        TopicPartition::new("topic", 0)
110    }
111
112    fn tp_one() -> TopicPartition {
113        TopicPartition::new("topic", 1)
114    }
115
116    fn partitions() -> HashSet<TopicPartition> {
117        HashSet::from([tp_zero(), tp_one()])
118    }
119
120    /// Translated from `testTopLevelErrorConstructor`.
121    #[tokio::test]
122    async fn top_level_error_constructor() {
123        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
124        handle.complete_with_error(Error::group_authorization("group"));
125        let result = DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions());
126        assert!(matches!(result.all().get().await.unwrap_err(), Error::GroupAuthorization(_)));
127    }
128
129    /// Translated from `testPartitionLevelErrorConstructor`.
130    #[tokio::test]
131    async fn partition_level_error_constructor() {
132        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
133        handle.complete(HashMap::from([
134            (tp_zero(), Errors::None),
135            (tp_one(), Errors::UnknownTopicOrPartition),
136        ]));
137        let result = DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions());
138        assert_eq!(result.all().get().await.unwrap_err().error(), Errors::UnknownTopicOrPartition);
139        assert_eq!(result.partition_result(&tp_zero()).unwrap().get().await.unwrap(), ());
140        assert_eq!(
141            result.partition_result(&tp_one()).unwrap().get().await.unwrap_err().error(),
142            Errors::UnknownTopicOrPartition
143        );
144    }
145
146    /// Translated from `testPartitionMissingInResponseErrorConstructor`.
147    #[tokio::test]
148    async fn partition_missing_in_response_error_constructor() {
149        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
150        handle.complete(HashMap::from([(tp_zero(), Errors::None)]));
151        let result = DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions());
152        assert!(matches!(result.all().get().await.unwrap_err(), Error::LocalIllegalArgument(_)));
153        assert_eq!(result.partition_result(&tp_zero()).unwrap().get().await.unwrap(), ());
154        assert!(matches!(
155            result.partition_result(&tp_one()).unwrap().get().await.unwrap_err(),
156            Error::LocalIllegalArgument(_)
157        ));
158    }
159
160    /// Translated from `testPartitionMissingInRequestErrorConstructor` (the
161    /// synchronous `IllegalArgumentException` when asking about a partition not
162    /// in the original request).
163    #[tokio::test]
164    async fn partition_missing_in_request_error_constructor() {
165        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
166        handle.complete(HashMap::from([
167            (tp_zero(), Errors::None),
168            (tp_one(), Errors::UnknownTopicOrPartition),
169        ]));
170        let result = DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions());
171        assert!(matches!(
172            result.partition_result(&TopicPartition::new("invalid-topic", 0)),
173            Err(Error::LocalIllegalArgument(_))
174        ));
175    }
176
177    /// Translated from `testNoErrorConstructor`.
178    #[tokio::test]
179    async fn no_error_constructor() {
180        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
181        handle.complete(HashMap::from([(tp_zero(), Errors::None), (tp_one(), Errors::None)]));
182        let result = DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions());
183        assert_eq!(result.all().get().await.unwrap(), ());
184        assert_eq!(result.partition_result(&tp_zero()).unwrap().get().await.unwrap(), ());
185        assert_eq!(result.partition_result(&tp_one()).unwrap().get().await.unwrap(), ());
186    }
187}