Skip to main content

confluent_kafka/admin/
consumer_group_description.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//! A detailed description of a single consumer group in the cluster.
16
17use std::collections::BTreeSet;
18
19use crate::admin::MemberDescription;
20use crate::common::acl::AclOperation;
21use crate::common::{GroupState, GroupType, Node};
22
23/// A detailed description of a single consumer group in the cluster.
24// Note: Java's `@Deprecated(forRemoval = true)` constructors that accept a
25// `ConsumerGroupState`, and the deprecated `state()` accessor, are not
26// translated; use [`new`](Self::new) and [`group_state`](Self::group_state).
27#[derive(Clone, Debug, PartialEq, Eq, Hash)]
28#[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription")]
29pub struct ConsumerGroupDescription {
30    group_id: String,
31    is_simple_consumer_group: bool,
32    members: Vec<MemberDescription>,
33    partition_assignor: String,
34    group_type: GroupType,
35    group_state: GroupState,
36    coordinator: Option<Node>,
37    /// `Option` because Java's field is nullable: the admin client fills it
38    /// from `AdminUtils.validAclOperations`, which returns `null` when the broker
39    /// did not report the operations.
40    authorized_operations: Option<BTreeSet<AclOperation>>,
41    group_epoch: Option<i32>,
42    target_assignment_epoch: Option<i32>,
43}
44
45impl ConsumerGroupDescription {
46    /// Creates a consumer group description with all fields.
47    ///
48    /// # Arguments
49    ///
50    /// - `group_id` - the id of the consumer group.
51    /// - `is_simple_consumer_group` - whether the group is a simple consumer group.
52    /// - `members` - the members of the group.
53    /// - `partition_assignor` - the name of the partition assignor.
54    /// - `group_type` - the group protocol type.
55    /// - `group_state` - the group state.
56    /// - `coordinator` - the group coordinator, or `None` if not known.
57    /// - `authorized_operations` - the authorized operations for this group, or `None` if not
58    ///   known.
59    /// - `group_epoch` - the epoch of the group, or `None` for a classic group.
60    /// - `target_assignment_epoch` - the epoch of the target assignment, or `None` for a
61    ///   classic group.
62    #[expect(clippy::too_many_arguments)]
63    #[doc(
64        alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#ConsumerGroupDescription(String,boolean,Collection,String,GroupType,GroupState,Node,Set,Optional,Optional)"
65    )]
66    pub fn new(
67        group_id: impl Into<String>,
68        is_simple_consumer_group: bool,
69        members: Vec<MemberDescription>,
70        partition_assignor: impl Into<String>,
71        group_type: GroupType,
72        group_state: GroupState,
73        coordinator: Option<Node>,
74        authorized_operations: Option<BTreeSet<AclOperation>>,
75        group_epoch: Option<i32>,
76        target_assignment_epoch: Option<i32>,
77    ) -> Self {
78        Self {
79            group_id: group_id.into(),
80            is_simple_consumer_group,
81            members,
82            partition_assignor: partition_assignor.into(),
83            group_type,
84            group_state,
85            coordinator,
86            authorized_operations,
87            group_epoch,
88            target_assignment_epoch,
89        }
90    }
91
92    /// Returns the id of the consumer group.
93    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#groupId")]
94    pub fn group_id(&self) -> &str {
95        &self.group_id
96    }
97
98    /// Returns whether the consumer group is simple.
99    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#isSimpleConsumerGroup")]
100    pub fn is_simple_consumer_group(&self) -> bool {
101        self.is_simple_consumer_group
102    }
103
104    /// Returns the members of the consumer group.
105    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#members")]
106    pub fn members(&self) -> &[MemberDescription] {
107        &self.members
108    }
109
110    /// Returns the consumer group partition assignor.
111    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#partitionAssignor")]
112    pub fn partition_assignor(&self) -> &str {
113        &self.partition_assignor
114    }
115
116    /// Returns the group type.
117    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#type")]
118    pub fn r#type(&self) -> GroupType {
119        self.group_type
120    }
121
122    /// Returns the group state, or [`GroupState::Unknown`] if the state is too new for us to
123    /// parse.
124    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#groupState")]
125    pub fn group_state(&self) -> GroupState {
126        self.group_state
127    }
128
129    /// Returns the consumer group coordinator, or `None` if not known.
130    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#coordinator")]
131    pub fn coordinator(&self) -> Option<&Node> {
132        self.coordinator.as_ref()
133    }
134
135    /// Returns the authorized operations for this group, or `None` if that information is
136    /// not known.
137    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#authorizedOperations")]
138    pub fn authorized_operations(&self) -> Option<&BTreeSet<AclOperation>> {
139        self.authorized_operations.as_ref()
140    }
141
142    /// Returns the epoch of the consumer group. The optional is set to an integer if it is a
143    /// [`GroupType::Consumer`] group, and to `None` if it is a [`GroupType::Classic`] group.
144    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#groupEpoch")]
145    pub fn group_epoch(&self) -> Option<i32> {
146        self.group_epoch
147    }
148
149    /// Returns the epoch of the target assignment. The optional is set to an integer if it is a
150    /// [`GroupType::Consumer`] group, and to `None` if it is a [`GroupType::Classic`] group.
151    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescription#targetAssignmentEpoch")]
152    pub fn target_assignment_epoch(&self) -> Option<i32> {
153        self.target_assignment_epoch
154    }
155}
156
157impl std::fmt::Display for ConsumerGroupDescription {
158    /// Java's `toString()`: an absent coordinator, operation set or epoch
159    /// prints as `null`, and the operations as Java's `[A, B]`.
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        let members = self.members.iter().map(ToString::to_string).collect::<Vec<_>>().join(",");
162        let coordinator = self
163            .coordinator
164            .as_ref()
165            .map_or_else(|| "null".to_string(), ToString::to_string);
166        let operations = self.authorized_operations.as_ref().map_or_else(
167            || "null".to_string(),
168            |operations| {
169                format!(
170                    "[{}]",
171                    operations.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
172                )
173            },
174        );
175        let null_or = |epoch: Option<i32>| epoch.map_or_else(|| "null".to_string(), |e| e.to_string());
176        write!(
177            f,
178            "(groupId={}, isSimpleConsumerGroup={}, members={}, partitionAssignor={}, type={}, groupState={}, \
179             coordinator={}, authorizedOperations={}, groupEpoch={}, targetAssignmentEpoch={})",
180            self.group_id,
181            self.is_simple_consumer_group,
182            members,
183            self.partition_assignor,
184            self.group_type,
185            self.group_state,
186            coordinator,
187            operations,
188            null_or(self.group_epoch),
189            null_or(self.target_assignment_epoch),
190        )
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn to_string_follows_java() {
200        let description = ConsumerGroupDescription::new(
201            "g",
202            false,
203            Vec::new(),
204            "range",
205            GroupType::Consumer,
206            GroupState::Stable,
207            None,
208            Some(BTreeSet::from([AclOperation::Write, AclOperation::Read])),
209            Some(3),
210            None,
211        );
212        assert_eq!(
213            description.to_string(),
214            "(groupId=g, isSimpleConsumerGroup=false, members=, partitionAssignor=range, type=Consumer, \
215             groupState=Stable, coordinator=null, authorizedOperations=[READ, WRITE], groupEpoch=3, \
216             targetAssignmentEpoch=null)"
217        );
218    }
219
220    /// Translated from `ConsumerGroupDescriptionTest.testGroupState`.
221    #[test]
222    #[doc(alias = "org.apache.kafka.clients.admin.ConsumerGroupDescriptionTest#testGroupState")]
223    fn test_group_state() {
224        for group_state in [
225            GroupState::Unknown,
226            GroupState::PreparingRebalance,
227            GroupState::CompletingRebalance,
228            GroupState::Stable,
229            GroupState::Dead,
230            GroupState::Empty,
231            GroupState::Assigning,
232            GroupState::Reconciling,
233            GroupState::NotReady,
234        ] {
235            let description = ConsumerGroupDescription::new(
236                "groupId",
237                false,
238                Vec::new(),
239                "assignor",
240                GroupType::Consumer,
241                group_state,
242                None,
243                Some(BTreeSet::new()),
244                None,
245                None,
246            );
247            assert_eq!(description.group_state(), group_state);
248        }
249    }
250}