krafka 0.14.0

A pure Rust, async-native Apache Kafka client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! AdminClient operation group: group_offsets.

use tracing::{debug, info, warn};

use crate::error::{KrafkaError, ProtocolErrorKind, Result};
use crate::protocol::{
    ApiKey, OffsetCommitRequest, OffsetCommitRequestPartition, OffsetCommitRequestTopic,
    OffsetCommitResponse, OffsetDeletePartitionRequest, OffsetDeleteRequest, OffsetDeleteResponse,
    OffsetDeleteTopicRequest, OffsetFetchRequest, OffsetFetchRequestTopic, OffsetFetchResponse,
    VersionedDecode, VersionedEncode, versions,
};

#[allow(clippy::wildcard_imports)]
use super::*;

impl AdminClient {
    /// Delete committed offsets for a consumer group.
    ///
    /// **This is a destructive operation** — deleted offsets cannot be
    /// recovered. The consumer group must be in the `Empty` state.
    ///
    /// The request is sent to the group coordinator.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let results = admin.delete_offsets(
    ///     "my-group",
    ///     &[("my-topic", &[0, 1, 2])],
    /// ).await?;
    /// ```
    pub async fn delete_consumer_group_offsets(
        &self,
        group_id: &str,
        topic_partitions: &[(&str, &[i32])],
    ) -> Result<OffsetDeleteResult> {
        self.check_not_closed()?;

        // Find the group coordinator.
        let coordinator = self.find_group_coordinator(group_id).await?;

        let topics = topic_partitions
            .iter()
            .map(|(name, partitions)| OffsetDeleteTopicRequest {
                name: (*name).to_string(),
                partitions: partitions
                    .iter()
                    .map(|&p| OffsetDeletePartitionRequest { partition_index: p })
                    .collect(),
            })
            .collect();

        let request = OffsetDeleteRequest {
            group_id: group_id.to_string(),
            topics,
        };

        let version = coordinator
            .negotiate_api_version(
                ApiKey::OffsetDelete,
                versions::OFFSET_DELETE_MAX,
                versions::OFFSET_DELETE_MIN,
            )
            .await
            .ok_or_else(|| {
                KrafkaError::protocol_kind(
                    ProtocolErrorKind::UnknownApiVersion,
                    "no mutually supported OffsetDelete API version",
                )
            })?;

        let response_bytes = coordinator
            .send_request(ApiKey::OffsetDelete, version, |buf| {
                request.encode_versioned(version, buf)
            })
            .await?;

        let mut buf = response_bytes;
        let response = OffsetDeleteResponse::decode_versioned(version, &mut buf)?;

        if !response.error_code.is_ok() {
            warn!("OffsetDelete top-level error: {:?}", response.error_code);
        }

        let topics = response
            .topics
            .into_iter()
            .map(|t| OffsetDeleteTopicResult {
                name: t.name,
                partitions: t
                    .partitions
                    .into_iter()
                    .map(|p| OffsetDeletePartitionResult {
                        partition_index: p.partition_index,
                        error: if p.error_code.is_ok() {
                            None
                        } else {
                            Some(format!("{:?}", p.error_code))
                        },
                    })
                    .collect(),
            })
            .collect::<Vec<_>>();

        info!("OffsetDelete completed for group {group_id}");

        Ok(OffsetDeleteResult {
            error: if response.error_code.is_ok() {
                None
            } else {
                Some(format!("{:?}", response.error_code))
            },
            topics,
        })
    }

    // ════════════════════════════════════════════════════════════════════
    // DescribeUserScramCredentials (API key 50)
    // ════════════════════════════════════════════════════════════════════

    /// Fetch committed offsets for a consumer group.
    ///
    /// Pass `topic_partitions` to fetch offsets for specific partitions,
    /// or `None` to fetch all committed offsets for the group.
    ///
    /// The request is sent to the group coordinator.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let offsets = admin
    ///     .describe_consumer_group_offsets("my-group", None)
    ///     .await?;
    /// for entry in &offsets {
    ///     println!("{}/{}: {}", entry.topic, entry.partition, entry.committed_offset);
    /// }
    /// ```
    pub async fn describe_consumer_group_offsets(
        &self,
        group_id: &str,
        topic_partitions: Option<&[(&str, &[i32])]>,
    ) -> Result<Vec<GroupOffsetEntry>> {
        self.check_not_closed()?;

        let coordinator = self.find_group_coordinator(group_id).await?;

        let topics = topic_partitions.map(|tps| {
            tps.iter()
                .map(|(name, partitions)| OffsetFetchRequestTopic {
                    name: (*name).to_string(),
                    topic_id: None,
                    partition_indexes: partitions.to_vec(),
                })
                .collect::<Vec<_>>()
        });

        let request = OffsetFetchRequest {
            group_id: group_id.to_string(),
            topics,
            require_stable: false,
            member_id: None,
            member_epoch: -1,
        };

        let version = coordinator
            .negotiate_api_version(
                ApiKey::OffsetFetch,
                versions::OFFSET_FETCH_MAX,
                versions::OFFSET_FETCH_MIN,
            )
            .await
            .ok_or_else(|| {
                KrafkaError::protocol_kind(
                    ProtocolErrorKind::UnknownApiVersion,
                    "no mutually supported OffsetFetch API version",
                )
            })?;

        let response_bytes = coordinator
            .send_request(ApiKey::OffsetFetch, version, |buf| {
                request.encode_versioned(version, buf)
            })
            .await?;

        let mut buf = response_bytes;
        let response = OffsetFetchResponse::decode_versioned(version, &mut buf)?;

        if !response.error_code.is_ok() {
            return Err(KrafkaError::protocol_kind(
                ProtocolErrorKind::Other,
                format!("OffsetFetch top-level error: {:?}", response.error_code),
            ));
        }

        let mut entries = Vec::new();
        for topic in response.topics {
            for partition in topic.partitions {
                entries.push(GroupOffsetEntry {
                    topic: topic.name.clone(),
                    partition: partition.partition_index,
                    committed_offset: partition.committed_offset,
                    metadata: partition.metadata,
                    error: if partition.error_code.is_ok() {
                        None
                    } else {
                        Some(format!("{:?}", partition.error_code))
                    },
                });
            }
        }

        debug!(
            "OffsetFetch for group {group_id}: {} entries",
            entries.len()
        );
        Ok(entries)
    }

    /// Alter committed offsets for a consumer group.
    ///
    /// Sets each specified partition's committed offset. The consumer group
    /// must be in the `Empty` state (no active members).
    ///
    /// The request is sent to the group coordinator.
    ///
    /// # Example
    ///
    /// ```ignore
    /// admin
    ///     .alter_consumer_group_offsets(
    ///         "my-group",
    ///         &[("my-topic", &[(0, 100), (1, 200)])],
    ///     )
    ///     .await?;
    /// ```
    pub async fn alter_consumer_group_offsets(
        &self,
        group_id: &str,
        topic_offsets: &[(&str, &[(i32, i64)])],
    ) -> Result<Vec<AlterGroupOffsetResult>> {
        self.check_not_closed()?;

        let coordinator = self.find_group_coordinator(group_id).await?;

        let topics = topic_offsets
            .iter()
            .map(|(name, partitions)| OffsetCommitRequestTopic {
                name: (*name).to_string(),
                topic_id: None,
                partitions: partitions
                    .iter()
                    .map(|&(partition, offset)| OffsetCommitRequestPartition {
                        partition_index: partition,
                        committed_offset: offset,
                        // `-1` is correct here, unlike on the consumer's own
                        // commit path. An administratively set offset is not
                        // derived from a record this client consumed, so there
                        // is no leader epoch it can honestly vouch for;
                        // inventing one would defeat the KIP-320 check it is
                        // supposed to feed.
                        committed_leader_epoch: -1,
                        commit_timestamp: -1,
                        committed_metadata: None,
                    })
                    .collect(),
            })
            .collect();

        let request = OffsetCommitRequest {
            group_id: group_id.to_string(),
            generation_id: -1,
            member_id: String::new(),
            group_instance_id: None,
            retention_time_ms: -1,
            topics,
        };

        let version = coordinator
            .negotiate_api_version(
                ApiKey::OffsetCommit,
                versions::OFFSET_COMMIT_MAX,
                versions::OFFSET_COMMIT_MIN,
            )
            .await
            .ok_or_else(|| {
                KrafkaError::protocol_kind(
                    ProtocolErrorKind::UnknownApiVersion,
                    "no mutually supported OffsetCommit API version",
                )
            })?;

        let response_bytes = coordinator
            .send_request(ApiKey::OffsetCommit, version, |buf| {
                request.encode_versioned(version, buf)
            })
            .await?;

        let mut buf = response_bytes;
        let response = OffsetCommitResponse::decode_versioned(version, &mut buf)?;

        let mut results = Vec::new();
        for topic in response.topics {
            for partition in topic.partitions {
                results.push(AlterGroupOffsetResult {
                    topic: topic.name.clone(),
                    partition: partition.partition_index,
                    error: if partition.error_code.is_ok() {
                        None
                    } else {
                        Some(format!("{:?}", partition.error_code))
                    },
                });
            }
        }

        info!(
            "OffsetCommit for group {group_id}: {} partitions updated",
            results.len()
        );
        Ok(results)
    }

    // ════════════════════════════════════════════════════════════════════
    // DescribeUserScramCredentials (API key 50)
    // ════════════════════════════════════════════════════════════════════
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn test_offset_delete_request_maps_topic_partitions() {
        let request = OffsetDeleteRequest {
            group_id: "my-group".into(),
            topics: vec![OffsetDeleteTopicRequest {
                name: "orders".into(),
                partitions: [0, 1, 2]
                    .iter()
                    .map(|&p| OffsetDeletePartitionRequest { partition_index: p })
                    .collect(),
            }],
        };

        assert_eq!(request.group_id, "my-group");
        assert_eq!(request.topics[0].partitions.len(), 3);

        let mut buf = Vec::new();
        request
            .encode_versioned(versions::OFFSET_DELETE_MAX, &mut buf)
            .expect("OffsetDelete must encode");
        assert!(!buf.is_empty());
    }

    /// `topics: None` fetches every committed offset for the group; an empty
    /// vec would fetch none. The two must not be conflated.
    #[test]
    fn test_offset_fetch_request_none_means_all_partitions() {
        let all = OffsetFetchRequest {
            group_id: "g".into(),
            topics: None,
            require_stable: false,
            member_id: None,
            member_epoch: -1,
        };
        assert!(all.topics.is_none());

        let specific = OffsetFetchRequest {
            group_id: "g".into(),
            topics: Some(vec![OffsetFetchRequestTopic {
                name: "orders".into(),
                topic_id: None,
                partition_indexes: vec![0, 1],
            }]),
            require_stable: false,
            member_id: None,
            member_epoch: -1,
        };
        assert_eq!(
            specific.topics.as_ref().unwrap()[0].partition_indexes.len(),
            2
        );

        let mut buf = Vec::new();
        specific
            .encode_versioned(versions::OFFSET_FETCH_MAX, &mut buf)
            .expect("OffsetFetch must encode");
        assert!(!buf.is_empty());
    }

    /// An admin offset reset acts outside any group membership, so it must send
    /// the "no member" sentinels — a real generation/member ID would be fenced.
    #[test]
    fn test_admin_offset_commit_uses_no_member_sentinels() {
        let request = OffsetCommitRequest {
            group_id: "g".into(),
            generation_id: -1,
            member_id: String::new(),
            group_instance_id: None,
            retention_time_ms: -1,
            topics: vec![OffsetCommitRequestTopic {
                name: "orders".into(),
                topic_id: None,
                partitions: vec![OffsetCommitRequestPartition {
                    partition_index: 0,
                    committed_offset: 100,
                    committed_leader_epoch: -1,
                    commit_timestamp: -1,
                    committed_metadata: None,
                }],
            }],
        };

        assert_eq!(request.generation_id, -1);
        assert!(request.member_id.is_empty());
        assert_eq!(request.topics[0].partitions[0].committed_offset, 100);

        let mut buf = Vec::new();
        request
            .encode_versioned(versions::OFFSET_COMMIT_MAX, &mut buf)
            .expect("OffsetCommit must encode");
        assert!(!buf.is_empty());
    }

    /// `-1` is Kafka's "no offset committed" sentinel and must not be read as
    /// a real offset of -1.
    #[test]
    fn test_committed_offset_sentinel_is_distinguished_from_a_real_offset() {
        let none = GroupOffsetEntry {
            topic: "orders".into(),
            partition: 0,
            committed_offset: -1,
            metadata: None,
            error: None,
        };
        let real = GroupOffsetEntry {
            topic: "orders".into(),
            partition: 1,
            committed_offset: 0,
            metadata: None,
            error: None,
        };

        let interpret = |e: &GroupOffsetEntry| {
            if e.committed_offset == -1 {
                None
            } else {
                Some(e.committed_offset)
            }
        };

        assert_eq!(interpret(&none), None);
        assert_eq!(
            interpret(&real),
            Some(0),
            "offset 0 is a real committed position, not 'no commit'"
        );
    }
}