Skip to main content

confluent_kafka/admin/
classic_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 classic group in the cluster.
16
17use std::collections::BTreeSet;
18
19use crate::admin::MemberDescription;
20use crate::common::acl::AclOperation;
21use crate::common::{ClassicGroupState, Node};
22
23/// A detailed description of a single classic group in the cluster.
24#[derive(Clone, Debug, PartialEq, Eq, Hash)]
25#[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription")]
26pub struct ClassicGroupDescription {
27    group_id: String,
28    protocol: String,
29    protocol_data: String,
30    members: Vec<MemberDescription>,
31    state: ClassicGroupState,
32    coordinator: Option<Node>,
33    /// `Option` because Java's field is nullable (see
34    /// [`ConsumerGroupDescription`](crate::admin::ConsumerGroupDescription)).
35    authorized_operations: Option<BTreeSet<AclOperation>>,
36}
37
38impl ClassicGroupDescription {
39    /// Creates a classic group description with no authorized operations.
40    ///
41    /// Java's six-argument constructor passes `Set.of()`, an empty set rather than `None`, as
42    /// the authorized operations.
43    ///
44    /// # Arguments
45    ///
46    /// - `group_id` - the id of the classic group.
47    /// - `protocol` - the group protocol type.
48    /// - `protocol_data` - the group protocol data.
49    /// - `members` - the members of the group.
50    /// - `state` - the group state.
51    /// - `coordinator` - the group coordinator, or `None` if not known.
52    #[doc(
53        alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#ClassicGroupDescription(String,String,String,Collection,ClassicGroupState,Node)"
54    )]
55    pub fn new(
56        group_id: impl Into<String>,
57        protocol: impl Into<String>,
58        protocol_data: impl Into<String>,
59        members: Vec<MemberDescription>,
60        state: ClassicGroupState,
61        coordinator: Option<Node>,
62    ) -> Self {
63        Self::with_authorized_operations(
64            group_id,
65            protocol,
66            protocol_data,
67            members,
68            state,
69            coordinator,
70            Some(BTreeSet::new()),
71        )
72    }
73
74    /// Creates a classic group description with all fields.
75    ///
76    /// # Arguments
77    ///
78    /// - `group_id` - the id of the classic group.
79    /// - `protocol` - the group protocol type.
80    /// - `protocol_data` - the group protocol data.
81    /// - `members` - the members of the group.
82    /// - `state` - the group state.
83    /// - `coordinator` - the group coordinator, or `None` if not known.
84    /// - `authorized_operations` - the authorized operations for this group, or `None` if not
85    ///   known.
86    #[doc(
87        alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#ClassicGroupDescription(String,String,String,Collection,ClassicGroupState,Node,Set)"
88    )]
89    pub fn with_authorized_operations(
90        group_id: impl Into<String>,
91        protocol: impl Into<String>,
92        protocol_data: impl Into<String>,
93        members: Vec<MemberDescription>,
94        state: ClassicGroupState,
95        coordinator: Option<Node>,
96        authorized_operations: Option<BTreeSet<AclOperation>>,
97    ) -> Self {
98        Self {
99            group_id: group_id.into(),
100            protocol: protocol.into(),
101            protocol_data: protocol_data.into(),
102            members,
103            state,
104            coordinator,
105            authorized_operations,
106        }
107    }
108
109    /// Returns the id of the classic group.
110    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#groupId")]
111    pub fn group_id(&self) -> &str {
112        &self.group_id
113    }
114
115    /// Returns the group protocol type.
116    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#protocol")]
117    pub fn protocol(&self) -> &str {
118        &self.protocol
119    }
120
121    /// Returns the group protocol data. The meaning depends on the group protocol type. For a
122    /// classic consumer group, this is the partition assignor name. For a classic connect group,
123    /// this indicates which Connect protocols are enabled.
124    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#protocolData")]
125    pub fn protocol_data(&self) -> &str {
126        &self.protocol_data
127    }
128
129    /// Returns whether the group is a simple consumer group (empty protocol).
130    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#isSimpleConsumerGroup")]
131    pub fn is_simple_consumer_group(&self) -> bool {
132        self.protocol.is_empty()
133    }
134
135    /// Returns the members of the classic group.
136    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#members")]
137    pub fn members(&self) -> &[MemberDescription] {
138        &self.members
139    }
140
141    /// Returns the classic group state, or [`ClassicGroupState::Unknown`] if the state is too new
142    /// for us to parse.
143    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#state")]
144    pub fn state(&self) -> ClassicGroupState {
145        self.state
146    }
147
148    /// Returns the classic group coordinator, or `None` if not known.
149    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#coordinator")]
150    pub fn coordinator(&self) -> Option<&Node> {
151        self.coordinator.as_ref()
152    }
153
154    /// Returns the authorized operations for this group.
155    #[doc(alias = "org.apache.kafka.clients.admin.ClassicGroupDescription#authorizedOperations")]
156    pub fn authorized_operations(&self) -> Option<&BTreeSet<AclOperation>> {
157        self.authorized_operations.as_ref()
158    }
159}
160
161impl std::fmt::Display for ClassicGroupDescription {
162    /// Java's `toString()`: an absent coordinator or operation set prints as
163    /// `null`, and the operations as Java's `[A, B]`.
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        let members = self.members.iter().map(ToString::to_string).collect::<Vec<_>>().join(",");
166        let coordinator = self
167            .coordinator
168            .as_ref()
169            .map_or_else(|| "null".to_string(), ToString::to_string);
170        let operations = self.authorized_operations.as_ref().map_or_else(
171            || "null".to_string(),
172            |operations| {
173                format!(
174                    "[{}]",
175                    operations.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
176                )
177            },
178        );
179        write!(
180            f,
181            "(groupId={}, protocol='{}', protocolData={}, members={}, state={}, coordinator={}, \
182             authorizedOperations={})",
183            self.group_id, self.protocol, self.protocol_data, members, self.state, coordinator, operations,
184        )
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn to_string_follows_java() {
194        let d = ClassicGroupDescription::with_authorized_operations(
195            "g",
196            "consumer",
197            "range",
198            Vec::new(),
199            ClassicGroupState::Stable,
200            None,
201            None,
202        );
203        assert_eq!(
204            d.to_string(),
205            "(groupId=g, protocol='consumer', protocolData=range, members=, state=Stable, coordinator=null, \
206             authorizedOperations=null)"
207        );
208    }
209
210    #[test]
211    fn is_simple_consumer_group_when_protocol_empty() {
212        let d = ClassicGroupDescription::new("g", "", "", Vec::new(), ClassicGroupState::Empty, None);
213        assert!(d.is_simple_consumer_group());
214
215        let d = ClassicGroupDescription::new("g", "consumer", "range", Vec::new(), ClassicGroupState::Stable, None);
216        assert!(!d.is_simple_consumer_group());
217    }
218
219    /// New test, no Java original (Java has no `ClassicGroupDescriptionTest`):
220    /// the six-argument constructor is the seven-argument one with Java's
221    /// `Set.of()`, an empty set of authorized operations, not `null`
222    /// (the six-argument `ClassicGroupDescription` constructor).
223    #[test]
224    fn new_passes_an_empty_set_of_authorized_operations() {
225        let coordinator = Node::new(1, "localhost".to_string(), 9092);
226        let short = ClassicGroupDescription::new(
227            "g",
228            "consumer",
229            "range",
230            Vec::new(),
231            ClassicGroupState::Stable,
232            Some(coordinator.clone()),
233        );
234        assert_eq!(short.authorized_operations(), Some(&BTreeSet::new()));
235        assert_eq!(
236            short,
237            ClassicGroupDescription::with_authorized_operations(
238                "g",
239                "consumer",
240                "range",
241                Vec::new(),
242                ClassicGroupState::Stable,
243                Some(coordinator.clone()),
244                Some(BTreeSet::new()),
245            )
246        );
247        assert_ne!(
248            short,
249            ClassicGroupDescription::with_authorized_operations(
250                "g",
251                "consumer",
252                "range",
253                Vec::new(),
254                ClassicGroupState::Stable,
255                Some(coordinator),
256                None,
257            )
258        );
259    }
260}