Skip to main content

confluent_kafka/admin/
alter_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::alter_consumer_group_offsets`.
16
17use std::collections::HashMap;
18
19use crate::common::protocol::Errors;
20use crate::common::{Error, KafkaFuture, TopicPartition};
21
22/// The per-partition commit errors carried by the underlying future.
23type PartitionErrors = HashMap<TopicPartition, Errors>;
24
25/// The result of `Admin::alter_consumer_group_offsets`.
26#[derive(Clone, Debug)]
27#[doc(alias = "org.apache.kafka.clients.admin.AlterConsumerGroupOffsetsResult")]
28pub struct AlterConsumerGroupOffsetsResult {
29    future: KafkaFuture<PartitionErrors>,
30}
31
32impl AlterConsumerGroupOffsetsResult {
33    /// Creates a result wrapping the single group's per-partition-error future.
34    #[doc(alias = "org.apache.kafka.clients.admin.AlterConsumerGroupOffsetsResult#AlterConsumerGroupOffsetsResult")]
35    pub(crate) fn new(future: KafkaFuture<PartitionErrors>) -> Self {
36        Self { future }
37    }
38
39    /// Returns a future which can be used to check the result for a given
40    /// partition.
41    ///
42    /// # Arguments
43    ///
44    /// - `partition` - the partition to check
45    ///
46    /// # Errors
47    ///
48    /// The returned future completes with:
49    /// - `Error::is_local_illegal_argument_error` if the partition was not part of
50    ///   the alter request;
51    /// - the partition's own error, if its commit failed.
52    #[doc(alias = "org.apache.kafka.clients.admin.AlterConsumerGroupOffsetsResult#partitionResult")]
53    pub fn partition_result(&self, partition: &TopicPartition) -> KafkaFuture<()> {
54        let partition = partition.clone();
55        self.future.then_apply(
56            move |topic_partitions: PartitionErrors| match topic_partitions.get(&partition) {
57                None => Err(Error::local_illegal_argument(format!(
58                    "Alter offset for partition \"{partition}\" was not attempted"
59                ))),
60                Some(&Errors::None) => Ok(()),
61                Some(&error) => Err(Error::new(error)),
62            },
63        )
64    }
65
66    /// Returns a future which succeeds if all the alter offsets succeed.
67    #[doc(alias = "org.apache.kafka.clients.admin.AlterConsumerGroupOffsetsResult#all")]
68    pub fn all(&self) -> KafkaFuture<()> {
69        self.future.then_apply(|topic_partition_errors: PartitionErrors| {
70            let mut partitions_failed: Vec<&TopicPartition> = topic_partition_errors
71                .iter()
72                .filter(|(_, error)| **error != Errors::None)
73                .map(|(tp, _)| tp)
74                .collect();
75            for &error in topic_partition_errors.values() {
76                if error != Errors::None {
77                    // Sort only when reporting, for a stable message (Java relies on
78                    // the map's list order, which is unspecified anyway).
79                    partitions_failed.sort_by_key(|tp| (tp.topic().to_string(), tp.partition()));
80                    let list = partitions_failed.iter().map(|tp| tp.to_string()).collect::<Vec<_>>().join(", ");
81                    return Err(Error::with_message(
82                        error,
83                        format!("Failed altering group offsets for the following partitions: [{list}]"),
84                    ));
85                }
86            }
87            Ok(())
88        })
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::common::internals::KafkaFutureImpl;
96
97    fn t0p0() -> TopicPartition {
98        TopicPartition::new("foo", 0)
99    }
100
101    fn t0p1() -> TopicPartition {
102        TopicPartition::new("bar", 0)
103    }
104
105    #[tokio::test]
106    async fn all_and_partition_result_succeed_when_no_errors() {
107        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
108        handle.complete(HashMap::from([(t0p0(), Errors::None), (t0p1(), Errors::None)]));
109        let result = AlterConsumerGroupOffsetsResult::new(handle.future());
110        assert_eq!(result.all().get().await.unwrap(), ());
111        assert_eq!(result.partition_result(&t0p0()).get().await.unwrap(), ());
112    }
113
114    #[tokio::test]
115    async fn partition_result_not_attempted_is_illegal_argument() {
116        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
117        handle.complete(HashMap::from([(t0p0(), Errors::None)]));
118        let result = AlterConsumerGroupOffsetsResult::new(handle.future());
119        let err = result
120            .partition_result(&TopicPartition::new("absent", 0))
121            .get()
122            .await
123            .unwrap_err();
124        assert!(matches!(err, Error::LocalIllegalArgument(_)));
125    }
126
127    #[tokio::test]
128    async fn partition_error_surfaces_in_partition_result_and_all() {
129        let handle: KafkaFutureImpl<PartitionErrors> = KafkaFutureImpl::new();
130        handle.complete(HashMap::from([
131            (t0p0(), Errors::None),
132            (t0p1(), Errors::UnknownTopicOrPartition),
133        ]));
134        let result = AlterConsumerGroupOffsetsResult::new(handle.future());
135        assert_eq!(result.partition_result(&t0p0()).get().await.unwrap(), ());
136        assert_eq!(
137            result.partition_result(&t0p1()).get().await.unwrap_err().error(),
138            Errors::UnknownTopicOrPartition
139        );
140        assert_eq!(result.all().get().await.unwrap_err().error(), Errors::UnknownTopicOrPartition);
141    }
142}