Skip to main content

rdkafka_sys/
types.rs

1//! Aliases for types defined in the auto-generated bindings.
2
3use std::convert::TryFrom;
4use std::error::Error;
5use std::ffi::CStr;
6use std::fmt;
7
8use crate::bindings;
9use crate::helpers;
10
11// TYPES
12
13/// Native rdkafka client.
14pub type RDKafka = bindings::rd_kafka_t;
15
16/// Native rdkafka configuration.
17pub type RDKafkaConf = bindings::rd_kafka_conf_t;
18
19/// Native rdkafka message.
20pub type RDKafkaMessage = bindings::rd_kafka_message_t;
21
22/// Native rdkafka topic.
23pub type RDKafkaTopic = bindings::rd_kafka_topic_t;
24
25/// Native rdkafka topic configuration.
26pub type RDKafkaTopicConf = bindings::rd_kafka_topic_conf_t;
27
28/// Native rdkafka topic partition.
29pub type RDKafkaTopicPartition = bindings::rd_kafka_topic_partition_t;
30
31/// Native rdkafka topic partition list.
32pub type RDKafkaTopicPartitionList = bindings::rd_kafka_topic_partition_list_t;
33
34/// Native rdkafka metadata container.
35pub type RDKafkaMetadata = bindings::rd_kafka_metadata_t;
36
37/// Native rdkafka topic information.
38pub type RDKafkaMetadataTopic = bindings::rd_kafka_metadata_topic_t;
39
40/// Native rdkafka partition information.
41pub type RDKafkaMetadataPartition = bindings::rd_kafka_metadata_partition_t;
42
43/// Native rdkafka broker information.
44pub type RDKafkaMetadataBroker = bindings::rd_kafka_metadata_broker_t;
45
46/// Native rdkafka consumer group metadata.
47pub type RDKafkaConsumerGroupMetadata = bindings::rd_kafka_consumer_group_metadata_t;
48
49/// Native rdkafka state.
50pub type RDKafkaState = bindings::rd_kafka_s;
51
52/// Native rdkafka list of groups.
53pub type RDKafkaGroupList = bindings::rd_kafka_group_list;
54
55/// Native rdkafka group information.
56pub type RDKafkaGroupInfo = bindings::rd_kafka_group_info;
57
58/// Native rdkafka group member information.
59pub type RDKafkaGroupMemberInfo = bindings::rd_kafka_group_member_info;
60
61/// Native rdkafka group member information.
62pub type RDKafkaHeaders = bindings::rd_kafka_headers_t;
63
64/// Native rdkafka queue.
65pub type RDKafkaQueue = bindings::rd_kafka_queue_t;
66
67/// Native rdkafka new topic object.
68pub type RDKafkaNewTopic = bindings::rd_kafka_NewTopic_t;
69
70/// Native rdkafka delete topic object.
71pub type RDKafkaDeleteTopic = bindings::rd_kafka_DeleteTopic_t;
72
73/// Native rdkafka new partitions object.
74pub type RDKafkaNewPartitions = bindings::rd_kafka_NewPartitions_t;
75
76/// Native rdkafka delete records object.
77pub type RDKafkaDeleteRecords = bindings::rd_kafka_DeleteRecords_t;
78
79/// Native rdkafka config resource.
80pub type RDKafkaConfigResource = bindings::rd_kafka_ConfigResource_t;
81
82/// Native rdkafka event.
83pub type RDKafkaEvent = bindings::rd_kafka_event_t;
84
85/// Native rdkafka admin options.
86pub type RDKafkaAdminOptions = bindings::rd_kafka_AdminOptions_t;
87
88/// Native rdkafka topic result.
89pub type RDKafkaTopicResult = bindings::rd_kafka_topic_result_t;
90
91// ENUMS
92
93/// Client types.
94pub use bindings::rd_kafka_type_t as RDKafkaType;
95
96/// Configuration result.
97pub use bindings::rd_kafka_conf_res_t as RDKafkaConfRes;
98
99/// Response error.
100pub use bindings::rd_kafka_resp_err_t as RDKafkaRespErr;
101
102/// Admin operation.
103pub use bindings::rd_kafka_admin_op_t as RDKafkaAdminOp;
104
105/// Config resource type.
106pub use bindings::rd_kafka_ResourceType_t as RDKafkaResourceType;
107
108/// Config source.
109pub use bindings::rd_kafka_ConfigSource_t as RDKafkaConfigSource;
110
111// Errors enum
112
113/// Native rdkafka error code.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115#[non_exhaustive]
116pub enum RDKafkaErrorCode {
117    #[doc(hidden)]
118    Begin = -200,
119    /// Received message is incorrect.
120    BadMessage = -199,
121    /// Bad/unknown compression.
122    BadCompression = -198,
123    /// Broker is going away.
124    BrokerDestroy = -197,
125    /// Generic failure.
126    Fail = -196,
127    /// Broker transport failure.
128    BrokerTransportFailure = -195,
129    /// Critical system resource.
130    CriticalSystemResource = -194,
131    /// Failed to resolve broker.
132    Resolve = -193,
133    /// Produced message timed out.
134    MessageTimedOut = -192,
135    /// Reached the end of the topic+partition queue on the broker. Not really an error.
136    PartitionEOF = -191,
137    /// Permanent: Partition does not exist in cluster.
138    UnknownPartition = -190,
139    /// File or filesystem error.
140    FileSystem = -189,
141    /// Permanent: Topic does not exist in cluster.
142    UnknownTopic = -188,
143    /// All broker connections are down.
144    AllBrokersDown = -187,
145    /// Invalid argument, or invalid configuration.
146    InvalidArgument = -186,
147    /// Operation timed out.
148    OperationTimedOut = -185,
149    /// Queue is full.
150    QueueFull = -184,
151    /// ISR count < required.acks.
152    ISRInsufficient = -183,
153    /// Broker node update.
154    NodeUpdate = -182,
155    /// SSL error.
156    SSL = -181,
157    /// Waiting for coordinator to become available.
158    WaitingForCoordinator = -180,
159    /// Unknown client group.
160    UnknownGroup = -179,
161    /// Operation in progress.
162    InProgress = -178,
163    /// Previous operation in progress, wait for it to finish.
164    PreviousInProgress = -177,
165    /// This operation would interfere with an existing subscription.
166    ExistingSubscription = -176,
167    /// Assigned partitions (rebalance_cb).
168    AssignPartitions = -175,
169    /// Revoked partitions (rebalance_cb).
170    RevokePartitions = -174,
171    /// Conflicting use.
172    Conflict = -173,
173    /// Wrong state.
174    State = -172,
175    /// Unknown protocol.
176    UnknownProtocol = -171,
177    /// Not implemented.
178    NotImplemented = -170,
179    /// Authentication failure.
180    Authentication = -169,
181    /// No stored offset.
182    NoOffset = -168,
183    /// Outdated.
184    Outdated = -167,
185    /// Timed out in queue.
186    TimedOutQueue = -166,
187    /// Feature not supported by broker.
188    UnsupportedFeature = -165,
189    /// Awaiting cache update.
190    WaitCache = -164,
191    /// Operation interrupted (e.g., due to yield).
192    Interrupted = -163,
193    /// Key serialization error.
194    KeySerialization = -162,
195    /// Value serialization error.
196    ValueSerialization = -161,
197    /// Key deserialization error.
198    KeyDeserialization = -160,
199    /// Value deserialization error.
200    ValueDeserialization = -159,
201    /// Partial response.
202    Partial = -158,
203    /// Modification attempted on read-only object.
204    ReadOnly = -157,
205    /// No such entry or item not found.
206    NoEnt = -156,
207    /// Read underflow.
208    Underflow = -155,
209    /// Invalid type.
210    InvalidType = -154,
211    /// Retry operation.
212    Retry = -153,
213    /// Purged in queue.
214    PurgeQueue = -152,
215    /// Purged in flight.
216    PurgeInflight = -151,
217    /// Fatal error: see rd_kafka_fatal_error().
218    Fatal = -150,
219    /// Inconsistent state.
220    Inconsistent = -149,
221    /// Gap-less ordering would not be guaranteed if proceeding.
222    GaplessGuarantee = -148,
223    /// Maximum poll interval exceeded.
224    PollExceeded = -147,
225    /// Unknown broker.
226    UnknownBroker = -146,
227    /// Functionality not configured.
228    NotConfigured = -145,
229    /// Instance has been fenced.
230    Fenced = -144,
231    /// Application generated error.
232    Application = -143,
233    /// Assignment lost.
234    AssignmentLost = -142,
235    /// No operation performed.
236    Noop = -141,
237    /// No offset to automatically reset to.
238    AutoOffsetReset = -140,
239    /// Partition log truncation detected
240    LogTruncation = -139,
241    /// A different record in the batch was invalid and this message failed
242    /// persisting.
243    InvalidDifferentRecord = -138,
244    /// Broker is going away but client isn't terminating.
245    DestroyBroker = -137,
246    #[doc(hidden)]
247    End = -100,
248    /// Unknown broker error.
249    Unknown = -1,
250    /// Success.
251    NoError = 0,
252    /// Offset out of range.
253    OffsetOutOfRange = 1,
254    /// Invalid message.
255    InvalidMessage = 2,
256    /// Unknown topic or partition.
257    UnknownTopicOrPartition = 3,
258    /// Invalid message size.
259    InvalidMessageSize = 4,
260    /// Leader not available.
261    LeaderNotAvailable = 5,
262    /// Not leader for partition.
263    NotLeaderForPartition = 6,
264    /// Request timed out.
265    RequestTimedOut = 7,
266    /// Broker not available.
267    BrokerNotAvailable = 8,
268    /// Replica not available.
269    ReplicaNotAvailable = 9,
270    /// Message size too large.
271    MessageSizeTooLarge = 10,
272    /// Stale controller epoch code.
273    StaleControllerEpoch = 11,
274    /// Offset metadata string too large.
275    OffsetMetadataTooLarge = 12,
276    /// Broker disconnected before response received.
277    NetworkException = 13,
278    /// Coordinator load in progress.
279    CoordinatorLoadInProgress = 14,
280    /// Coordinator not available.
281    CoordinatorNotAvailable = 15,
282    /// Not coordinator.
283    NotCoordinator = 16,
284    /// Invalid topic.
285    InvalidTopic = 17,
286    /// Message batch larger than configured server segment size.
287    MessageBatchTooLarge = 18,
288    /// Not enough in-sync replicas.
289    NotEnoughReplicas = 19,
290    /// Message(s) written to insufficient number of in-sync replicas.
291    NotEnoughReplicasAfterAppend = 20,
292    /// Invalid required acks value.
293    InvalidRequiredAcks = 21,
294    /// Specified group generation id is not valid.
295    IllegalGeneration = 22,
296    /// Inconsistent group protocol.
297    InconsistentGroupProtocol = 23,
298    /// Invalid group.id.
299    InvalidGroupId = 24,
300    /// Unknown member.
301    UnknownMemberId = 25,
302    /// Invalid session timeout.
303    InvalidSessionTimeout = 26,
304    /// Group rebalance in progress.
305    RebalanceInProgress = 27,
306    /// Commit offset data size is not valid.
307    InvalidCommitOffsetSize = 28,
308    /// Topic authorization failed.
309    TopicAuthorizationFailed = 29,
310    /// Group authorization failed.
311    GroupAuthorizationFailed = 30,
312    /// Cluster authorization failed.
313    ClusterAuthorizationFailed = 31,
314    /// Invalid timestamp.
315    InvalidTimestamp = 32,
316    /// Unsupported SASL mechanism.
317    UnsupportedSASLMechanism = 33,
318    /// Illegal SASL state.
319    IllegalSASLState = 34,
320    /// Unsupported version.
321    UnsupportedVersion = 35,
322    /// Topic already exists.
323    TopicAlreadyExists = 36,
324    /// Invalid number of partitions.
325    InvalidPartitions = 37,
326    /// Invalid replication factor.
327    InvalidReplicationFactor = 38,
328    /// Invalid replica assignment.
329    InvalidReplicaAssignment = 39,
330    /// Invalid config.
331    InvalidConfig = 40,
332    /// Not controller for cluster.
333    NotController = 41,
334    /// Invalid request.
335    InvalidRequest = 42,
336    /// Message format on broker does not support request.
337    UnsupportedForMessageFormat = 43,
338    /// Policy violation.
339    PolicyViolation = 44,
340    /// Broker received an out of order sequence number.
341    OutOfOrderSequenceNumber = 45,
342    /// Broker received a duplicate sequence number.
343    DuplicateSequenceNumber = 46,
344    /// Producer attempted an operation with an old epoch.
345    InvalidProducerEpoch = 47,
346    /// Producer attempted a transactional operation in an invalid state.
347    InvalidTransactionalState = 48,
348    /// Producer attempted to use a producer id which is currently assigned to
349    /// its transactional id.
350    InvalidProducerIdMapping = 49,
351    /// Transaction timeout is larger than the maxi value allowed by the
352    /// broker's max.transaction.timeout.ms.
353    InvalidTransactionTimeout = 50,
354    /// Producer attempted to update a transaction while another concurrent
355    /// operation on the same transaction was ongoing.
356    ConcurrentTransactions = 51,
357    /// Indicates that the transaction coordinator sending a WriteTxnMarker is
358    /// no longer the current coordinator for a given producer.
359    TransactionCoordinatorFenced = 52,
360    /// Transactional Id authorization failed.
361    TransactionalIdAuthorizationFailed = 53,
362    /// Security features are disabled.
363    SecurityDisabled = 54,
364    /// Operation not attempted.
365    OperationNotAttempted = 55,
366    /// Disk error when trying to access log file on the disk.
367    KafkaStorageError = 56,
368    /// The user-specified log directory is not found in the broker config.
369    LogDirNotFound = 57,
370    /// SASL Authentication failed.
371    SaslAuthenticationFailed = 58,
372    /// Unknown Producer Id.
373    UnknownProducerId = 59,
374    /// Partition reassignment is in progress.
375    ReassignmentInProgress = 60,
376    /// Delegation Token feature is not enabled.
377    DelegationTokenAuthDisabled = 61,
378    /// Delegation Token is not found on server.
379    DelegationTokenNotFound = 62,
380    /// Specified Principal is not valid Owner/Renewer.
381    DelegationTokenOwnerMismatch = 63,
382    /// Delegation Token requests are not allowed on this connection.
383    DelegationTokenRequestNotAllowed = 64,
384    /// Delegation Token authorization failed.
385    DelegationTokenAuthorizationFailed = 65,
386    /// Delegation Token is expired.
387    DelegationTokenExpired = 66,
388    /// Supplied principalType is not supported.
389    InvalidPrincipalType = 67,
390    /// The group is not empty.
391    NonEmptyGroup = 68,
392    /// The group id does not exist.
393    GroupIdNotFound = 69,
394    /// The fetch session ID was not found.
395    FetchSessionIdNotFound = 70,
396    /// The fetch session epoch is invalid.
397    InvalidFetchSessionEpoch = 71,
398    /// No matching listener.
399    ListenerNotFound = 72,
400    /// Topic deletion is disabled.
401    TopicDeletionDisabled = 73,
402    /// Leader epoch is older than broker epoch.
403    FencedLeaderEpoch = 74,
404    /// Leader epoch is newer than broker epoch.
405    UnknownLeaderEpoch = 75,
406    /// Unsupported compression type.
407    UnsupportedCompressionType = 76,
408    /// Broker epoch has changed.
409    StaleBrokerEpoch = 77,
410    /// Leader high watermark is not caught up.
411    OffsetNotAvailable = 78,
412    /// Group member needs a valid member ID.
413    MemberIdRequired = 79,
414    /// Preferred leader was not available.
415    PreferredLeaderNotAvailable = 80,
416    /// Consumer group has reached maximum size.
417    GroupMaxSizeReached = 81,
418    /// Static consumer fenced by other consumer with same group.instance.id.
419    FencedInstanceId = 82,
420    /// Eligible partition leaders are not available.
421    EligibleLeadersNotAvailable = 83,
422    /// Leader election not needed for topic partition.
423    ElectionNotNeeded = 84,
424    /// No partition reassignment is in progress.
425    NoReassignmentInProgress = 85,
426    /// Deleting offsets of a topic while the consumer group is subscribed to
427    /// it.
428    GroupSubscribedToTopic = 86,
429    /// Broker failed to validate record.
430    InvalidRecord = 87,
431    /// There are unstable offsets that need to be cleared.
432    UnstableOffsetCommit = 88,
433    /// Throttling quota has been exceeded.
434    ThrottlingQuotaExceeded = 89,
435    /// There is a newer producer with the same transactional ID which fences
436    /// the current one.
437    ProducerFenced = 90,
438    /// Request illegally referred to resource that does not exist.
439    ResourceNotFound = 91,
440    /// Request illegally referred to the same resource twice.
441    DuplicateResource = 92,
442    /// Requested credential would not meet criteria for acceptability.
443    UnacceptableCredential = 93,
444    /// Either the sender or recipient of a voter-only request is not one of the
445    /// expected voters.
446    InconsistentVoterSet = 94,
447    /// Invalid update version.
448    InvalidUpdateVersion = 95,
449    /// Unable to update finalized features due to server error.
450    FeatureUpdateFailed = 96,
451    /// Request principal deserialization failed during forwarding.
452    PrincipalDeserializationFailure = 97,
453    /// Unknown topic ID.
454    UnknownTopicId = 100,
455    /// The log's topic ID did not match the topic ID in the request.
456    InconsistentTopicId = 103,
457    /// The member epoch is fenced by the group coordinator.
458    FencedMemberEpoch = 110,
459    /// The instance ID is still used by another member in the consumer group.
460    UnreleasedInstanceId = 111,
461    /// The assignor or its version range is not supported by the consumer
462    /// group.
463    UnsupportedAssignor = 112,
464    /// The member epoch is stale.
465    StaleMemberEpoch = 113,
466    /// The request was sent to an endpoint of the wrong type.
467    MismatchedEndpointType = 114,
468    /// This endpoint type is not supported yet.
469    UnsupportedEndpointType = 115,
470    /// This controller ID is not known.
471    UnknownControllerId = 116,
472    /// The client sent a push telemetry request with an invalid or outdated
473    /// subscription ID.
474    UnknownSubscriptionId = 117,
475    /// The client sent a push telemetry request larger than the maximum size
476    /// that the broker will accept.
477    TelemetryTooLarge = 118,
478    /// The controller has considered the broker registration to be invalid.
479    InvalidRegistration = 119,
480    /// The server encountered an error with the transaction. The client can
481    /// abort the transaction to continue using this transactional ID.
482    TransactionAbortable = 120,
483    /// The record state is invalid. The acknowledgement of delivery could not
484    /// be completed.
485    InvalidRecordState = 121,
486    /// The share session was not found.
487    ShareSessionNotFound = 122,
488    /// The share session epoch is invalid.
489    InvalidShareSessionEpoch = 123,
490    /// The share coordinator rejected the request because the share-group
491    /// state epoch did not match.
492    FencedStateEpoch = 124,
493    /// The voter key doesn't match the receiving replica's key.
494    InvalidVoterKey = 125,
495    /// The voter is already part of the set of voters.
496    DuplicateVoter = 126,
497    /// The voter is not part of the set of voters.
498    VoterNotFound = 127,
499    /// The regular expression is not valid.
500    InvalidRegularExpression = 128,
501    /// Client metadata is stale, client should rebootstrap to obtain new
502    /// metadata.
503    RebootstrapRequired = 129,
504    /// The supplied topology is invalid.
505    StreamsInvalidTopology = 130,
506    /// The supplied topology epoch is invalid.
507    StreamsInvalidTopologyEpoch = 131,
508    /// The supplied topology epoch is outdated.
509    StreamsTopologyFenced = 132,
510    /// The limit of share sessions has been reached.
511    ShareSessionLimitReached = 133,
512    #[doc(hidden)]
513    EndAll,
514}
515
516impl From<RDKafkaRespErr> for RDKafkaErrorCode {
517    fn from(err: RDKafkaRespErr) -> RDKafkaErrorCode {
518        helpers::rd_kafka_resp_err_t_to_rdkafka_error(err)
519    }
520}
521
522impl fmt::Display for RDKafkaErrorCode {
523    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
524        let description = match RDKafkaRespErr::try_from(*self as i32) {
525            Ok(err) => {
526                let cstr = unsafe { bindings::rd_kafka_err2str(err) };
527                unsafe { CStr::from_ptr(cstr) }
528                    .to_string_lossy()
529                    .into_owned()
530            }
531            Err(_) => "Unknown error".to_owned(),
532        };
533
534        write!(f, "{:?} ({})", self, description)
535    }
536}
537
538impl Error for RDKafkaErrorCode {}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    #[test]
545    fn test_display_error() {
546        let error: RDKafkaErrorCode = RDKafkaRespErr::RD_KAFKA_RESP_ERR__PARTITION_EOF.into();
547        assert_eq!(
548            "PartitionEOF (Broker: No more messages)",
549            format!("{}", error)
550        );
551        assert_eq!("PartitionEOF", format!("{:?}", error));
552    }
553}