kafkit-client 0.1.2

Kafka 4.0+ pure Rust 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
//! Producer API for sending records and managing transactions.
//!
//! ```no_run
//! # async fn example() -> kafkit_client::Result<()> {
//! use kafkit_client::{KafkaClient, KafkaMessage};
//!
//! let producer = KafkaClient::new("localhost:9092")
//!     .topic("orders")
//!     .producer()
//!     .connect()
//!     .await?;
//!
//! producer.send(KafkaMessage::new("created")).await?;
//! producer.flush().await?;
//! producer.shutdown().await?;
//! # Ok(())
//! # }
//! ```
//!
mod accumulator;
mod partitioner;
mod request;
mod sender;
mod transaction;

use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::{debug, instrument};

use self::sender::Sender;
use crate::config::ProducerConfig;
use crate::types::{CommitOffset, ConsumerGroupMetadata, KafkaMessage, ProduceAck, ProduceRecord};
use crate::{Error, ProducerError, Result};

/// A Kafka producer with batching, retries, idempotence, and transactions.
pub struct KafkaProducer {
    producer_runtime: ProducerRuntime,
    join: JoinHandle<()>,
    default_topic: Option<String>,
    default_partition: Option<i32>,
}

impl KafkaProducer {
    #[instrument(
        name = "producer.connect",
        level = "debug",
        skip(config),
        fields(
            bootstrap_server_count = config.bootstrap_servers.len(),
            client_id = %config.client_id,
            transactional = config.is_transactional(),
            acks = config.acks
        )
    )]
    /// Connects to Kafka and returns the client.
    pub async fn connect(config: ProducerConfig) -> Result<Self> {
        if config.is_transactional() && config.acks != -1 {
            return Err(ProducerError::TransactionalRequiresAcksAll.into());
        }
        if config.is_idempotent() && config.acks != -1 {
            return Err(ProducerError::IdempotenceRequiresAcksAll.into());
        }
        if config.is_idempotent() && config.max_retries == 0 {
            return Err(ProducerError::IdempotenceRequiresRetries.into());
        }

        let (tx, rx) = mpsc::channel(64);
        let sender = Sender::new(config);
        let join = tokio::spawn(async move {
            sender.run(rx).await;
        });

        let producer = Self {
            producer_runtime: ProducerRuntime::new(tx),
            join,
            default_topic: None,
            default_partition: None,
        };
        if let Err(error) = producer.warm_up().await {
            producer.join.abort();
            return Err(error);
        }
        debug!("producer connected");
        Ok(producer)
    }

    /// Sets defaults and returns the updated value.
    pub fn with_defaults(
        mut self,
        default_topic: Option<String>,
        default_partition: Option<i32>,
    ) -> Self {
        self.default_topic = default_topic;
        self.default_partition = default_partition;
        self
    }

    /// Send Message.
    pub async fn send_message(&self, message: KafkaMessage) -> Result<ProduceAck> {
        let record = message
            .into_record(self.default_topic.as_deref(), self.default_partition)
            .map_err(Error::from)?;
        self.send_record(record).await
    }

    /// Send Value.
    pub async fn send_value(&self, value: impl Into<bytes::Bytes>) -> Result<ProduceAck> {
        self.send(value).await
    }

    /// Send To.
    pub async fn send_to(
        &self,
        topic: impl Into<String>,
        value: impl Into<bytes::Bytes>,
    ) -> Result<ProduceAck> {
        let message = KafkaMessage::new(value).with_topic(topic);
        self.send_message(message).await
    }

    #[instrument(name = "producer.send", level = "debug", skip(self, input))]
    /// Sends a record.
    pub async fn send(&self, input: impl Into<KafkaMessage>) -> Result<ProduceAck> {
        let record = input
            .into()
            .into_record(self.default_topic.as_deref(), self.default_partition)
            .map_err(Error::from)?;
        self.send_record(record).await
    }

    #[instrument(
        name = "producer.send_record",
        level = "debug",
        skip(self, record),
        fields(
            topic = %record.topic,
            partition = record.partition,
            value_len = record.value.as_ref().map(|value| value.len()).unwrap_or(0),
            tombstone = record.value.is_none(),
            headers = record.headers.len(),
            has_key = record.key.is_some(),
            has_timestamp = record.timestamp.is_some()
        )
    )]
    async fn send_record(&self, record: ProduceRecord) -> Result<ProduceAck> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::AppendRecord {
                    record,
                    reply: reply_tx,
                },
                ProducerError::ThreadStoppedBefore {
                    operation: "accepting the produce request",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "answering the produce request",
            })?
    }

    #[instrument(name = "producer.flush", level = "debug", skip(self))]
    /// Waits for buffered records to be sent.
    pub async fn flush(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::Flush { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "flushing buffered records",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring { operation: "flush" })?
    }

    #[instrument(name = "producer.init_transactions", level = "debug", skip(self))]
    /// Init Transactions.
    pub async fn init_transactions(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::InitTransactions { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "initializing transactions",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "initializing transactions",
            })?
    }

    #[instrument(name = "producer.begin_transaction", level = "debug", skip(self))]
    /// Begin Transaction.
    pub async fn begin_transaction(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::BeginTransaction { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "beginning the transaction",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "beginning the transaction",
            })?
    }

    #[instrument(name = "producer.commit_transaction", level = "debug", skip(self))]
    /// Commit Transaction.
    pub async fn commit_transaction(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::CommitTransaction { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "committing the transaction",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "committing the transaction",
            })?
    }

    #[instrument(name = "producer.abort_transaction", level = "debug", skip(self))]
    /// Abort Transaction.
    pub async fn abort_transaction(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::AbortTransaction { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "aborting the transaction",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "aborting the transaction",
            })?
    }

    #[instrument(
        name = "producer.send_offsets_to_transaction",
        level = "debug",
        skip(self, offsets, group_metadata),
        fields(
            offset_count = offsets.len(),
            group_id = %group_metadata.group_id,
            generation_id = group_metadata.generation_id,
            has_instance_id = group_metadata.group_instance_id.is_some()
        )
    )]
    /// Send Offsets To Transaction.
    pub async fn send_offsets_to_transaction(
        &self,
        offsets: Vec<CommitOffset>,
        group_metadata: ConsumerGroupMetadata,
    ) -> Result<()> {
        if offsets.is_empty() {
            return Ok(());
        }

        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::SendOffsetsToTransaction {
                    offsets,
                    group_metadata,
                    reply: reply_tx,
                },
                ProducerError::ThreadStoppedBefore {
                    operation: "sending offsets to the transaction",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "send_offsets_to_transaction",
            })?
    }

    #[instrument(name = "producer.shutdown", level = "debug", skip(self))]
    /// Shuts the client down and waits for in-flight work to finish.
    pub async fn shutdown(self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::Shutdown { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "shutdown",
                },
            )
            .await?;

        let result = reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "shutdown",
            })?;
        self.join.await.map_err(ProducerError::Join)?;
        result
    }

    #[instrument(name = "producer.warm_up", level = "trace", skip(self))]
    async fn warm_up(&self) -> Result<()> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.producer_runtime
            .send(
                ProducerRuntimeEvent::WarmUp { reply: reply_tx },
                ProducerError::ThreadStoppedBefore {
                    operation: "startup",
                },
            )
            .await?;
        reply_rx
            .await
            .map_err(|_| ProducerError::ThreadStoppedDuring {
                operation: "startup",
            })?
    }
}

struct ProducerRuntime {
    tx: mpsc::Sender<ProducerRuntimeEvent>,
}

impl ProducerRuntime {
    fn new(tx: mpsc::Sender<ProducerRuntimeEvent>) -> Self {
        Self { tx }
    }

    async fn send(&self, event: ProducerRuntimeEvent, stopped_error: ProducerError) -> Result<()> {
        self.tx.send(event).await.map_err(|_| stopped_error.into())
    }
}

/// Producer Runtime Event.
pub enum ProducerRuntimeEvent {
    WarmUp {
        reply: oneshot::Sender<Result<()>>,
    },
    BeginTransaction {
        reply: oneshot::Sender<Result<()>>,
    },
    InitTransactions {
        reply: oneshot::Sender<Result<()>>,
    },
    AppendRecord {
        record: ProduceRecord,
        reply: oneshot::Sender<Result<ProduceAck>>,
    },
    Flush {
        reply: oneshot::Sender<Result<()>>,
    },
    CommitTransaction {
        reply: oneshot::Sender<Result<()>>,
    },
    AbortTransaction {
        reply: oneshot::Sender<Result<()>>,
    },
    SendOffsetsToTransaction {
        offsets: Vec<CommitOffset>,
        group_metadata: ConsumerGroupMetadata,
        reply: oneshot::Sender<Result<()>>,
    },
    Shutdown {
        reply: oneshot::Sender<Result<()>>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ProducerConfig;

    #[tokio::test]
    async fn transactional_connect_requires_acks_all() {
        let result = KafkaProducer::connect(
            ProducerConfig::new("127.0.0.1:1")
                .with_transactional_id("tx-a")
                .with_acks(1),
        )
        .await;

        assert!(matches!(
            result,
            Err(crate::Error::Producer(
                ProducerError::TransactionalRequiresAcksAll
            ))
        ));
    }

    #[tokio::test]
    async fn idempotent_connect_requires_acks_all() {
        let result = KafkaProducer::connect(
            ProducerConfig::new("127.0.0.1:1")
                .with_enable_idempotence(true)
                .with_acks(1),
        )
        .await;

        assert!(matches!(
            result,
            Err(crate::Error::Producer(
                ProducerError::IdempotenceRequiresAcksAll
            ))
        ));
    }

    #[tokio::test]
    async fn idempotent_connect_requires_retries() {
        let result = KafkaProducer::connect(
            ProducerConfig::new("127.0.0.1:1")
                .with_enable_idempotence(true)
                .with_max_retries(0),
        )
        .await;

        assert!(matches!(
            result,
            Err(crate::Error::Producer(
                ProducerError::IdempotenceRequiresRetries
            ))
        ));
    }
}