krafka 0.22.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
use bytes::{Buf, BufMut};

use super::{VersionedDecode, VersionedEncode, non_nullable_string};
use crate::error::{ErrorCode, Result};
use crate::protocol::api::ApiKey;
use crate::protocol::primitives::{Decode, Encode, KafkaString, TaggedFields, TryEncode};
use crate::protocol::{
    check_compact_array_len, check_compact_nullable_array_len, decode_capacity,
    encode_compact_array_len,
};

// ============================================================================
// ListPartitionReassignments API (Key 46)
//
// v0 baseline. All versions use flexible encoding.
// ============================================================================

/// Topic filter for a ListPartitionReassignments request.
#[derive(Debug, Clone)]
pub struct ListPartitionReassignmentsTopic {
    /// Topic name.
    pub name: String,
    /// Partition indexes to list reassignments for.
    pub partition_indexes: Vec<i32>,
}

/// ListPartitionReassignments request.
///
/// When `topics` is `None`, all ongoing reassignments are listed.
#[derive(Debug, Clone)]
pub struct ListPartitionReassignmentsRequest {
    /// Timeout in milliseconds.
    pub timeout_ms: i32,
    /// Topics to list, or `None` for all ongoing reassignments.
    pub topics: Option<Vec<ListPartitionReassignmentsTopic>>,
}

impl ListPartitionReassignmentsRequest {
    /// Get the API key.
    pub fn api_key() -> ApiKey {
        ApiKey::ListPartitionReassignments
    }

    /// Create a request for all ongoing reassignments.
    pub fn all() -> Self {
        Self {
            timeout_ms: 60_000,
            topics: None,
        }
    }

    /// Encode for version 0 (flexible encoding).
    pub fn encode_v0(&self, buf: &mut impl BufMut) -> Result<()> {
        self.timeout_ms.encode(buf);
        match &self.topics {
            None => {
                // Compact nullable array: 0 means null.
                crate::util::varint::encode_unsigned_varint(0, buf);
            }
            Some(topics) => {
                encode_compact_array_len(topics.len(), buf)?;
                for topic in topics {
                    KafkaString::new(&topic.name).try_encode_compact(buf)?;
                    encode_compact_array_len(topic.partition_indexes.len(), buf)?;
                    for &p in &topic.partition_indexes {
                        p.encode(buf);
                    }
                    TaggedFields::default().try_encode(buf)?;
                }
            }
        }
        TaggedFields::default().try_encode(buf)?;
        Ok(())
    }
}

impl VersionedEncode for ListPartitionReassignmentsRequest {
    fn encode_versioned(&self, version: i16, buf: &mut impl BufMut) -> Result<()> {
        match version {
            0 => self.encode_v0(buf),
            _ => unsupported_encode!("ListPartitionReassignmentsRequest", version),
        }
    }
}

// ── Response ─────────────────────────────────────────────────────────────

/// An ongoing partition reassignment.
#[derive(Debug, Clone)]
pub struct OngoingPartitionReassignment {
    /// Partition index.
    pub partition_index: i32,
    /// Current replica set.
    pub replicas: Vec<i32>,
    /// Replicas currently being added.
    pub adding_replicas: Vec<i32>,
    /// Replicas currently being removed.
    pub removing_replicas: Vec<i32>,
}

/// An ongoing topic reassignment.
#[derive(Debug, Clone)]
pub struct OngoingTopicReassignment {
    /// Topic name.
    pub name: String,
    /// Partition reassignments.
    pub partitions: Vec<OngoingPartitionReassignment>,
}

/// ListPartitionReassignments response.
#[derive(Debug, Clone)]
pub struct ListPartitionReassignmentsResponse {
    /// Throttle time in milliseconds.
    pub throttle_time_ms: i32,
    /// Top-level error code.
    pub error_code: ErrorCode,
    /// Top-level error message, or `None` if no error.
    pub error_message: Option<String>,
    /// Ongoing reassignments per topic.
    pub topics: Vec<OngoingTopicReassignment>,
}

impl ListPartitionReassignmentsResponse {
    /// Decode from version 0 (flexible encoding).
    pub fn decode_v0(buf: &mut impl Buf) -> Result<Self> {
        let throttle_time_ms = i32::decode(buf)?;
        let error_code = ErrorCode::from_i16(i16::decode(buf)?);
        let error_message = KafkaString::decode_compact(buf)?.0;

        let topic_count =
            check_compact_array_len(crate::util::varint::decode_unsigned_varint(buf)?)?;
        let mut topics = Vec::with_capacity(decode_capacity(topic_count, buf.remaining()));
        for _ in 0..topic_count {
            let name = non_nullable_string("topic name", KafkaString::decode_compact(buf)?.0)?;
            let partition_count =
                check_compact_array_len(crate::util::varint::decode_unsigned_varint(buf)?)?;
            let mut partitions =
                Vec::with_capacity(decode_capacity(partition_count, buf.remaining()));
            for _ in 0..partition_count {
                let partition_index = i32::decode(buf)?;
                let replicas = Self::decode_broker_id_array(buf)?;
                let adding_replicas = Self::decode_broker_id_array(buf)?;
                let removing_replicas = Self::decode_broker_id_array(buf)?;
                let _ = TaggedFields::decode(buf)?;
                partitions.push(OngoingPartitionReassignment {
                    partition_index,
                    replicas,
                    adding_replicas,
                    removing_replicas,
                });
            }
            let _ = TaggedFields::decode(buf)?;
            topics.push(OngoingTopicReassignment { name, partitions });
        }
        let _ = TaggedFields::decode(buf)?;

        Ok(Self {
            throttle_time_ms,
            error_code,
            error_message,
            topics,
        })
    }

    /// Decode a compact array of broker IDs (i32).
    fn decode_broker_id_array(buf: &mut impl Buf) -> Result<Vec<i32>> {
        let count =
            check_compact_nullable_array_len(crate::util::varint::decode_unsigned_varint(buf)?)?;
        let mut ids = Vec::with_capacity(decode_capacity(count, buf.remaining()));
        for _ in 0..count {
            ids.push(i32::decode(buf)?);
        }
        Ok(ids)
    }
}

impl VersionedDecode for ListPartitionReassignmentsResponse {
    fn decode_versioned(version: i16, buf: &mut impl Buf) -> Result<Self> {
        match version {
            0 => Self::decode_v0(buf),
            _ => unsupported_decode!("ListPartitionReassignmentsResponse", version),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    use bytes::BytesMut;

    #[test]
    fn test_list_partition_reassignments_api_key() {
        assert_eq!(
            ListPartitionReassignmentsRequest::api_key(),
            ApiKey::ListPartitionReassignments
        );
    }

    #[test]
    fn test_list_partition_reassignments_request_all() {
        let request = ListPartitionReassignmentsRequest::all();
        assert!(request.topics.is_none());
        assert_eq!(request.timeout_ms, 60_000);
    }

    #[test]
    fn test_list_partition_reassignments_request_encode_v0_null() {
        let request = ListPartitionReassignmentsRequest::all();
        let mut buf = BytesMut::new();
        request.encode_v0(&mut buf).unwrap();
        // timeout (4 bytes) + compact nullable null (varint 0) + tagged fields (varint 0)
        assert_eq!(buf.len(), 6);
    }

    #[test]
    fn test_list_partition_reassignments_request_encode_v0_with_topics() {
        let request = ListPartitionReassignmentsRequest {
            timeout_ms: 30_000,
            topics: Some(vec![ListPartitionReassignmentsTopic {
                name: "my-topic".to_string(),
                partition_indexes: vec![0, 1, 2],
            }]),
        };

        let mut buf = BytesMut::new();
        request.encode_v0(&mut buf).unwrap();
        assert!(!buf.is_empty());
    }

    #[test]
    fn test_list_partition_reassignments_versioned_unsupported() {
        let request = ListPartitionReassignmentsRequest::all();
        let mut buf = BytesMut::new();
        assert!(request.encode_versioned(-1, &mut buf).is_err());
        assert!(request.encode_versioned(1, &mut buf).is_err());
    }

    /// Build a compact (flexible) string: varint(len+1) followed by raw bytes.
    fn put_compact_string(buf: &mut BytesMut, s: &str) {
        crate::util::varint::encode_unsigned_varint((s.len() + 1) as u32, buf);
        buf.put_slice(s.as_bytes());
    }

    /// Write a compact nullable string set to null: varint(0).
    fn put_compact_null_string(buf: &mut BytesMut) {
        crate::util::varint::encode_unsigned_varint(0, buf);
    }

    /// Write a zero-length tagged-fields section.
    fn put_empty_tagged_fields(buf: &mut BytesMut) {
        crate::util::varint::encode_unsigned_varint(0, buf);
    }

    /// Write a compact array length: varint(count + 1).
    fn put_compact_array_len(buf: &mut BytesMut, count: usize) {
        crate::util::varint::encode_unsigned_varint((count + 1) as u32, buf);
    }

    #[test]
    fn test_list_partition_reassignments_response_decode_v0() {
        let mut buf = BytesMut::new();
        // throttle_time_ms
        buf.put_i32(0);
        // error_code = NONE
        buf.put_i16(0);
        // error_message = null
        put_compact_null_string(&mut buf);
        // topics compact array: count = 1
        put_compact_array_len(&mut buf, 1);
        // topic name
        put_compact_string(&mut buf, "my-topic");
        // partitions compact array: count = 1
        put_compact_array_len(&mut buf, 1);
        // partition_index
        buf.put_i32(0);
        // replicas: [1, 2, 3]
        put_compact_array_len(&mut buf, 3);
        buf.put_i32(1);
        buf.put_i32(2);
        buf.put_i32(3);
        // adding_replicas: [3]
        put_compact_array_len(&mut buf, 1);
        buf.put_i32(3);
        // removing_replicas: [1]
        put_compact_array_len(&mut buf, 1);
        buf.put_i32(1);
        // partition tagged fields
        put_empty_tagged_fields(&mut buf);
        // topic tagged fields
        put_empty_tagged_fields(&mut buf);
        // top-level tagged fields
        put_empty_tagged_fields(&mut buf);

        let resp = ListPartitionReassignmentsResponse::decode_v0(&mut buf.freeze()).unwrap();
        assert_eq!(resp.throttle_time_ms, 0);
        assert!(resp.error_code.is_ok());
        assert!(resp.error_message.is_none());
        assert_eq!(resp.topics.len(), 1);

        let topic = &resp.topics[0];
        assert_eq!(topic.name, "my-topic");
        assert_eq!(topic.partitions.len(), 1);

        let p = &topic.partitions[0];
        assert_eq!(p.partition_index, 0);
        assert_eq!(p.replicas, vec![1, 2, 3]);
        assert_eq!(p.adding_replicas, vec![3]);
        assert_eq!(p.removing_replicas, vec![1]);
    }

    #[test]
    fn test_list_partition_reassignments_response_empty() {
        let mut buf = BytesMut::new();
        buf.put_i32(0); // throttle_time_ms
        buf.put_i16(0); // error_code = NONE
        put_compact_null_string(&mut buf);
        put_compact_array_len(&mut buf, 0); // empty topics
        put_empty_tagged_fields(&mut buf);

        let resp = ListPartitionReassignmentsResponse::decode_v0(&mut buf.freeze()).unwrap();
        assert!(resp.error_code.is_ok());
        assert!(resp.topics.is_empty());
    }

    #[test]
    fn test_list_partition_reassignments_response_top_level_error() {
        let mut buf = BytesMut::new();
        buf.put_i32(10); // throttle_time_ms
        buf.put_i16(31); // error_code = CLUSTER_AUTHORIZATION_FAILED
        put_compact_string(&mut buf, "Not authorized");
        put_compact_array_len(&mut buf, 0); // empty topics
        put_empty_tagged_fields(&mut buf);

        let resp = ListPartitionReassignmentsResponse::decode_v0(&mut buf.freeze()).unwrap();
        assert!(!resp.error_code.is_ok());
        assert_eq!(resp.error_message.as_deref(), Some("Not authorized"));
    }

    #[test]
    fn test_list_partition_reassignments_versioned_decode_unsupported() {
        let buf = BytesMut::new();
        assert!(
            ListPartitionReassignmentsResponse::decode_versioned(-1, &mut buf.clone().freeze())
                .is_err()
        );
        assert!(
            ListPartitionReassignmentsResponse::decode_versioned(1, &mut buf.freeze()).is_err()
        );
    }

    #[test]
    fn test_list_partition_reassignments_response_multiple_topics() {
        let mut buf = BytesMut::new();
        buf.put_i32(0); // throttle_time_ms
        buf.put_i16(0); // error_code
        put_compact_null_string(&mut buf);
        // 2 topics
        put_compact_array_len(&mut buf, 2);

        // topic 1
        put_compact_string(&mut buf, "topic-a");
        put_compact_array_len(&mut buf, 1);
        buf.put_i32(0); // partition_index
        put_compact_array_len(&mut buf, 2); // replicas
        buf.put_i32(1);
        buf.put_i32(2);
        put_compact_array_len(&mut buf, 0); // adding
        put_compact_array_len(&mut buf, 0); // removing
        put_empty_tagged_fields(&mut buf); // partition
        put_empty_tagged_fields(&mut buf); // topic

        // topic 2
        put_compact_string(&mut buf, "topic-b");
        put_compact_array_len(&mut buf, 1);
        buf.put_i32(1); // partition_index
        put_compact_array_len(&mut buf, 3); // replicas
        buf.put_i32(1);
        buf.put_i32(2);
        buf.put_i32(3);
        put_compact_array_len(&mut buf, 1); // adding
        buf.put_i32(3);
        put_compact_array_len(&mut buf, 1); // removing
        buf.put_i32(1);
        put_empty_tagged_fields(&mut buf); // partition
        put_empty_tagged_fields(&mut buf); // topic

        // top-level tagged fields
        put_empty_tagged_fields(&mut buf);

        let resp = ListPartitionReassignmentsResponse::decode_v0(&mut buf.freeze()).unwrap();
        assert_eq!(resp.topics.len(), 2);
        assert_eq!(resp.topics[0].name, "topic-a");
        assert_eq!(resp.topics[1].name, "topic-b");
        assert_eq!(resp.topics[1].partitions[0].adding_replicas, vec![3]);
        assert_eq!(resp.topics[1].partitions[0].removing_replicas, vec![1]);
    }
}