kafrust 0.2.28

A pure Rust Kafka client with no librdkafka or C client binding dependency.
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
use core::fmt;

/// Result type returned by kafrust APIs.
pub type Result<T> = core::result::Result<T, Error>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Kafka broker error categories used by kafrust retry and diagnostics code.
pub enum BrokerErrorKind {
    /// An error code that kafrust does not classify yet.
    Unknown,
    /// Kafka reported that the requested fetch offset is outside the retained log.
    OffsetOutOfRange,
    /// Kafka reported an unknown topic or partition.
    UnknownTopicOrPartition,
    /// Kafka reported that a partition leader is not currently available.
    LeaderNotAvailable,
    /// Kafka reported that the target broker is not the leader or follower.
    NotLeaderOrFollower,
    /// Kafka reported that the broker-side request timed out.
    RequestTimedOut,
    /// Kafka reported that a replica is unavailable.
    ReplicaNotAvailable,
    /// Kafka rejected an invalid topic name or definition.
    InvalidTopic,
    /// Kafka reported that the coordinator is unavailable.
    CoordinatorNotAvailable,
    /// Kafka reported that the coordinator is still loading its state.
    CoordinatorLoadInProgress,
    /// Kafka reported that the request was sent to the wrong coordinator.
    NotCoordinator,
    /// Kafka reported an invalid consumer group generation.
    IllegalGeneration,
    /// Kafka reported inconsistent group protocol metadata.
    InconsistentGroupProtocol,
    /// Kafka reported an unknown consumer group member ID.
    UnknownMemberId,
    /// Kafka rejected the configured session timeout.
    InvalidSessionTimeout,
    /// Kafka reported that a group rebalance is in progress.
    RebalanceInProgress,
    /// Kafka denied access to a topic.
    TopicAuthorizationFailed,
    /// Kafka denied access to the cluster operation.
    ClusterAuthorizationFailed,
    /// Kafka reported that the topic already exists.
    TopicAlreadyExists,
    /// Kafka rejected the requested partition count.
    InvalidPartitions,
    /// Kafka rejected the requested replication factor.
    InvalidReplicationFactor,
    /// Kafka rejected an explicit replica assignment.
    InvalidReplicaAssignment,
    /// Kafka rejected a topic or broker configuration.
    InvalidConfig,
    /// Kafka reported that this broker is not the active controller.
    NotController,
    /// Kafka rejected an invalid request.
    InvalidRequest,
    /// Kafka received a producer sequence larger than the expected sequence.
    OutOfOrderSequenceNumber,
    /// Kafka recognized a retry of an already appended producer sequence.
    DuplicateSequenceNumber,
    /// Kafka rejected an operation from an older producer epoch.
    InvalidProducerEpoch,
    /// Kafka fenced this producer with a newer producer instance.
    ProducerFenced,
    /// Kafka is still completing another transaction for this transactional ID.
    ConcurrentTransactions,
    /// Kafka reported that the requested consumer group does not exist.
    GroupIdNotFound,
    /// Kafka refused to delete a group that still has active members.
    NonEmptyGroup,
    /// Kafka rejected offset deletion because the group still subscribes to the topic.
    GroupSubscribedToTopic,
    /// Kafka fenced a static consumer because another member uses the same instance ID.
    FencedInstanceId,
    /// Kafka fenced a consumer-group member epoch.
    FencedMemberEpoch,
    /// Kafka reported a stale consumer-group member epoch.
    StaleMemberEpoch,
    /// Kafka rejected a fetch because the supplied leader epoch is fenced.
    FencedLeaderEpoch,
    /// Kafka could not identify the supplied leader epoch during a transition.
    UnknownLeaderEpoch,
    /// Kafka rejected the current fetch session epoch and requires a new session.
    InvalidFetchSessionEpoch,
    /// Kafka found no eligible replica for the requested leader election.
    EligibleLeadersNotAvailable,
    /// Kafka reported that the requested leader is already preferred.
    ElectionNotNeeded,
    /// Kafka reported that no partition reassignment is currently active.
    NoReassignmentInProgress,
}

impl BrokerErrorKind {
    /// Classifies a Kafka protocol error code.
    pub fn from_code(code: i16) -> Self {
        match code {
            1 => Self::OffsetOutOfRange,
            3 => Self::UnknownTopicOrPartition,
            5 => Self::LeaderNotAvailable,
            6 => Self::NotLeaderOrFollower,
            7 => Self::RequestTimedOut,
            9 => Self::ReplicaNotAvailable,
            14 => Self::CoordinatorLoadInProgress,
            15 => Self::CoordinatorNotAvailable,
            16 => Self::NotCoordinator,
            17 => Self::InvalidTopic,
            22 => Self::IllegalGeneration,
            23 => Self::InconsistentGroupProtocol,
            25 => Self::UnknownMemberId,
            26 => Self::InvalidSessionTimeout,
            27 => Self::RebalanceInProgress,
            29 => Self::TopicAuthorizationFailed,
            31 => Self::ClusterAuthorizationFailed,
            36 => Self::TopicAlreadyExists,
            37 => Self::InvalidPartitions,
            38 => Self::InvalidReplicationFactor,
            39 => Self::InvalidReplicaAssignment,
            40 => Self::InvalidConfig,
            41 => Self::NotController,
            42 => Self::InvalidRequest,
            45 => Self::OutOfOrderSequenceNumber,
            46 => Self::DuplicateSequenceNumber,
            47 => Self::InvalidProducerEpoch,
            51 => Self::ConcurrentTransactions,
            68 => Self::NonEmptyGroup,
            69 => Self::GroupIdNotFound,
            82 => Self::FencedInstanceId,
            110 => Self::FencedMemberEpoch,
            113 => Self::StaleMemberEpoch,
            74 => Self::FencedLeaderEpoch,
            75 => Self::UnknownLeaderEpoch,
            70 => Self::InvalidFetchSessionEpoch,
            86 => Self::GroupSubscribedToTopic,
            90 => Self::ProducerFenced,
            83 => Self::EligibleLeadersNotAvailable,
            84 => Self::ElectionNotNeeded,
            85 => Self::NoReassignmentInProgress,
            _ => Self::Unknown,
        }
    }

    /// Returns whether this broker error is retryable for the current producer path.
    pub fn is_produce_retryable(self) -> bool {
        matches!(
            self,
            Self::UnknownTopicOrPartition
                | Self::LeaderNotAvailable
                | Self::NotLeaderOrFollower
                | Self::RequestTimedOut
                | Self::ReplicaNotAvailable
        )
    }
}

#[derive(Debug)]
/// Error type returned by kafrust APIs.
pub enum Error {
    /// No bootstrap server was configured.
    MissingBootstrapServer,
    /// Metadata did not contain the requested topic partition.
    UnknownTopicOrPartition {
        /// Kafka topic name.
        topic: String,
        /// Kafka partition index.
        partition: i32,
    },
    /// A custom producer partitioner selected a partition absent from metadata.
    InvalidPartition {
        /// Kafka topic name.
        topic: String,
        /// Partition index selected by the custom partitioner.
        partition: i32,
    },
    /// A position operation targeted a topic partition that is not assigned.
    UnassignedTopicPartition {
        /// Kafka topic name.
        topic: String,
        /// Kafka partition index.
        partition: i32,
    },
    /// A split consumer partition queue reached its configured bound.
    PartitionQueueFull {
        /// Kafka topic name.
        topic: String,
        /// Kafka partition index.
        partition: i32,
        /// Configured queue capacity.
        capacity: usize,
    },
    /// Metadata did not contain a usable leader for a topic partition.
    MissingLeader {
        /// Kafka topic name.
        topic: String,
        /// Kafka partition index.
        partition: i32,
    },
    /// Metadata referenced a broker node that was not present in the broker list.
    MissingBroker {
        /// Kafka broker node ID.
        node_id: i32,
    },
    /// A DescribeGroups response omitted the requested group.
    MissingGroupDescription {
        /// Requested consumer group ID.
        group_id: String,
    },
    /// A DeleteGroups response omitted the requested group.
    MissingDeleteGroupResult {
        /// Requested consumer group ID.
        group_id: String,
    },
    /// A broker returned a per-entry response with a different count than its request.
    ResponseCountMismatch {
        /// Kafka request family that returned the inconsistent response.
        operation: &'static str,
        /// Number of entries sent by the client.
        expected: usize,
        /// Number of entries returned by the broker.
        actual: usize,
    },
    /// SASL security protocol was selected without configuring credentials.
    MissingSaslCredentials,
    /// SASL authentication response could not be validated.
    InvalidSaslResponse {
        /// SASL mechanism being authenticated.
        mechanism: &'static str,
        /// Redacted validation failure reason.
        reason: &'static str,
    },
    /// An asynchronous OAUTHBEARER token provider exceeded the client timeout.
    OAuthBearerTokenTimeout {
        /// Timeout applied to the provider call in milliseconds.
        timeout_ms: u64,
    },
    /// The broker outcome of an EndTxn request could not be observed.
    TransactionOutcomeUnknown {
        /// Transaction operation whose outcome is unknown.
        operation: &'static str,
    },
    /// A transactional producer can no longer safely issue transaction commands.
    TransactionProducerDefunct,
    /// Kafka returned a non-zero broker error code.
    Broker {
        /// Raw Kafka broker error code.
        code: i16,
        /// Operation context for the broker error.
        context: String,
    },
    /// A Kafka request exceeded the configured request timeout.
    RequestTimedOut {
        /// Timeout in milliseconds.
        timeout_ms: u64,
    },
    /// A broker response frame exceeded the configured allocation limit.
    ResponseTooLarge {
        /// Response payload bytes declared by the broker.
        size: usize,
        /// Configured maximum response payload bytes.
        max: usize,
    },
    /// TLS configuration could not be built.
    TlsConfig {
        /// Redacted TLS configuration failure reason.
        reason: String,
    },
    /// Configured or derived TLS server name is invalid.
    InvalidTlsServerName {
        /// Original configured or derived server name value.
        server: String,
    },
    /// A static consumer group instance ID was configured as an empty string.
    InvalidGroupInstanceId,
    /// A consumer-group topic subscription pattern failed local validation.
    InvalidTopicPattern {
        /// The configured regular expression.
        pattern: String,
        /// The regular-expression compiler's diagnostic.
        reason: String,
    },
    /// A SCRAM credential request failed local validation before reaching Kafka.
    InvalidScramCredential {
        /// Redacted validation failure reason.
        reason: &'static str,
    },
    /// A public builder received a value outside the client's supported range.
    InvalidConfiguration {
        /// Configuration field that failed validation.
        field: &'static str,
        /// Stable, non-secret explanation of the validation failure.
        reason: &'static str,
    },
    /// The requested Kafka feature is not implemented by this alpha API yet.
    Unsupported(&'static str),
    /// I/O failure while connecting to or communicating with a broker.
    Io(std::io::Error),
    /// A background Tokio task failed before returning its Kafka result.
    TaskJoin(tokio::task::JoinError),
    /// Kafka protocol encoding or decoding failure.
    Protocol(kafrust_protocol::Error),
}

impl Error {
    /// Returns the classified broker error kind when this is a broker error.
    pub fn broker_error_kind(&self) -> Option<BrokerErrorKind> {
        match self {
            Self::Broker { code, .. } => Some(BrokerErrorKind::from_code(*code)),
            _ => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingBootstrapServer => f.write_str("missing Kafka bootstrap server"),
            Self::UnknownTopicOrPartition { topic, partition } => {
                write!(f, "unknown topic or partition {topic}-{partition}")
            }
            Self::InvalidPartition { topic, partition } => {
                write!(
                    f,
                    "custom partitioner selected invalid topic partition {topic}-{partition}"
                )
            }
            Self::UnassignedTopicPartition { topic, partition } => {
                write!(f, "unassigned topic partition {topic}-{partition}")
            }
            Self::PartitionQueueFull {
                topic,
                partition,
                capacity,
            } => write!(
                f,
                "partition queue for {topic}-{partition} is full (capacity {capacity})"
            ),
            Self::MissingLeader { topic, partition } => {
                write!(f, "missing leader for topic partition {topic}-{partition}")
            }
            Self::MissingBroker { node_id } => {
                write!(f, "missing broker metadata for node {node_id}")
            }
            Self::MissingGroupDescription { group_id } => {
                write!(f, "missing description for consumer group {group_id}")
            }
            Self::MissingDeleteGroupResult { group_id } => {
                write!(f, "missing delete result for consumer group {group_id}")
            }
            Self::ResponseCountMismatch {
                operation,
                expected,
                actual,
            } => write!(
                f,
                "{operation} response count mismatch: expected {expected}, got {actual}"
            ),
            Self::MissingSaslCredentials => f.write_str("missing Kafka SASL credentials"),
            Self::InvalidSaslResponse { mechanism, reason } => {
                write!(f, "invalid SASL {mechanism} response: {reason}")
            }
            Self::OAuthBearerTokenTimeout { timeout_ms } => write!(
                f,
                "SASL/OAUTHBEARER token provider timed out after {timeout_ms}ms"
            ),
            Self::TransactionOutcomeUnknown { operation } => write!(
                f,
                "transaction {operation} outcome is unknown; discard the producer"
            ),
            Self::TransactionProducerDefunct => {
                f.write_str("transactional producer is defunct; discard the producer")
            }
            Self::Broker { code, context } => write!(f, "Kafka broker error {code}: {context}"),
            Self::RequestTimedOut { timeout_ms } => {
                write!(f, "Kafka request timed out after {timeout_ms}ms")
            }
            Self::ResponseTooLarge { size, max } => {
                write!(
                    f,
                    "Kafka response frame of {size} bytes exceeds configured maximum of {max} bytes"
                )
            }
            Self::TlsConfig { reason } => write!(f, "TLS configuration error: {reason}"),
            Self::InvalidTlsServerName { server } => {
                write!(f, "invalid TLS server name {server}")
            }
            Self::InvalidGroupInstanceId => {
                f.write_str("consumer group instance ID must not be empty")
            }
            Self::InvalidTopicPattern { pattern, reason } => {
                write!(
                    f,
                    "invalid consumer group topic pattern {pattern:?}: {reason}"
                )
            }
            Self::InvalidScramCredential { reason } => {
                write!(f, "invalid SCRAM credential: {reason}")
            }
            Self::InvalidConfiguration { field, reason } => {
                write!(f, "invalid Kafka configuration field {field}: {reason}")
            }
            Self::Unsupported(feature) => write!(f, "unsupported feature: {feature}"),
            Self::Io(error) => write!(f, "I/O error: {error}"),
            Self::TaskJoin(error) => write!(f, "background task join error: {error}"),
            Self::Protocol(error) => write!(f, "Kafka protocol error: {error}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::TaskJoin(error) => Some(error),
            Self::Protocol(error) => Some(error),
            Self::MissingBootstrapServer
            | Self::UnknownTopicOrPartition { .. }
            | Self::InvalidPartition { .. }
            | Self::UnassignedTopicPartition { .. }
            | Self::PartitionQueueFull { .. }
            | Self::MissingLeader { .. }
            | Self::MissingBroker { .. }
            | Self::MissingGroupDescription { .. }
            | Self::MissingDeleteGroupResult { .. }
            | Self::ResponseCountMismatch { .. }
            | Self::MissingSaslCredentials
            | Self::InvalidSaslResponse { .. }
            | Self::OAuthBearerTokenTimeout { .. }
            | Self::TransactionOutcomeUnknown { .. }
            | Self::TransactionProducerDefunct
            | Self::Broker { .. }
            | Self::RequestTimedOut { .. }
            | Self::ResponseTooLarge { .. }
            | Self::TlsConfig { .. }
            | Self::InvalidTlsServerName { .. }
            | Self::InvalidGroupInstanceId
            | Self::InvalidTopicPattern { .. }
            | Self::InvalidScramCredential { .. }
            | Self::InvalidConfiguration { .. }
            | Self::Unsupported(_) => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Self::Io(error)
    }
}

impl From<tokio::task::JoinError> for Error {
    fn from(error: tokio::task::JoinError) -> Self {
        Self::TaskJoin(error)
    }
}

impl From<kafrust_protocol::Error> for Error {
    fn from(error: kafrust_protocol::Error) -> Self {
        Self::Protocol(error)
    }
}

#[cfg(test)]
mod tests {
    use super::{BrokerErrorKind, Error};

    #[test]
    fn classifies_known_broker_error_codes() {
        assert_eq!(
            BrokerErrorKind::from_code(3),
            BrokerErrorKind::UnknownTopicOrPartition
        );
        assert_eq!(
            BrokerErrorKind::from_code(1),
            BrokerErrorKind::OffsetOutOfRange
        );
        assert_eq!(
            BrokerErrorKind::from_code(16),
            BrokerErrorKind::NotCoordinator
        );
        assert_eq!(
            BrokerErrorKind::from_code(14),
            BrokerErrorKind::CoordinatorLoadInProgress
        );
        assert_eq!(
            BrokerErrorKind::from_code(27),
            BrokerErrorKind::RebalanceInProgress
        );
        assert_eq!(
            BrokerErrorKind::from_code(36),
            BrokerErrorKind::TopicAlreadyExists
        );
        assert_eq!(
            BrokerErrorKind::from_code(41),
            BrokerErrorKind::NotController
        );
        assert_eq!(
            BrokerErrorKind::from_code(45),
            BrokerErrorKind::OutOfOrderSequenceNumber
        );
        assert_eq!(
            BrokerErrorKind::from_code(46),
            BrokerErrorKind::DuplicateSequenceNumber
        );
        assert_eq!(
            BrokerErrorKind::from_code(47),
            BrokerErrorKind::InvalidProducerEpoch
        );
        assert_eq!(
            BrokerErrorKind::from_code(51),
            BrokerErrorKind::ConcurrentTransactions
        );
        assert_eq!(
            BrokerErrorKind::from_code(69),
            BrokerErrorKind::GroupIdNotFound
        );
        assert_eq!(
            BrokerErrorKind::from_code(82),
            BrokerErrorKind::FencedInstanceId
        );
        assert_eq!(
            BrokerErrorKind::from_code(86),
            BrokerErrorKind::GroupSubscribedToTopic
        );
        assert_eq!(
            BrokerErrorKind::from_code(90),
            BrokerErrorKind::ProducerFenced
        );
        assert_eq!(
            BrokerErrorKind::from_code(74),
            BrokerErrorKind::FencedLeaderEpoch
        );
        assert_eq!(
            BrokerErrorKind::from_code(75),
            BrokerErrorKind::UnknownLeaderEpoch
        );
        assert_eq!(
            BrokerErrorKind::from_code(70),
            BrokerErrorKind::InvalidFetchSessionEpoch
        );
        assert_eq!(
            BrokerErrorKind::from_code(83),
            BrokerErrorKind::EligibleLeadersNotAvailable
        );
        assert_eq!(
            BrokerErrorKind::from_code(84),
            BrokerErrorKind::ElectionNotNeeded
        );
        assert_eq!(
            BrokerErrorKind::from_code(85),
            BrokerErrorKind::NoReassignmentInProgress
        );
        assert_eq!(BrokerErrorKind::from_code(999), BrokerErrorKind::Unknown);
    }

    #[test]
    fn exposes_broker_error_kind_from_error() {
        let error = Error::Broker {
            code: 7,
            context: "produce orders-0".to_owned(),
        };

        assert_eq!(
            error.broker_error_kind(),
            Some(BrokerErrorKind::RequestTimedOut)
        );
    }
}