Skip to main content

confluent_kafka/common/
group_state.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 group state.
16//!
17//! Translated from `org.apache.kafka.common.GroupState`.
18
19use std::collections::HashSet;
20use std::fmt;
21
22use crate::common::GroupType;
23
24/// The group state.
25///
26/// The following table shows the correspondence between the group states and
27/// types.
28///
29/// | State | Classic group | Consumer group | Share group | Streams group |
30/// | --- | --- | --- | --- | --- |
31/// | UNKNOWN | Yes | Yes | Yes | Yes |
32/// | PREPARING_REBALANCE | Yes | Yes |  |  |
33/// | COMPLETING_REBALANCE | Yes | Yes |  |  |
34/// | STABLE | Yes | Yes | Yes | Yes |
35/// | DEAD | Yes | Yes | Yes | Yes |
36/// | EMPTY | Yes | Yes | Yes | Yes |
37/// | ASSIGNING |  | Yes |  | Yes |
38/// | RECONCILING |  | Yes |  | Yes |
39/// | NOT_READY |  |  |  | Yes |
40#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
41#[non_exhaustive]
42#[doc(alias = "org.apache.kafka.common.GroupState")]
43pub enum GroupState {
44    /// An unrecognized group state (e.g. a state newer than this client).
45    Unknown,
46    /// The group is preparing to rebalance.
47    PreparingRebalance,
48    /// The group is completing a rebalance.
49    CompletingRebalance,
50    /// The group is stable.
51    Stable,
52    /// The group is dead.
53    Dead,
54    /// The group is empty.
55    Empty,
56    /// The group is assigning (consumer/streams groups only).
57    Assigning,
58    /// The group is reconciling (consumer/streams groups only).
59    Reconciling,
60    /// The group is not ready (streams groups only).
61    NotReady,
62}
63
64impl GroupState {
65    /// Returns the name of this enum constant, exactly as declared in Java
66    /// (`PREPARING_REBALANCE`).
67    ///
68    /// Java's `Enum.name()`, which `GroupState` inherits. The text Java's
69    /// `toString()` returns (`PreparingRebalance`, the text the broker sends and
70    /// [`parse`](Self::parse) reads) is this type's [`Display`](fmt::Display).
71    #[doc(alias = "org.apache.kafka.common.GroupState#name")]
72    pub fn name(&self) -> &'static str {
73        match self {
74            Self::Unknown => "UNKNOWN",
75            Self::PreparingRebalance => "PREPARING_REBALANCE",
76            Self::CompletingRebalance => "COMPLETING_REBALANCE",
77            Self::Stable => "STABLE",
78            Self::Dead => "DEAD",
79            Self::Empty => "EMPTY",
80            Self::Assigning => "ASSIGNING",
81            Self::Reconciling => "RECONCILING",
82            Self::NotReady => "NOT_READY",
83        }
84    }
85
86    /// Case-insensitive group state lookup by string name.
87    ///
88    /// # Arguments
89    ///
90    /// - `name` - the state name
91    ///
92    /// # Returns
93    ///
94    /// The state, `Unknown` if unrecognized.
95    #[doc(alias = "org.apache.kafka.common.GroupState#parse")]
96    pub fn parse(name: &str) -> Self {
97        match name.to_uppercase().as_str() {
98            "UNKNOWN" => Self::Unknown,
99            "PREPARINGREBALANCE" => Self::PreparingRebalance,
100            "COMPLETINGREBALANCE" => Self::CompletingRebalance,
101            "STABLE" => Self::Stable,
102            "DEAD" => Self::Dead,
103            "EMPTY" => Self::Empty,
104            "ASSIGNING" => Self::Assigning,
105            "RECONCILING" => Self::Reconciling,
106            "NOTREADY" => Self::NotReady,
107            _ => Self::Unknown,
108        }
109    }
110
111    /// Returns the set of group states applicable to the given group type.
112    ///
113    /// # Arguments
114    ///
115    /// - `group_type` - the group type
116    ///
117    /// # Panics
118    ///
119    /// Panics with `Group type not known` if `group_type` is
120    /// [`GroupType::Unknown`], where Java throws
121    /// `IllegalArgumentException("Group type not known")`. A group listing reports `Unknown` for a type
122    /// this client does not know, such as one a newer broker added, so check
123    /// for it before calling. The lookup otherwise always succeeds, so its
124    /// signature stays a plain `HashSet`.
125    #[doc(alias = "org.apache.kafka.common.GroupState#groupStatesForType")]
126    pub fn group_states_for_type(group_type: GroupType) -> HashSet<GroupState> {
127        match group_type {
128            GroupType::Classic => [
129                Self::PreparingRebalance,
130                Self::CompletingRebalance,
131                Self::Stable,
132                Self::Dead,
133                Self::Empty,
134            ]
135            .into_iter()
136            .collect(),
137            GroupType::Consumer => [
138                Self::PreparingRebalance,
139                Self::CompletingRebalance,
140                Self::Stable,
141                Self::Dead,
142                Self::Empty,
143                Self::Assigning,
144                Self::Reconciling,
145            ]
146            .into_iter()
147            .collect(),
148            GroupType::Streams => [
149                Self::Stable,
150                Self::Dead,
151                Self::Empty,
152                Self::Assigning,
153                Self::Reconciling,
154                Self::NotReady,
155            ]
156            .into_iter()
157            .collect(),
158            GroupType::Share => [Self::Stable, Self::Dead, Self::Empty].into_iter().collect(),
159            GroupType::Unknown => panic!("Group type not known"),
160        }
161    }
162}
163
164/// Java's `toString()`, which returns the private `name` field: the text
165/// (`PreparingRebalance`) the broker sends and [`GroupState::parse`] reads, not
166/// the constant name [`GroupState::name`] returns (the constants of `GroupState`).
167impl fmt::Display for GroupState {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.write_str(match self {
170            Self::Unknown => "Unknown",
171            Self::PreparingRebalance => "PreparingRebalance",
172            Self::CompletingRebalance => "CompletingRebalance",
173            Self::Stable => "Stable",
174            Self::Dead => "Dead",
175            Self::Empty => "Empty",
176            Self::Assigning => "Assigning",
177            Self::Reconciling => "Reconciling",
178            Self::NotReady => "NotReady",
179        })
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn parse_is_case_insensitive() {
189        assert_eq!(GroupState::parse("stable"), GroupState::Stable);
190        assert_eq!(GroupState::parse("STABLE"), GroupState::Stable);
191        assert_eq!(GroupState::parse("PreparingRebalance"), GroupState::PreparingRebalance);
192        assert_eq!(GroupState::parse("NotReady"), GroupState::NotReady);
193    }
194
195    #[test]
196    fn parse_unknown_returns_unknown() {
197        assert_eq!(GroupState::parse(""), GroupState::Unknown);
198        assert_eq!(GroupState::parse("bogus"), GroupState::Unknown);
199    }
200
201    /// New test, no Java original (Java has no `GroupStateTest`): every
202    /// constant's `name()` is Java's `Enum.name()` and its `Display` is Java's
203    /// `toString()` (`GroupState#toString`), and `parse` reads the `toString()` text back.
204    #[test]
205    fn name_and_display_match_java_for_every_constant() {
206        for (state, name, display) in [
207            (GroupState::Unknown, "UNKNOWN", "Unknown"),
208            (GroupState::PreparingRebalance, "PREPARING_REBALANCE", "PreparingRebalance"),
209            (GroupState::CompletingRebalance, "COMPLETING_REBALANCE", "CompletingRebalance"),
210            (GroupState::Stable, "STABLE", "Stable"),
211            (GroupState::Dead, "DEAD", "Dead"),
212            (GroupState::Empty, "EMPTY", "Empty"),
213            (GroupState::Assigning, "ASSIGNING", "Assigning"),
214            (GroupState::Reconciling, "RECONCILING", "Reconciling"),
215            (GroupState::NotReady, "NOT_READY", "NotReady"),
216        ] {
217            assert_eq!(state.name(), name);
218            assert_eq!(state.to_string(), display);
219            assert_eq!(GroupState::parse(&state.to_string()), state);
220        }
221    }
222
223    /// New test, no Java original: Java's `parse` looks the upper-cased text up
224    /// among the upper-cased `toString()` texts (`GroupState#parse`), so a
225    /// constant name with an underscore is not found and parses as `UNKNOWN`.
226    #[test]
227    fn parse_does_not_read_constant_names_with_an_underscore() {
228        assert_eq!(GroupState::parse("PREPARING_REBALANCE"), GroupState::Unknown);
229        assert_eq!(GroupState::parse("COMPLETING_REBALANCE"), GroupState::Unknown);
230        assert_eq!(GroupState::parse("NOT_READY"), GroupState::Unknown);
231        assert_eq!(GroupState::parse(GroupState::Stable.name()), GroupState::Stable);
232    }
233
234    #[test]
235    fn group_states_for_classic() {
236        let states = GroupState::group_states_for_type(GroupType::Classic);
237        assert_eq!(states.len(), 5);
238        assert!(states.contains(&GroupState::PreparingRebalance));
239        assert!(states.contains(&GroupState::Empty));
240        assert!(!states.contains(&GroupState::Assigning));
241    }
242
243    #[test]
244    fn group_states_for_consumer() {
245        let states = GroupState::group_states_for_type(GroupType::Consumer);
246        assert_eq!(states.len(), 7);
247        assert!(states.contains(&GroupState::Assigning));
248        assert!(states.contains(&GroupState::Reconciling));
249        assert!(!states.contains(&GroupState::NotReady));
250    }
251
252    #[test]
253    fn group_states_for_streams() {
254        let states = GroupState::group_states_for_type(GroupType::Streams);
255        assert_eq!(states.len(), 6);
256        assert!(states.contains(&GroupState::NotReady));
257        assert!(!states.contains(&GroupState::PreparingRebalance));
258    }
259
260    #[test]
261    fn group_states_for_share() {
262        let states = GroupState::group_states_for_type(GroupType::Share);
263        assert_eq!(states.len(), 3);
264        assert!(states.contains(&GroupState::Stable));
265    }
266
267    #[test]
268    #[should_panic(expected = "Group type not known")]
269    fn group_states_for_unknown_panics() {
270        GroupState::group_states_for_type(GroupType::Unknown);
271    }
272}