odradek-protocol 0.1.0

Sans-I/O implementation of the Kafka wire protocol: primitive codecs, message framing, and versioned message types
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! `MetadataResponse` — generated from `schemas/MetadataResponse.json`.
//!
//! @generated by `cargo xtask codegen`. Do not edit by hand.

#![allow(
    clippy::field_reassign_with_default,
    clippy::nonminimal_bool,
    clippy::derivable_impls,
    clippy::borrow_deref_ref,
    clippy::double_parens,
    unused_parens
)]

use bytes::{Buf, BufMut};

use crate::budget::{Budget, Limits};
#[allow(unused_imports)]
use crate::error::{DecodeError, EncodeError};
use crate::wire::{self, RawTaggedField};

/// Whether `version` of this message uses the flexible (compact) encoding.
pub fn is_flexible(version: i16) -> bool {
    let _ = version;
    version >= 9
}

/// `MetadataResponse`, versions 0-13.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MetadataResponse {
    /// The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota.
    pub throttle_time_ms: i32,
    /// A list of brokers present in the cluster.
    pub brokers: Vec<MetadataResponseBroker>,
    /// The cluster ID that responding broker belongs to.
    pub cluster_id: Option<String>,
    /// The ID of the controller broker.
    pub controller_id: i32,
    /// Each topic in the response.
    pub topics: Vec<MetadataResponseTopic>,
    /// 32-bit bitfield to represent authorized operations for this cluster.
    pub cluster_authorized_operations: i32,
    /// The top-level error code, or 0 if there was no error.
    pub error_code: i16,
    /// Tagged fields not (yet) known to this crate, kept raw.
    pub unknown_tagged_fields: Vec<RawTaggedField>,
}

impl Default for MetadataResponse {
    fn default() -> Self {
        Self {
            throttle_time_ms: 0,
            brokers: Vec::new(),
            cluster_id: None,
            controller_id: -1,
            topics: Vec::new(),
            cluster_authorized_operations: -2147483648,
            error_code: 0,
            unknown_tagged_fields: Vec::new(),
        }
    }
}

impl MetadataResponse {
    /// This message's api key in Kafka's registry.
    pub const API_KEY: i16 = 3;
    /// The lowest schema version this snapshot can speak.
    pub const MIN_VERSION: i16 = 0;
    /// The highest schema version this snapshot can speak.
    pub const MAX_VERSION: i16 = 13;

    /// Encode this `MetadataResponse` at `version`.
    pub fn encode(&self, buf: &mut impl BufMut, version: i16) -> Result<(), EncodeError> {
        if version >= 3 {
            buf.put_i32(self.throttle_time_ms);
        }
        if is_flexible(version) {
            wire::put_compact_array_len(buf, Some(self.brokers.len()));
        } else {
            wire::put_array_len(buf, Some(self.brokers.len()))?;
        }
        for item in &self.brokers {
            item.encode(buf, version)?;
        }
        if version >= 2 {
            if is_flexible(version) {
                wire::put_compact_nullable_string(buf, self.cluster_id.as_deref());
            } else {
                wire::put_nullable_string(buf, self.cluster_id.as_deref())?;
            }
        }
        if version >= 1 {
            buf.put_i32(self.controller_id);
        }
        if is_flexible(version) {
            wire::put_compact_array_len(buf, Some(self.topics.len()));
        } else {
            wire::put_array_len(buf, Some(self.topics.len()))?;
        }
        for item in &self.topics {
            item.encode(buf, version)?;
        }
        if (8..=10).contains(&version) {
            buf.put_i32(self.cluster_authorized_operations);
        }
        if version >= 13 {
            buf.put_i16(self.error_code);
        }
        if is_flexible(version) {
            wire::put_tagged_fields(buf, &self.unknown_tagged_fields);
        }
        Ok(())
    }

    /// Decode one `MetadataResponse`, bounding allocation by the default
    /// [`Limits`] derived from `buf`'s remaining length.
    pub fn decode(buf: &mut impl Buf, version: i16) -> Result<Self, DecodeError> {
        Self::decode_with_limits(buf, version, Limits::default())
    }

    /// Decode one `MetadataResponse` under `limits`.
    pub fn decode_with_limits(
        buf: &mut impl Buf,
        version: i16,
        limits: Limits,
    ) -> Result<Self, DecodeError> {
        let mut budget = limits.budget(buf.remaining());
        Self::decode_with_budget(buf, version, &mut budget)
    }

    /// Decode one `MetadataResponse` against an existing `budget`.
    pub fn decode_with_budget(
        buf: &mut impl Buf,
        version: i16,
        budget: &mut Budget,
    ) -> Result<Self, DecodeError> {
        let mut this = Self::default();
        if version >= 3 {
            this.throttle_time_ms = wire::get_i32(buf)?;
        }
        this.brokers = {
            let len = if is_flexible(version) {
                wire::get_compact_array_len(buf)?
            } else {
                wire::get_array_len(buf)?
            };
            match len {
                None => return Err(DecodeError::InvalidLength(-1)),
                Some(n) => {
                    let mut items = Vec::new();
                    for _ in 0..n {
                        let mark = buf.remaining();
                        let item =
                            MetadataResponseBroker::decode_with_budget(buf, version, budget)?;
                        budget.progress(mark, buf.remaining())?;
                        budget.push(&mut items, item)?;
                    }
                    items
                }
            }
        };
        if version >= 2 {
            this.cluster_id = if is_flexible(version) {
                wire::get_compact_nullable_string(buf)?
            } else {
                wire::get_nullable_string(buf)?
            };
        }
        if version >= 1 {
            this.controller_id = wire::get_i32(buf)?;
        }
        this.topics = {
            let len = if is_flexible(version) {
                wire::get_compact_array_len(buf)?
            } else {
                wire::get_array_len(buf)?
            };
            match len {
                None => return Err(DecodeError::InvalidLength(-1)),
                Some(n) => {
                    let mut items = Vec::new();
                    for _ in 0..n {
                        let mark = buf.remaining();
                        let item = MetadataResponseTopic::decode_with_budget(buf, version, budget)?;
                        budget.progress(mark, buf.remaining())?;
                        budget.push(&mut items, item)?;
                    }
                    items
                }
            }
        };
        if (8..=10).contains(&version) {
            this.cluster_authorized_operations = wire::get_i32(buf)?;
        }
        if version >= 13 {
            this.error_code = wire::get_i16(buf)?;
        }
        if is_flexible(version) {
            this.unknown_tagged_fields = wire::get_tagged_fields_with_budget(buf, budget)?;
        }
        Ok(this)
    }
}

impl crate::Message for MetadataResponse {
    const API_KEY: i16 = 3;
    const MIN_VERSION: i16 = 0;
    const MAX_VERSION: i16 = 13;

    fn encode(&self, buf: &mut impl BufMut, version: i16) -> Result<(), EncodeError> {
        MetadataResponse::encode(self, buf, version)
    }
    fn decode(buf: &mut impl Buf, version: i16) -> Result<Self, DecodeError> {
        MetadataResponse::decode(buf, version)
    }
    fn decode_with_limits(
        buf: &mut impl Buf,
        version: i16,
        limits: Limits,
    ) -> Result<Self, DecodeError> {
        MetadataResponse::decode_with_limits(buf, version, limits)
    }
    fn throttle_time_ms(&self) -> Option<i32> {
        Some(self.throttle_time_ms)
    }
}

/// `MetadataResponseBroker` (nested in [`MetadataResponse`]).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MetadataResponseBroker {
    /// The broker ID.
    pub node_id: i32,
    /// The broker hostname.
    pub host: String,
    /// The broker port.
    pub port: i32,
    /// The rack of the broker, or null if it has not been assigned to a rack.
    pub rack: Option<String>,
    /// Tagged fields not (yet) known to this crate, kept raw.
    pub unknown_tagged_fields: Vec<RawTaggedField>,
}

impl Default for MetadataResponseBroker {
    fn default() -> Self {
        Self {
            node_id: 0,
            host: String::new(),
            port: 0,
            rack: None,
            unknown_tagged_fields: Vec::new(),
        }
    }
}

impl MetadataResponseBroker {
    /// Encode this `MetadataResponseBroker` at `version`.
    pub fn encode(&self, buf: &mut impl BufMut, version: i16) -> Result<(), EncodeError> {
        buf.put_i32(self.node_id);
        if is_flexible(version) {
            wire::put_compact_string(buf, &self.host);
        } else {
            wire::put_string(buf, &self.host)?;
        }
        buf.put_i32(self.port);
        if version >= 1 {
            if is_flexible(version) {
                wire::put_compact_nullable_string(buf, self.rack.as_deref());
            } else {
                wire::put_nullable_string(buf, self.rack.as_deref())?;
            }
        }
        if is_flexible(version) {
            wire::put_tagged_fields(buf, &self.unknown_tagged_fields);
        }
        Ok(())
    }

    /// Decode one `MetadataResponseBroker`, bounding allocation by the default
    /// [`Limits`] derived from `buf`'s remaining length.
    pub fn decode(buf: &mut impl Buf, version: i16) -> Result<Self, DecodeError> {
        Self::decode_with_limits(buf, version, Limits::default())
    }

    /// Decode one `MetadataResponseBroker` under `limits`.
    pub fn decode_with_limits(
        buf: &mut impl Buf,
        version: i16,
        limits: Limits,
    ) -> Result<Self, DecodeError> {
        let mut budget = limits.budget(buf.remaining());
        Self::decode_with_budget(buf, version, &mut budget)
    }

    /// Decode one `MetadataResponseBroker` against an existing `budget`.
    pub fn decode_with_budget(
        buf: &mut impl Buf,
        version: i16,
        budget: &mut Budget,
    ) -> Result<Self, DecodeError> {
        let mut this = Self::default();
        this.node_id = wire::get_i32(buf)?;
        this.host = if is_flexible(version) {
            wire::get_compact_string(buf)?
        } else {
            wire::get_string(buf)?
        };
        this.port = wire::get_i32(buf)?;
        if version >= 1 {
            this.rack = if is_flexible(version) {
                wire::get_compact_nullable_string(buf)?
            } else {
                wire::get_nullable_string(buf)?
            };
        }
        if is_flexible(version) {
            this.unknown_tagged_fields = wire::get_tagged_fields_with_budget(buf, budget)?;
        }
        Ok(this)
    }
}

/// `MetadataResponseTopic` (nested in [`MetadataResponse`]).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MetadataResponseTopic {
    /// The topic error, or 0 if there was no error.
    pub error_code: i16,
    /// The topic name. Null for non-existing topics queried by ID. This is never null when ErrorCode is zero. One of Name and TopicId is always populated.
    pub name: Option<String>,
    /// The topic id. Zero for non-existing topics queried by name. This is never zero when ErrorCode is zero. One of Name and TopicId is always populated.
    pub topic_id: [u8; 16],
    /// True if the topic is internal.
    pub is_internal: bool,
    /// Each partition in the topic.
    pub partitions: Vec<MetadataResponsePartition>,
    /// 32-bit bitfield to represent authorized operations for this topic.
    pub topic_authorized_operations: i32,
    /// Tagged fields not (yet) known to this crate, kept raw.
    pub unknown_tagged_fields: Vec<RawTaggedField>,
}

impl Default for MetadataResponseTopic {
    fn default() -> Self {
        Self {
            error_code: 0,
            name: Some(String::new()),
            topic_id: [0u8; 16],
            is_internal: false,
            partitions: Vec::new(),
            topic_authorized_operations: -2147483648,
            unknown_tagged_fields: Vec::new(),
        }
    }
}

impl MetadataResponseTopic {
    /// Encode this `MetadataResponseTopic` at `version`.
    pub fn encode(&self, buf: &mut impl BufMut, version: i16) -> Result<(), EncodeError> {
        buf.put_i16(self.error_code);
        if self.name.is_none() && !(version >= 12) {
            return Err(EncodeError::NullField("Name"));
        }
        if is_flexible(version) {
            wire::put_compact_nullable_string(buf, self.name.as_deref());
        } else {
            wire::put_nullable_string(buf, self.name.as_deref())?;
        }
        if version >= 10 {
            wire::put_uuid(buf, self.topic_id);
        }
        if version >= 1 {
            buf.put_u8(u8::from(self.is_internal));
        }
        if is_flexible(version) {
            wire::put_compact_array_len(buf, Some(self.partitions.len()));
        } else {
            wire::put_array_len(buf, Some(self.partitions.len()))?;
        }
        for item in &self.partitions {
            item.encode(buf, version)?;
        }
        if version >= 8 {
            buf.put_i32(self.topic_authorized_operations);
        }
        if is_flexible(version) {
            wire::put_tagged_fields(buf, &self.unknown_tagged_fields);
        }
        Ok(())
    }

    /// Decode one `MetadataResponseTopic`, bounding allocation by the default
    /// [`Limits`] derived from `buf`'s remaining length.
    pub fn decode(buf: &mut impl Buf, version: i16) -> Result<Self, DecodeError> {
        Self::decode_with_limits(buf, version, Limits::default())
    }

    /// Decode one `MetadataResponseTopic` under `limits`.
    pub fn decode_with_limits(
        buf: &mut impl Buf,
        version: i16,
        limits: Limits,
    ) -> Result<Self, DecodeError> {
        let mut budget = limits.budget(buf.remaining());
        Self::decode_with_budget(buf, version, &mut budget)
    }

    /// Decode one `MetadataResponseTopic` against an existing `budget`.
    pub fn decode_with_budget(
        buf: &mut impl Buf,
        version: i16,
        budget: &mut Budget,
    ) -> Result<Self, DecodeError> {
        let mut this = Self::default();
        this.error_code = wire::get_i16(buf)?;
        this.name = {
            let raw = if is_flexible(version) {
                wire::get_compact_nullable_string(buf)?
            } else {
                wire::get_nullable_string(buf)?
            };
            if raw.is_none() && !(version >= 12) {
                return Err(DecodeError::InvalidLength(-1));
            }
            raw
        };
        if version >= 10 {
            this.topic_id = wire::get_uuid(buf)?;
        }
        if version >= 1 {
            this.is_internal = wire::get_bool(buf)?;
        }
        this.partitions = {
            let len = if is_flexible(version) {
                wire::get_compact_array_len(buf)?
            } else {
                wire::get_array_len(buf)?
            };
            match len {
                None => return Err(DecodeError::InvalidLength(-1)),
                Some(n) => {
                    let mut items = Vec::new();
                    for _ in 0..n {
                        let mark = buf.remaining();
                        let item =
                            MetadataResponsePartition::decode_with_budget(buf, version, budget)?;
                        budget.progress(mark, buf.remaining())?;
                        budget.push(&mut items, item)?;
                    }
                    items
                }
            }
        };
        if version >= 8 {
            this.topic_authorized_operations = wire::get_i32(buf)?;
        }
        if is_flexible(version) {
            this.unknown_tagged_fields = wire::get_tagged_fields_with_budget(buf, budget)?;
        }
        Ok(this)
    }
}

/// `MetadataResponsePartition` (nested in [`MetadataResponse`]).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MetadataResponsePartition {
    /// The partition error, or 0 if there was no error.
    pub error_code: i16,
    /// The partition index.
    pub partition_index: i32,
    /// The ID of the leader broker.
    pub leader_id: i32,
    /// The leader epoch of this partition.
    pub leader_epoch: i32,
    /// The set of all nodes that host this partition.
    pub replica_nodes: Vec<i32>,
    /// The set of nodes that are in sync with the leader for this partition.
    pub isr_nodes: Vec<i32>,
    /// The set of offline replicas of this partition.
    pub offline_replicas: Vec<i32>,
    /// Tagged fields not (yet) known to this crate, kept raw.
    pub unknown_tagged_fields: Vec<RawTaggedField>,
}

impl Default for MetadataResponsePartition {
    fn default() -> Self {
        Self {
            error_code: 0,
            partition_index: 0,
            leader_id: 0,
            leader_epoch: -1,
            replica_nodes: Vec::new(),
            isr_nodes: Vec::new(),
            offline_replicas: Vec::new(),
            unknown_tagged_fields: Vec::new(),
        }
    }
}

impl MetadataResponsePartition {
    /// Encode this `MetadataResponsePartition` at `version`.
    pub fn encode(&self, buf: &mut impl BufMut, version: i16) -> Result<(), EncodeError> {
        buf.put_i16(self.error_code);
        buf.put_i32(self.partition_index);
        buf.put_i32(self.leader_id);
        if version >= 7 {
            buf.put_i32(self.leader_epoch);
        }
        if is_flexible(version) {
            wire::put_compact_array_len(buf, Some(self.replica_nodes.len()));
        } else {
            wire::put_array_len(buf, Some(self.replica_nodes.len()))?;
        }
        for item in &self.replica_nodes {
            buf.put_i32(*item);
        }
        if is_flexible(version) {
            wire::put_compact_array_len(buf, Some(self.isr_nodes.len()));
        } else {
            wire::put_array_len(buf, Some(self.isr_nodes.len()))?;
        }
        for item in &self.isr_nodes {
            buf.put_i32(*item);
        }
        if version >= 5 {
            if is_flexible(version) {
                wire::put_compact_array_len(buf, Some(self.offline_replicas.len()));
            } else {
                wire::put_array_len(buf, Some(self.offline_replicas.len()))?;
            }
            for item in &self.offline_replicas {
                buf.put_i32(*item);
            }
        }
        if is_flexible(version) {
            wire::put_tagged_fields(buf, &self.unknown_tagged_fields);
        }
        Ok(())
    }

    /// Decode one `MetadataResponsePartition`, bounding allocation by the default
    /// [`Limits`] derived from `buf`'s remaining length.
    pub fn decode(buf: &mut impl Buf, version: i16) -> Result<Self, DecodeError> {
        Self::decode_with_limits(buf, version, Limits::default())
    }

    /// Decode one `MetadataResponsePartition` under `limits`.
    pub fn decode_with_limits(
        buf: &mut impl Buf,
        version: i16,
        limits: Limits,
    ) -> Result<Self, DecodeError> {
        let mut budget = limits.budget(buf.remaining());
        Self::decode_with_budget(buf, version, &mut budget)
    }

    /// Decode one `MetadataResponsePartition` against an existing `budget`.
    pub fn decode_with_budget(
        buf: &mut impl Buf,
        version: i16,
        budget: &mut Budget,
    ) -> Result<Self, DecodeError> {
        let mut this = Self::default();
        this.error_code = wire::get_i16(buf)?;
        this.partition_index = wire::get_i32(buf)?;
        this.leader_id = wire::get_i32(buf)?;
        if version >= 7 {
            this.leader_epoch = wire::get_i32(buf)?;
        }
        this.replica_nodes = {
            let len = if is_flexible(version) {
                wire::get_compact_array_len(buf)?
            } else {
                wire::get_array_len(buf)?
            };
            match len {
                None => return Err(DecodeError::InvalidLength(-1)),
                Some(n) => {
                    let mut items = Vec::new();
                    for _ in 0..n {
                        budget.push(&mut items, wire::get_i32(buf)?)?;
                    }
                    items
                }
            }
        };
        this.isr_nodes = {
            let len = if is_flexible(version) {
                wire::get_compact_array_len(buf)?
            } else {
                wire::get_array_len(buf)?
            };
            match len {
                None => return Err(DecodeError::InvalidLength(-1)),
                Some(n) => {
                    let mut items = Vec::new();
                    for _ in 0..n {
                        budget.push(&mut items, wire::get_i32(buf)?)?;
                    }
                    items
                }
            }
        };
        if version >= 5 {
            this.offline_replicas = {
                let len = if is_flexible(version) {
                    wire::get_compact_array_len(buf)?
                } else {
                    wire::get_array_len(buf)?
                };
                match len {
                    None => return Err(DecodeError::InvalidLength(-1)),
                    Some(n) => {
                        let mut items = Vec::new();
                        for _ in 0..n {
                            budget.push(&mut items, wire::get_i32(buf)?)?;
                        }
                        items
                    }
                }
            };
        }
        if is_flexible(version) {
            this.unknown_tagged_fields = wire::get_tagged_fields_with_budget(buf, budget)?;
        }
        Ok(this)
    }
}