confluent_kafka/consumer/consumer_group_metadata.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//! Metadata containing consumer group information.
16//!
17//! Translated from `org.apache.kafka.clients.consumer.ConsumerGroupMetadata`.
18
19use std::fmt;
20
21/// `JoinGroupRequest.UNKNOWN_GENERATION_ID` from Java's request module.
22///
23/// NOTE: a later phase will wire this to the generated `JoinGroupRequest`
24/// constant once the consumer membership translation lands; for Phase 1 we
25/// hardcode the value with a comment pointing to the Java source.
26#[cfg(test)]
27const UNKNOWN_GENERATION_ID: i32 = -1;
28
29/// `JoinGroupRequest.UNKNOWN_MEMBER_ID` from Java's request module.
30///
31/// NOTE: a later phase will wire this to the generated `JoinGroupRequest`
32/// constant once the consumer membership translation lands; for Phase 1 we
33/// hardcode the value (empty string) with a comment pointing to the Java
34/// source.
35#[cfg(test)]
36const UNKNOWN_MEMBER_ID: &str = "";
37
38/// A metadata struct containing the consumer group information.
39///
40/// Note: Any change to this class is considered public and requires a KIP.
41///
42/// # Translation notes
43///
44/// A trait, as in Kafka 5.0: see
45/// [`Consumer::group_metadata`](super::Consumer::group_metadata).
46// Java has deprecated both public constructors since 4.2
47// (`@Deprecated(since = "4.2", forRemoval = true)`): "please use
48// `KafkaConsumer#groupMetadata()` instead. This class will be an interface in
49// Kafka 5.0." The Rust client translates the class directly in its 5.0 shape,
50// a trait, so the deprecated constructors are never public. The trait is
51// dyn-compatible, so `send_offsets_to_transaction` accepts the metadata of any
52// consumer implementation, including a future classic-protocol one.
53// `Display` on `dyn ConsumerGroupMetadata` renders Java's `toString()`.
54#[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadata")]
55pub trait ConsumerGroupMetadata: Send + Sync + fmt::Debug + 'static {
56 /// The consumer group ID.
57 ///
58 /// # Returns
59 ///
60 /// The group ID
61 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadata#groupId")]
62 fn group_id(&self) -> &str;
63
64 /// The current generation ID, or `-1` (`UNKNOWN_GENERATION_ID`) if unknown.
65 ///
66 /// # Returns
67 ///
68 /// The generation ID
69 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadata#generationId")]
70 fn generation_id(&self) -> i32;
71
72 /// The member ID, or an empty string (`UNKNOWN_MEMBER_ID`) if unknown.
73 ///
74 /// # Returns
75 ///
76 /// The member ID
77 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadata#memberId")]
78 fn member_id(&self) -> &str;
79
80 /// The group instance ID, if the consumer is a static member.
81 ///
82 /// # Returns
83 ///
84 /// The group instance ID, or empty if this is a dynamic member
85 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadata#groupInstanceId")]
86 fn group_instance_id(&self) -> Option<&str>;
87}
88
89impl fmt::Display for dyn ConsumerGroupMetadata {
90 // Matches Java's
91 // `String.format("GroupMetadata(groupId = %s, generationId = %d, memberId = %s, groupInstanceId = %s)", …)`
92 // where `groupInstanceId` is replaced with an empty string if absent.
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(
95 f,
96 "GroupMetadata(groupId = {}, generationId = {}, memberId = {}, groupInstanceId = {})",
97 self.group_id(),
98 self.generation_id(),
99 self.member_id(),
100 self.group_instance_id().unwrap_or("")
101 )
102 }
103}
104
105/// The crate's own [`ConsumerGroupMetadata`] implementation. It holds the four
106/// fields of Java's class; the consumers build it and the transaction manager
107/// snapshots into it.
108///
109/// Java has no such type, because `ConsumerGroupMetadata` is still a class
110/// there (DoD #7 deviation). Turning the class into a trait separates the
111/// public type from its data, and the data needs a holder. The struct and its
112/// constructors are `pub(crate)`, so the deprecated Java constructors never
113/// reach the public surface. `PartialEq` / `Hash` translate Java's `equals` /
114/// `hashCode`, which compare only instances of the same class.
115#[derive(Clone, Debug, PartialEq, Eq, Hash)]
116pub(crate) struct ConsumerGroupMetadataImpl {
117 group_id: String,
118 generation_id: i32,
119 member_id: String,
120 group_instance_id: Option<String>,
121}
122
123impl ConsumerGroupMetadataImpl {
124 /// Metadata for `group_id` with unknown generation and member ids.
125 ///
126 /// Corresponds to Java's `new ConsumerGroupMetadata(String)`. Only the
127 /// tests build it: Java deprecates that constructor, and the consumer
128 /// seeds its metadata through the four-argument form.
129 #[cfg(test)]
130 pub(crate) fn new(group_id: impl Into<String>) -> Self {
131 Self::with_generation_id_member_id_group_instance_id(group_id, UNKNOWN_GENERATION_ID, UNKNOWN_MEMBER_ID, None)
132 }
133
134 /// Metadata with all four fields.
135 ///
136 /// Corresponds to Java's four-argument constructor.
137 pub(crate) fn with_generation_id_member_id_group_instance_id(
138 group_id: impl Into<String>,
139 generation_id: i32,
140 member_id: impl Into<String>,
141 group_instance_id: Option<String>,
142 ) -> Self {
143 Self {
144 group_id: group_id.into(),
145 generation_id,
146 member_id: member_id.into(),
147 group_instance_id,
148 }
149 }
150
151 /// Copies the fields of any [`ConsumerGroupMetadata`] implementation.
152 ///
153 /// Java keeps the caller's reference. The fields are immutable, so an
154 /// owned copy is equivalent, and it lets the transaction manager hold the
155 /// metadata after the caller's borrow ends.
156 pub(crate) fn copy_of(group_metadata: &dyn ConsumerGroupMetadata) -> Self {
157 Self::with_generation_id_member_id_group_instance_id(
158 group_metadata.group_id(),
159 group_metadata.generation_id(),
160 group_metadata.member_id(),
161 group_metadata.group_instance_id().map(ToString::to_string),
162 )
163 }
164}
165
166impl ConsumerGroupMetadata for ConsumerGroupMetadataImpl {
167 fn group_id(&self) -> &str {
168 &self.group_id
169 }
170
171 fn generation_id(&self) -> i32 {
172 self.generation_id
173 }
174
175 fn member_id(&self) -> &str {
176 &self.member_id
177 }
178
179 fn group_instance_id(&self) -> Option<&str> {
180 self.group_instance_id.as_deref()
181 }
182}
183
184impl fmt::Display for ConsumerGroupMetadataImpl {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 fmt::Display::fmt(self as &dyn ConsumerGroupMetadata, f)
187 }
188}
189
190/// Translated from `org.apache.kafka.clients.consumer.ConsumerGroupMetadataTest`.
191///
192/// The Java constructors under test are deprecated, and the Rust client has
193/// no public ones, so the tests exercise the crate-internal
194/// [`ConsumerGroupMetadataImpl`] constructors that translate them.
195///
196/// Skipped tests:
197/// - `testInvalidGroupId`, `testInvalidMemberId`, `testInvalidInstanceId`
198/// — Java asserts `NullPointerException` for nullable arguments. In Rust
199/// the constructor takes `impl Into<String>` (non-null by the type
200/// system) and `Option<String>` for the instance ID (`None` is the
201/// "absent" sentinel). There is no equivalent runtime check to test.
202#[cfg(test)]
203mod tests {
204 use std::sync::Arc;
205
206 use super::*;
207
208 const GROUP_ID: &str = "group";
209
210 /// Translated from `ConsumerGroupMetadataTest.testAssignmentConstructor`.
211 #[test]
212 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadataTest#testAssignmentConstructor")]
213 fn test_assignment_constructor() {
214 let member_id = "member";
215 let generation_id = 2;
216 let group_instance_id = "instance";
217
218 let group_metadata = ConsumerGroupMetadataImpl::with_generation_id_member_id_group_instance_id(
219 GROUP_ID,
220 generation_id,
221 member_id,
222 Some(group_instance_id.to_string()),
223 );
224
225 assert_eq!(group_metadata.group_id(), GROUP_ID);
226 assert_eq!(group_metadata.generation_id(), generation_id);
227 assert_eq!(group_metadata.member_id(), member_id);
228 assert!(group_metadata.group_instance_id().is_some());
229 assert_eq!(group_metadata.group_instance_id(), Some(group_instance_id));
230 }
231
232 /// Translated from `ConsumerGroupMetadataTest.testGroupIdConstructor`.
233 ///
234 /// `JoinGroupRequest.UNKNOWN_GENERATION_ID = -1` and
235 /// `JoinGroupRequest.UNKNOWN_MEMBER_ID = ""` per the Java request module.
236 #[test]
237 #[doc(alias = "org.apache.kafka.clients.consumer.ConsumerGroupMetadataTest#testGroupIdConstructor")]
238 fn test_group_id_constructor() {
239 let group_metadata = ConsumerGroupMetadataImpl::new(GROUP_ID);
240
241 assert_eq!(group_metadata.group_id(), GROUP_ID);
242 assert_eq!(group_metadata.generation_id(), UNKNOWN_GENERATION_ID);
243 assert_eq!(group_metadata.member_id(), UNKNOWN_MEMBER_ID);
244 assert!(group_metadata.group_instance_id().is_none());
245 }
246
247 #[test]
248 fn test_display() {
249 let m = ConsumerGroupMetadataImpl::with_generation_id_member_id_group_instance_id(
250 "g",
251 2,
252 "member",
253 Some("instance".into()),
254 );
255 assert_eq!(
256 m.to_string(),
257 "GroupMetadata(groupId = g, generationId = 2, memberId = member, groupInstanceId = instance)"
258 );
259
260 let m = ConsumerGroupMetadataImpl::new("g");
261 // groupInstanceId rendered as empty string (matches Java)
262 assert_eq!(
263 m.to_string(),
264 "GroupMetadata(groupId = g, generationId = -1, memberId = , groupInstanceId = )"
265 );
266 }
267
268 /// The trait-object form a caller holds (`Consumer::group_metadata`'s
269 /// return type) renders the same `toString()`.
270 #[test]
271 fn test_display_through_trait_object() {
272 let m: Arc<dyn ConsumerGroupMetadata> =
273 Arc::new(ConsumerGroupMetadataImpl::with_generation_id_member_id_group_instance_id(
274 "g",
275 2,
276 "member",
277 Some("instance".into()),
278 ));
279 assert_eq!(
280 m.to_string(),
281 "GroupMetadata(groupId = g, generationId = 2, memberId = member, groupInstanceId = instance)"
282 );
283 }
284
285 /// `copy_of` preserves every field, including an absent instance id.
286 #[test]
287 fn test_copy_of() {
288 let with_instance =
289 ConsumerGroupMetadataImpl::with_generation_id_member_id_group_instance_id("g", 5, "m", Some("i".into()));
290 assert_eq!(ConsumerGroupMetadataImpl::copy_of(&with_instance), with_instance);
291 let without = ConsumerGroupMetadataImpl::new("g");
292 assert_eq!(ConsumerGroupMetadataImpl::copy_of(&without), without);
293 }
294}