spate-kafka 0.1.0

Kafka source and producer sink for the Spate framework, built on rdkafka: a single consumer per process with partition queues fanned across pipeline threads, and a delivery-report-acknowledged producer sink. Applications should depend on the `spate` facade crate with the `kafka` feature.
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
//! The I/O half of the Kafka sink: produce a sealed batch and await every
//! delivery report.
//!
//! `write_batch` runs in two phases. First it parses **all** frames back
//! into messages — validating the connector's framing before anything is
//! enqueued, and fixing the delivery countdown's total up front (counting
//! per send would race reports arriving mid-loop). Then it produces each
//! message, absorbing librdkafka queue-full pushback with a bounded async
//! backoff, and awaits the countdown under a deadline derived from the
//! configured delivery timeout. Only when every report confirmed does it
//! return `Ok` — the framework's durable-ack point.
//!
//! Failure semantics are honest at-least-once: a retryable error (report
//! timeout, broker transport failure) makes the framework retry the whole
//! sealed batch, re-producing any already-delivered prefix — duplicates,
//! never loss. Errors that idempotence or configuration cannot heal
//! (authorization, unknown topic, a fenced idempotent producer) are fatal:
//! the batch is abandoned, the watermark stalls, and the pipeline fails
//! fast instead of spinning.

use crate::sink::context::{BatchInflight, SinkContext};
use crate::sink::frame::{FrameParser, MessageRef};
use crate::sink::metrics::KafkaSinkStatsMetrics;
use rdkafka::error::RDKafkaErrorCode;
use rdkafka::message::{Header, OwnedHeaders};
use rdkafka::producer::{BaseRecord, Producer, ThreadedProducer};
use spate_core::error::{ErrorClass, SinkError};
use spate_core::metrics::Meter;
use spate_core::sink::{SealedBatch, ShardWriter};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Extra time granted past `delivery_timeout` for the countdown await:
/// `delivery.timeout.ms` bounds time-to-report only from each message's
/// *enqueue*, and the send loop itself may have spent time in queue-full
/// backoff.
const DELIVERY_GRACE: Duration = Duration::from_secs(5);

/// Queue-full backoff bounds: librdkafka signals queue-full synchronously
/// from `send`; the writer sleeps and retries that message while the
/// producer's poll thread drains the queue.
const QUEUE_FULL_BACKOFF_INITIAL: Duration = Duration::from_millis(10);
const QUEUE_FULL_BACKOFF_MAX: Duration = Duration::from_millis(250);

/// How long a readiness probe waits for topic metadata.
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);

/// One connected producer endpoint. The sink's shards all clone the same
/// underlying producer (see the config module: statistics soundness and
/// librdkafka's own broker routing both want exactly one client), so this
/// is a cheap `Arc`-backed handle.
pub struct KafkaEndpoint {
    producer: ThreadedProducer<SinkContext>,
    label: String,
}

impl KafkaEndpoint {
    pub(crate) fn new(producer: ThreadedProducer<SinkContext>, label: String) -> Self {
        KafkaEndpoint { producer, label }
    }

    pub(crate) fn label(&self) -> &str {
        &self.label
    }
}

impl Clone for KafkaEndpoint {
    fn clone(&self) -> Self {
        KafkaEndpoint {
            producer: self.producer.clone(),
            label: self.label.clone(),
        }
    }
}

impl std::fmt::Debug for KafkaEndpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KafkaEndpoint")
            .field("label", &self.label)
            .finish_non_exhaustive()
    }
}

/// The Kafka sink's [`ShardWriter`]: parses the connector's framed
/// messages out of a sealed batch, produces them to the configured topic,
/// and treats "every delivery report confirmed" as the durable write.
/// Built by the sink's config factory; cheap to clone.
#[derive(Clone, Debug)]
pub struct KafkaWriter {
    topic: String,
    delivery_timeout: Duration,
    /// Shared with the main producer's context, which publishes through
    /// it; filled by [`attach_metrics`](ShardWriter::attach_metrics).
    stats_slot: Arc<Mutex<Option<KafkaSinkStatsMetrics>>>,
    statistics_enabled: bool,
}

impl KafkaWriter {
    pub(crate) fn new(
        topic: String,
        delivery_timeout: Duration,
        stats_slot: Arc<Mutex<Option<KafkaSinkStatsMetrics>>>,
        statistics_enabled: bool,
    ) -> Self {
        KafkaWriter {
            topic,
            delivery_timeout,
            stats_slot,
            statistics_enabled,
        }
    }

    fn parse_messages<'a>(&self, batch: &'a SealedBatch) -> Result<Vec<MessageRef<'a>>, SinkError> {
        let mut messages = Vec::with_capacity(batch.rows as usize);
        for frame in &batch.frames {
            for message in FrameParser::new(frame) {
                messages.push(message.map_err(|e| SinkError::Client {
                    class: ErrorClass::Fatal,
                    reason: format!("corrupted sink frame (framework bug): {e}"),
                })?);
            }
        }
        if messages.len() as u64 != batch.rows {
            return Err(SinkError::Client {
                class: ErrorClass::Fatal,
                reason: format!(
                    "corrupted sink frame (framework bug): batch claims {} rows \
                     but frames parse to {} messages",
                    batch.rows,
                    messages.len()
                ),
            });
        }
        Ok(messages)
    }
}

impl ShardWriter for KafkaWriter {
    type Endpoint = KafkaEndpoint;

    /// Resolve the `spate_kafka_sink_*` statistics handles into the slot the
    /// producer context publishes through. No-op when `statistics_interval`
    /// is zero — disabled statistics register no families.
    fn attach_metrics(&mut self, meter: Option<Meter>) {
        if !self.statistics_enabled {
            return;
        }
        if let Some(meter) = meter {
            *self.stats_slot.lock().expect("stats slot lock") =
                Some(KafkaSinkStatsMetrics::new(meter));
        }
    }

    async fn write_batch(
        &self,
        endpoint: &KafkaEndpoint,
        batch: &SealedBatch,
    ) -> Result<(), SinkError> {
        // Phase 1: validate framing and fix the countdown total before any
        // message is enqueued.
        let messages = self.parse_messages(batch)?;
        let total = messages.len();
        let inflight = Arc::new(BatchInflight::new(total));
        let send_deadline = Instant::now() + self.delivery_timeout + DELIVERY_GRACE;

        // Phase 2: produce, absorbing queue-full pushback bounded by the
        // deadline. On a definitive send error librdkafka returns the
        // record (and its opaque) without a future report, so the batch
        // fails immediately; already-enqueued messages report into a
        // countdown nobody awaits, which is harmless.
        for message in &messages {
            let mut record: BaseRecord<'_, [u8], [u8], Arc<BatchInflight>> =
                BaseRecord::with_opaque_to(&self.topic, Arc::clone(&inflight));
            if let Some(key) = message.key {
                record = record.key(key);
            }
            if let Some(payload) = message.payload {
                record = record.payload(payload);
            }
            if !message.headers.is_empty() {
                let mut headers = OwnedHeaders::new_with_capacity(message.headers.len());
                for (name, value) in &message.headers {
                    headers = headers.insert(Header {
                        key: name,
                        value: Some(*value),
                    });
                }
                record = record.headers(headers);
            }

            let mut backoff = QUEUE_FULL_BACKOFF_INITIAL;
            loop {
                match endpoint.producer.send(record) {
                    Ok(()) => break,
                    Err((error, returned))
                        if error.rdkafka_error_code() == Some(RDKafkaErrorCode::QueueFull) =>
                    {
                        if Instant::now() >= send_deadline {
                            return Err(SinkError::Client {
                                class: ErrorClass::Retryable,
                                reason: format!(
                                    "producer queue stayed full past the delivery \
                                     deadline ({:?} + {:?} grace); the batch will be \
                                     retried",
                                    self.delivery_timeout, DELIVERY_GRACE
                                ),
                            });
                        }
                        tokio::time::sleep(backoff).await;
                        backoff = (backoff * 2).min(QUEUE_FULL_BACKOFF_MAX);
                        record = returned;
                    }
                    Err((error, _returned)) => {
                        return Err(classify(
                            error.rdkafka_error_code(),
                            &format!("produce to \"{}\" failed: {error}", self.topic),
                        ));
                    }
                }
            }
        }

        // Phase 3: the durable-ack point — every report must confirm.
        // Re-anchor the deadline: `delivery.timeout.ms` bounds each message's
        // time-to-report from *its own* enqueue, and the send loop above may
        // have spent the whole send window in queue-full backoff, so the last
        // messages were only just enqueued. A shared start-anchored deadline
        // would time the wait out while they were still legitimately in flight
        // and force a duplicate-producing retry under sustained queue-full.
        let wait_deadline = Instant::now() + self.delivery_timeout + DELIVERY_GRACE;
        if !inflight.wait(wait_deadline).await {
            return Err(SinkError::Client {
                class: ErrorClass::Retryable,
                reason: format!(
                    "delivery reports missing past the deadline ({:?} + {:?} \
                     grace); the batch will be retried (already-delivered \
                     messages will duplicate — at-least-once)",
                    self.delivery_timeout, DELIVERY_GRACE
                ),
            });
        }
        if let Some((code, reason)) = inflight.first_error() {
            return Err(classify(
                *code,
                &format!(
                    "{} of {total} delivery reports failed; first: {reason}",
                    inflight.failed()
                ),
            ));
        }
        Ok(())
    }

    /// Readiness: fetch the topic's metadata on a blocking thread (the
    /// underlying call blocks) and fail fast on an unknown topic. Runs
    /// against a probe-only producer — see the config module.
    async fn probe(&self, endpoint: &KafkaEndpoint) -> Result<(), SinkError> {
        let producer = endpoint.producer.clone();
        let topic = self.topic.clone();
        let outcome = tokio::task::spawn_blocking(move || {
            let metadata = producer
                .client()
                .fetch_metadata(Some(&topic), PROBE_TIMEOUT)
                .map_err(|e| classify(e.rdkafka_error_code(), &format!("metadata fetch: {e}")))?;
            let Some(meta) = metadata.topics().iter().find(|t| t.name() == topic) else {
                return Err(SinkError::Client {
                    class: ErrorClass::Retryable,
                    reason: format!("metadata response omitted topic \"{topic}\""),
                });
            };
            if let Some(err) = meta.error() {
                let code: RDKafkaErrorCode = err.into();
                return Err(classify(
                    Some(code),
                    &format!("topic \"{topic}\" metadata error: {code}"),
                ));
            }
            if meta.partitions().is_empty() {
                return Err(SinkError::Client {
                    class: ErrorClass::Retryable,
                    reason: format!("topic \"{topic}\" reports no partitions yet"),
                });
            }
            Ok(())
        })
        .await;
        outcome.unwrap_or_else(|join_error| {
            Err(SinkError::Client {
                class: ErrorClass::Retryable,
                reason: format!("probe task failed: {join_error}"),
            })
        })
    }
}

/// Map a produce/report error onto the framework taxonomy.
///
/// Fatal covers what retrying cannot heal: authorization and configuration
/// errors, an unknown topic, a message the broker's limits reject, and the
/// idempotent producer's fenced/fatal states (retrying those would spin
/// until the stalled-watermark deadline instead of surfacing the cause).
/// Everything else — transport failures, timeouts, purges, and unknown
/// codes — is retryable: with idempotence enabled a re-produce is safe
/// in-session, and a batch replay costs duplicates, never loss.
fn classify(code: Option<RDKafkaErrorCode>, reason: &str) -> SinkError {
    use RDKafkaErrorCode as C;
    let class = match code {
        Some(
            C::UnknownTopicOrPartition
            | C::TopicAuthorizationFailed
            | C::ClusterAuthorizationFailed
            | C::Authentication
            | C::SaslAuthenticationFailed
            | C::InvalidRequiredAcks
            | C::MessageSizeTooLarge
            | C::PolicyViolation
            | C::Fatal
            | C::OutOfOrderSequenceNumber
            | C::InvalidProducerEpoch
            | C::InvalidProducerIdMapping,
        ) => ErrorClass::Fatal,
        _ => ErrorClass::Retryable,
    };
    let reason = match code {
        Some(C::UnknownTopicOrPartition) => format!(
            "{reason} — the topic does not exist (create it, or check the \
             sink's `topic` field)"
        ),
        Some(C::MessageSizeTooLarge) => format!(
            "{reason} — a message passed the sink's `max_message_bytes` \
             guard but exceeded the broker/topic `message.max.bytes`; align \
             the two limits"
        ),
        _ => reason.to_string(),
    };
    SinkError::Client { class, reason }
}

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

    fn test_writer(statistics_enabled: bool) -> KafkaWriter {
        KafkaWriter::new(
            "t".to_string(),
            Duration::from_secs(1),
            Arc::new(Mutex::new(None)),
            statistics_enabled,
        )
    }

    fn class_of(err: &SinkError) -> ErrorClass {
        match err {
            SinkError::Client { class, .. } => *class,
            other => panic!("unexpected error shape: {other:?}"),
        }
    }

    #[test]
    fn classify_table() {
        use RDKafkaErrorCode as C;
        let fatal = [
            C::UnknownTopicOrPartition,
            C::TopicAuthorizationFailed,
            C::ClusterAuthorizationFailed,
            C::Authentication,
            C::SaslAuthenticationFailed,
            C::InvalidRequiredAcks,
            C::MessageSizeTooLarge,
            C::PolicyViolation,
            C::Fatal,
            C::OutOfOrderSequenceNumber,
            C::InvalidProducerEpoch,
            C::InvalidProducerIdMapping,
        ];
        for code in fatal {
            assert_eq!(
                class_of(&classify(Some(code), "x")),
                ErrorClass::Fatal,
                "{code:?} must be fatal"
            );
        }
        let retryable = [
            C::MessageTimedOut,
            C::BrokerTransportFailure,
            C::AllBrokersDown,
            C::NotEnoughReplicas,
            C::NotEnoughReplicasAfterAppend,
            C::QueueFull,
            C::PurgeQueue,
            C::PurgeInflight,
            C::InvalidMessage,
            C::RequestTimedOut,
        ];
        for code in retryable {
            assert_eq!(
                class_of(&classify(Some(code), "x")),
                ErrorClass::Retryable,
                "{code:?} must be retryable"
            );
        }
        // Unknown / uncoded errors stay retryable (conservative: replays
        // duplicate, never lose).
        assert_eq!(class_of(&classify(None, "x")), ErrorClass::Retryable);
    }

    #[test]
    fn classify_actionable_messages() {
        let err = classify(Some(RDKafkaErrorCode::UnknownTopicOrPartition), "ctx");
        let SinkError::Client { reason, .. } = err else {
            unreachable!()
        };
        assert!(reason.contains("topic"), "actionable: {reason}");

        let err = classify(Some(RDKafkaErrorCode::MessageSizeTooLarge), "ctx");
        let SinkError::Client { reason, .. } = err else {
            unreachable!()
        };
        assert!(reason.contains("max_message_bytes"), "actionable: {reason}");
        assert!(reason.contains("message.max.bytes"), "actionable: {reason}");
    }

    #[test]
    fn parse_messages_rejects_row_count_mismatch() {
        use bytes::BytesMut;
        let mut frame = BytesMut::new();
        crate::sink::frame::write_message(&mut frame, None, std::iter::empty(), Some(b"p"))
            .unwrap();
        let batch = SealedBatch {
            frames: vec![frame.freeze()],
            rows: 2, // claims two, frame holds one
            bytes: 0,
            dedup_token: "t".to_string(),
        };
        let writer = test_writer(false);
        let err = writer.parse_messages(&batch).unwrap_err();
        assert_eq!(class_of(&err), ErrorClass::Fatal);

        let ok_batch = SealedBatch { rows: 1, ..batch };
        assert_eq!(writer.parse_messages(&ok_batch).unwrap().len(), 1);
    }

    /// Disabled statistics must register no families, and a missing Meter
    /// (custom/reserved component_type) must leave the slot empty — the
    /// producer context then publishes nothing.
    #[test]
    fn attach_metrics_gates_on_statistics_and_meter() {
        let mut disabled = test_writer(false);
        disabled.attach_metrics(Some(Meter::with_namespace(
            "kafka", "orders", "out", "kafka",
        )));
        assert!(disabled.stats_slot.lock().unwrap().is_none());

        let mut no_meter = test_writer(true);
        no_meter.attach_metrics(None);
        assert!(no_meter.stats_slot.lock().unwrap().is_none());

        let mut enabled = test_writer(true);
        enabled.attach_metrics(Some(Meter::with_namespace(
            "kafka", "orders", "out", "kafka",
        )));
        assert!(enabled.stats_slot.lock().unwrap().is_some());
    }
}