kacrab 0.1.0

A Kafka client for Rust, built from the protocol up.
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
//! Record-batch construction for minimal produce requests.

use std::time::{SystemTime, UNIX_EPOCH};

use bytes::{Bytes, BytesMut};
use kacrab_protocol::record::{Record, RecordBatch};

use super::{
    config::ProducerCompression, error::Result, record::ProducerRecord,
    transaction::ProducerBatchState,
};

/// Kafka record-batch magic v2 is required for producer id, epoch, sequence,
/// timestamp fields, and compression attributes used by modern brokers.
const RECORD_BATCH_MAGIC_V2: i8 = 2;
/// Kafka sentinel for a non-idempotent producer id.
const NO_PRODUCER_ID: i64 = -1;
/// Kafka sentinel for non-idempotent producer epoch/base sequence.
const NO_PRODUCER_EPOCH_OR_SEQUENCE: i16 = -1;
/// Kacrab does not set per-record attributes yet; batch-level compression owns
/// the current attribute bits.
const DEFAULT_RECORD_ATTRIBUTES: i8 = 0;
/// Kafka uses zero base offset for request-side record batches; brokers assign
/// the final log offset in produce responses.
#[cfg(test)]
const REQUEST_RECORD_BATCH_BASE_OFFSET: i64 = 0;
/// Partition leader epoch is unknown on produce requests from clients.
const UNKNOWN_PARTITION_LEADER_EPOCH: i32 = -1;

#[cfg(all(test, feature = "lz4"))]
pub(crate) fn encode_record_batch_with_compression(
    records: &[ProducerRecord],
    compression: ProducerCompression,
) -> Result<Bytes> {
    let (records, timestamp_base) = producer_records(records);
    encode_records(
        records,
        compression,
        None,
        REQUEST_RECORD_BATCH_BASE_OFFSET,
        timestamp_base,
    )
}

pub(crate) fn encode_record_batch_with_producer_state_at_offset(
    records: &[ProducerRecord],
    compression: ProducerCompression,
    producer_state: Option<ProducerBatchState>,
    base_offset: i64,
) -> Result<Bytes> {
    let (records, timestamp_base) = producer_records(records);
    encode_records(
        records,
        compression,
        producer_state,
        base_offset,
        timestamp_base,
    )
}

#[cfg(test)]
pub(crate) fn encode_record_batch_with_producer_state_at_offset_into(
    records: &[ProducerRecord],
    compression: ProducerCompression,
    producer_state: Option<ProducerBatchState>,
    base_offset: i64,
    bytes: &mut BytesMut,
) -> Result<Bytes> {
    let (records, timestamp_base) = producer_records(records);
    let batch = record_batch(
        records,
        compression,
        producer_state,
        base_offset,
        timestamp_base,
    );
    encode_record_batch_into(&batch, compression, bytes)
}

pub(crate) fn encode_record_batch_with_producer_state_at_offset_into_buffer(
    records: &[ProducerRecord],
    compression: ProducerCompression,
    producer_state: Option<ProducerBatchState>,
    base_offset: i64,
    bytes: &mut BytesMut,
) -> Result<()> {
    let (records, timestamp_base) = producer_records(records);
    let batch = record_batch(
        records,
        compression,
        producer_state,
        base_offset,
        timestamp_base,
    );
    encode_record_batch_into_buffer(&batch, compression, bytes)
}

fn encode_records(
    records: Vec<Record>,
    compression: ProducerCompression,
    producer_state: Option<ProducerBatchState>,
    base_offset: i64,
    timestamp_base: RecordBatchTimestamps,
) -> Result<Bytes> {
    let mut bytes = BytesMut::new();
    let batch = record_batch(
        records,
        compression,
        producer_state,
        base_offset,
        timestamp_base,
    );
    encode_record_batch_into(&batch, compression, &mut bytes)
}

fn record_batch(
    records: Vec<Record>,
    compression: ProducerCompression,
    producer_state: Option<ProducerBatchState>,
    base_offset: i64,
    timestamp_base: RecordBatchTimestamps,
) -> RecordBatch {
    let (producer_id, producer_epoch, base_sequence) = producer_state.map_or_else(
        || {
            (
                NO_PRODUCER_ID,
                NO_PRODUCER_EPOCH_OR_SEQUENCE,
                i32::from(NO_PRODUCER_EPOCH_OR_SEQUENCE),
            )
        },
        |state| {
            (
                state.identity.producer_id,
                state.identity.producer_epoch,
                state.base_sequence,
            )
        },
    );
    RecordBatch {
        base_offset,
        partition_leader_epoch: UNKNOWN_PARTITION_LEADER_EPOCH,
        magic: RECORD_BATCH_MAGIC_V2,
        attributes: compression.codec as i16,
        last_offset_delta: i32::try_from(records.len().saturating_sub(1)).unwrap_or(i32::MAX),
        first_timestamp: timestamp_base.first_timestamp,
        max_timestamp: timestamp_base.max_timestamp,
        producer_id,
        producer_epoch,
        base_sequence,
        records,
    }
}

fn encode_record_batch_into(
    batch: &RecordBatch,
    compression: ProducerCompression,
    bytes: &mut BytesMut,
) -> Result<Bytes> {
    encode_record_batch_into_buffer(batch, compression, bytes)?;
    Ok(bytes.split_to(bytes.len()).freeze())
}

fn encode_record_batch_into_buffer(
    batch: &RecordBatch,
    compression: ProducerCompression,
    bytes: &mut BytesMut,
) -> Result<()> {
    bytes.clear();
    bytes.reserve(batch.uncompressed_encoded_len()?);
    batch.encode_with_compression_level(bytes, compression.level)?;
    Ok(())
}

fn producer_records(records: &[ProducerRecord]) -> (Vec<Record>, RecordBatchTimestamps) {
    let fallback = current_time_ms();
    let first_timestamp = records
        .first()
        .and_then(|record| record.timestamp_ms)
        .unwrap_or(fallback);
    let mut max_timestamp = first_timestamp;
    let records = records
        .iter()
        .enumerate()
        .map(|(index, record)| {
            max_timestamp = max_timestamp.max(record.timestamp_ms.unwrap_or(fallback));
            let timestamp_delta = record
                .timestamp_ms
                .map_or(0, |timestamp| timestamp.saturating_sub(first_timestamp));
            Record {
                attributes: DEFAULT_RECORD_ATTRIBUTES,
                timestamp_delta,
                offset_delta: i32::try_from(index).unwrap_or(i32::MAX),
                key: record.key.clone(),
                value: record.value.clone(),
                headers: clone_record_headers(record),
            }
        })
        .collect();
    (
        records,
        RecordBatchTimestamps {
            first_timestamp,
            max_timestamp,
        },
    )
}

fn clone_record_headers(record: &ProducerRecord) -> Vec<kacrab_protocol::record::RecordHeader> {
    record.headers.clone()
}

#[derive(Debug, Clone, Copy)]
struct RecordBatchTimestamps {
    first_timestamp: i64,
    max_timestamp: i64,
}

pub(crate) fn current_time_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| {
            i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
        })
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::expect_used,
        clippy::missing_assert_message,
        clippy::unwrap_used,
        reason = "Unit test fixtures fail fastest with contextual unwrap/expect calls."
    )]

    use std::time::{Duration, Instant};

    use bytes::{Bytes, BytesMut};
    use kacrab_protocol::record::RecordBatch;

    use super::{
        REQUEST_RECORD_BATCH_BASE_OFFSET, encode_record_batch_with_producer_state_at_offset,
        encode_record_batch_with_producer_state_at_offset_into,
    };
    use crate::producer::{
        AccumulatorConfig, ProducerBatchState, ProducerCompression, ProducerIdentity,
        ProducerRecord, RecordAccumulator,
    };

    #[test]
    fn record_batch_sets_idempotent_producer_fields() {
        let encoded = encode_record_batch_with_producer_state_at_offset(
            &[ProducerRecord::new("orders", 0).value(Bytes::from_static(b"value"))],
            ProducerCompression::default(),
            Some(ProducerBatchState {
                identity: ProducerIdentity {
                    producer_id: 42,
                    producer_epoch: 3,
                },
                base_sequence: 7,
            }),
            REQUEST_RECORD_BATCH_BASE_OFFSET,
        )
        .expect("idempotent batch should encode");
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("record batch");

        assert_eq!(decoded.producer_id, 42);
        assert_eq!(decoded.producer_epoch, 3);
        assert_eq!(decoded.base_sequence, 7);
    }

    #[test]
    fn record_batch_can_set_request_side_base_offset() {
        let encoded = encode_record_batch_with_producer_state_at_offset(
            &[ProducerRecord::new("orders", 0).value(Bytes::from_static(b"value"))],
            ProducerCompression::default(),
            None,
            9,
        )
        .expect("batch should encode");
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("record batch");

        assert_eq!(decoded.base_offset, 9);
    }

    #[test]
    fn record_batch_encoder_can_write_into_reusable_buffer() {
        let records = [ProducerRecord::new("orders", 0)
            .try_timestamp_ms(1_000)
            .expect("timestamp")
            .value(Bytes::from_static(b"value"))];
        let expected = encode_record_batch_with_producer_state_at_offset(
            &records,
            ProducerCompression::default(),
            None,
            REQUEST_RECORD_BATCH_BASE_OFFSET,
        )
        .expect("batch should encode");
        let mut buffer = BytesMut::with_capacity(4 * 1024);
        buffer.extend_from_slice(b"stale");

        let encoded = encode_record_batch_with_producer_state_at_offset_into(
            &records,
            ProducerCompression::default(),
            None,
            REQUEST_RECORD_BATCH_BASE_OFFSET,
            &mut buffer,
        )
        .expect("batch should encode into caller buffer");

        assert_eq!(encoded, expected);
        assert!(buffer.is_empty());
    }

    #[test]
    fn record_batch_sets_create_time_timestamp_from_clock() {
        let before = super::current_time_ms();
        let encoded = encode_record_batch_with_producer_state_at_offset(
            &[ProducerRecord::new("orders", 0).value(Bytes::from_static(b"value"))],
            ProducerCompression::default(),
            None,
            REQUEST_RECORD_BATCH_BASE_OFFSET,
        )
        .expect("batch should encode");
        let after = super::current_time_ms();
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("record batch");

        assert!(decoded.first_timestamp >= before);
        assert!(decoded.first_timestamp <= after);
        assert_eq!(decoded.max_timestamp, decoded.first_timestamp);
        assert_eq!(
            decoded.records.first().expect("one record").timestamp_delta,
            0
        );
    }

    #[test]
    fn accumulator_append_freezes_create_time_before_later_encode_like_java() {
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(1)
                .buffer_memory(1024)
                .linger(Duration::from_secs(1)),
        );
        let before_append = super::current_time_ms();
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"value")),
                Instant::now(),
            )
            .expect("append record without user timestamp");
        let after_append = super::current_time_ms();

        std::thread::sleep(Duration::from_millis(15));
        let drained = accumulator.drain_all();
        let encoded = encode_record_batch_with_producer_state_at_offset(
            &drained[0].records,
            ProducerCompression::default(),
            None,
            REQUEST_RECORD_BATCH_BASE_OFFSET,
        )
        .expect("batch should encode");
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("record batch");

        assert!(decoded.first_timestamp >= before_append);
        assert!(decoded.first_timestamp <= after_append);
        assert_eq!(decoded.max_timestamp, decoded.first_timestamp);
    }

    #[test]
    fn record_batch_encodes_user_timestamps_and_headers() {
        let encoded = encode_record_batch_with_producer_state_at_offset(
            &[
                ProducerRecord::new("orders", 0)
                    .try_timestamp_ms(1_000)
                    .expect("first timestamp")
                    .header("trace-id", Bytes::from_static(b"abc"))
                    .value(Bytes::from_static(b"first")),
                ProducerRecord::new("orders", 0)
                    .try_timestamp_ms(1_025)
                    .expect("second timestamp")
                    .header_null("null-header")
                    .value(Bytes::from_static(b"second")),
            ],
            ProducerCompression::default(),
            None,
            REQUEST_RECORD_BATCH_BASE_OFFSET,
        )
        .expect("batch should encode");
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("record batch");

        assert_eq!(decoded.first_timestamp, 1_000);
        assert_eq!(decoded.max_timestamp, 1_025);
        assert_eq!(decoded.records[0].timestamp_delta, 0);
        assert_eq!(decoded.records[1].timestamp_delta, 25);
        assert_eq!(decoded.records[0].headers.len(), 1);
        assert_eq!(
            decoded.records[0].headers[0].key,
            Bytes::from_static(b"trace-id")
        );
        assert_eq!(
            decoded.records[0].headers[0].value,
            Some(Bytes::from_static(b"abc"))
        );
        assert_eq!(decoded.records[1].headers.len(), 1);
        assert_eq!(
            decoded.records[1].headers[0].key,
            Bytes::from_static(b"null-header")
        );
        assert_eq!(decoded.records[1].headers[0].value, None);
    }

    #[cfg(feature = "lz4")]
    #[test]
    fn record_batch_sets_and_round_trips_compression_codec() {
        use kacrab_protocol::compression::Compression;

        use super::encode_record_batch_with_compression;

        let encoded = encode_record_batch_with_compression(
            &[ProducerRecord::new("orders", 0)
                .key(Bytes::from_static(b"k"))
                .value(Bytes::from_static(b"value"))],
            ProducerCompression {
                codec: Compression::Lz4,
                level: Some(9),
            },
        )
        .expect("compressed batch should encode");
        let mut encoded = encoded;
        let decoded = RecordBatch::decode(&mut encoded).expect("compressed batch should decode");

        assert_eq!(
            decoded.compression().expect("compression"),
            Compression::Lz4
        );
        let record = decoded.records.first().expect("one record");
        assert_eq!(record.key, Some(Bytes::from_static(b"k")));
        assert_eq!(record.value, Some(Bytes::from_static(b"value")));
    }
}