Skip to main content

confluent_kafka/consumer/
group_protocol.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 protocol used by the consumer.
16//!
17//! Translated from `org.apache.kafka.clients.consumer.GroupProtocol`.
18
19use std::fmt;
20use std::str::FromStr;
21
22use crate::common::Error;
23
24/// Enum representing the supported consumer group protocols.
25///
26/// - [`Classic`](Self::Classic) - The Classic consumer group protocol (pre
27///   KIP-848)
28/// - [`Consumer`](Self::Consumer) - The Consumer rebalance protocol (KIP-848)
29///
30/// # Translation notes
31///
32/// [`KafkaConsumer::new`](crate::consumer::KafkaConsumer::new) supports only
33/// [`Consumer`](Self::Consumer).
34#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35#[non_exhaustive]
36#[doc(alias = "org.apache.kafka.clients.consumer.GroupProtocol")]
37pub enum GroupProtocol {
38    /// Classic group protocol.
39    Classic,
40    /// Consumer group protocol (KIP-848).
41    Consumer,
42}
43
44impl GroupProtocol {
45    /// String representation of the group protocol.
46    ///
47    /// # Returns
48    ///
49    /// The upper-case name (e.g. `"CLASSIC"`).
50    #[doc(alias = "org.apache.kafka.clients.consumer.GroupProtocol#name")]
51    pub fn name(self) -> &'static str {
52        match self {
53            Self::Classic => "CLASSIC",
54            Self::Consumer => "CONSUMER",
55        }
56    }
57
58    /// Case-insensitive group protocol lookup by string name.
59    ///
60    /// # Arguments
61    ///
62    /// - `name` - The name of the group protocol
63    ///
64    /// # Returns
65    ///
66    /// The corresponding GroupProtocol
67    ///
68    /// # Errors
69    ///
70    /// - `Error::is_local_illegal_argument_error` If the name does not match any
71    ///   protocol
72    #[doc(alias = "org.apache.kafka.clients.consumer.GroupProtocol#of")]
73    pub fn of(name: &str) -> Result<Self, Error> {
74        match name.to_ascii_uppercase().as_str() {
75            "CLASSIC" => Ok(Self::Classic),
76            "CONSUMER" => Ok(Self::Consumer),
77            _ => Err(Error::local_illegal_argument(format!(
78                "No enum constant org.apache.kafka.clients.consumer.GroupProtocol.{name}"
79            ))),
80        }
81    }
82}
83
84impl fmt::Display for GroupProtocol {
85    // Lower-case representation matching Java's
86    // `toString().toLowerCase(Locale.ROOT)` pattern used in
87    // `ConsumerConfig.DEFAULT_GROUP_PROTOCOL`.
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(match self {
90            Self::Classic => "classic",
91            Self::Consumer => "consumer",
92        })
93    }
94}
95
96impl FromStr for GroupProtocol {
97    type Err = Error;
98
99    fn from_str(s: &str) -> Result<Self, Self::Err> {
100        Self::of(s)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn test_name() {
110        assert_eq!(GroupProtocol::Classic.name(), "CLASSIC");
111        assert_eq!(GroupProtocol::Consumer.name(), "CONSUMER");
112    }
113
114    #[test]
115    fn test_display_lowercase() {
116        assert_eq!(GroupProtocol::Classic.to_string(), "classic");
117        assert_eq!(GroupProtocol::Consumer.to_string(), "consumer");
118    }
119
120    #[test]
121    fn test_of_case_insensitive() {
122        assert_eq!(GroupProtocol::of("classic").unwrap(), GroupProtocol::Classic);
123        assert_eq!(GroupProtocol::of("CLASSIC").unwrap(), GroupProtocol::Classic);
124        assert_eq!(GroupProtocol::of("Classic").unwrap(), GroupProtocol::Classic);
125        assert_eq!(GroupProtocol::of("consumer").unwrap(), GroupProtocol::Consumer);
126        assert_eq!(GroupProtocol::of("CONSUMER").unwrap(), GroupProtocol::Consumer);
127        assert_eq!(GroupProtocol::of("Consumer").unwrap(), GroupProtocol::Consumer);
128    }
129
130    #[test]
131    fn test_of_invalid() {
132        let err = GroupProtocol::of("invalid").unwrap_err();
133        assert!(err.message().contains("GroupProtocol.invalid"), "got: {}", err.message());
134    }
135
136    #[test]
137    fn test_from_str_roundtrip() {
138        assert_eq!("classic".parse::<GroupProtocol>().unwrap(), GroupProtocol::Classic);
139        assert_eq!("consumer".parse::<GroupProtocol>().unwrap(), GroupProtocol::Consumer);
140    }
141}