Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

17.2 KB
Raw Blame
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::kafka::batch_context::{BatchConsumerContext, ConsumerCommand, ConsumerCommandReceiver};
use crate::kafka::batch_message::{Batch, BatchError, KafkaMessage};
use crate::kafka::error_handling;
use crate::kafka::metrics_consts::{
    BATCH_CONSUMER_BATCH_COLLECTION_DURATION_MS, BATCH_CONSUMER_BATCH_FILL_RATIO,
    BATCH_CONSUMER_BATCH_SIZE, BATCH_CONSUMER_KAFKA_ERROR, BATCH_CONSUMER_MESSAGES_RECEIVED,
    BATCH_CONSUMER_SEEK_DURATION_MS, BATCH_CONSUMER_SEEK_ERROR,
};
use crate::kafka::offset_tracker::OffsetTracker;
use crate::kafka::rebalance_handler::RebalanceHandler;
use crate::kafka::types::Partition;

use anyhow::{Context, Result};
use async_trait::async_trait;
use futures_util::StreamExt;
use rdkafka::config::ClientConfig;
use rdkafka::consumer::{CommitMode, Consumer, MessageStream, StreamConsumer};
use rdkafka::error::KafkaResult;
use rdkafka::message::Message;
use rdkafka::TopicPartitionList;
use serde::Deserialize;
use std::collections::HashMap;
use tokio::sync::mpsc;
use tokio::sync::oneshot::Receiver;
use tracing::{error, info, warn};

#[async_trait]
pub trait BatchConsumerProcessor<T>: Send + Sync {
    async fn process_batch(&self, messages: Vec<KafkaMessage<T>>) -> Result<()>;
}

/// Callback invoked after a successful Kafka offset commit.
///
/// Implementations receive the committed offsets (partition → next offset to consume)
/// and can perform side effects like updating local metadata. Failures should be
/// handled internally (non-fatal).
#[async_trait]
pub trait OnCommit: Send + Sync {
    async fn on_commit(&self, offsets: &HashMap<Partition, i64>);
}

pub struct BatchConsumer<T> {
    consumer: StreamConsumer<BatchConsumerContext>,

    // group offset commit interval
    commit_interval: Duration,

    // batch configs - how big should batches get
    // and how long to wait before we publish one
    // for downstream processing
    batch_size: usize,
    batch_timeout: Duration,

    // where we send batches after consuming them
    processor: Arc<dyn BatchConsumerProcessor<T>>,

    // tracks processed offsets per partition for safe commits
    offset_tracker: Arc<OffsetTracker>,

    // shutdown signal from parent process which
    // we assume will be wrapping start_consumption
    // in a spawned thread
    shutdown_rx: Receiver<()>,

    // receiver for consumer commands (e.g., seek partitions after checkpoint import, resume partitions)
    consumer_command_rx: ConsumerCommandReceiver,

    // timeout for seek_partitions after checkpoint import
    seek_timeout: Duration,

    // optional callback invoked after successful offset commits
    on_commit: Option<Arc<dyn OnCommit>>,
}

impl<T> BatchConsumer<T>
where
    T: for<'de> Deserialize<'de>,
{
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config: &ClientConfig,
        rebalance_handler: Arc<dyn RebalanceHandler>,
        processor: Arc<dyn BatchConsumerProcessor<T>>,
        offset_tracker: Arc<OffsetTracker>,
        on_commit: Option<Arc<dyn OnCommit>>,
        shutdown_rx: Receiver<()>,
        topic: &str,
        batch_size: usize,
        batch_timeout: Duration,
        commit_interval: Duration,
        seek_timeout: Duration,
    ) -> Result<Self> {
        // Create channel for consumer commands (e.g., seek partitions after checkpoint import, resume partitions)
        let (consumer_command_tx, consumer_command_rx) = mpsc::unbounded_channel();

        let consumer_ctx = BatchConsumerContext::new(rebalance_handler, consumer_command_tx);

        let consumer: StreamConsumer<BatchConsumerContext> = config
            .create_with_context(consumer_ctx)
            .context("Failed to create Kafka consumer")?;

        let err_msg = format!("Failed to subscribe to topic: {topic}");
        consumer.subscribe(&[topic]).context(err_msg)?;

        Ok(Self {
            consumer,
            commit_interval,
            batch_size,
            batch_timeout,
            processor,
            offset_tracker,
            on_commit,
            shutdown_rx,
            consumer_command_rx,
            seek_timeout,
        })
    }

    /// Start consuming messages in a loop with graceful shutdown support
    pub async fn start_consumption(mut self) -> Result<()> {
        info!("Starting batch Kafka message consumption...");

        let batch_timeout = self.batch_timeout;
        let batch_size = self.batch_size;
        let mut commit_interval = tokio::time::interval(self.commit_interval);

        let consumer = self.consumer;
        let mut stream = consumer.stream();

        loop {
            tokio::select! {
                // Check for shutdown signal
                _ = &mut self.shutdown_rx => {
                    info!("Shutdown signal received, starting graceful shutdown");
                    break;
                }

                // Handle consumer commands (e.g., seek partitions after checkpoint import, resume partitions)
                Some(command) = self.consumer_command_rx.recv() => {
                    match command {
                        ConsumerCommand::Resume(partitions) => {
                            let partition_count = partitions.count();
                            info!(
                                partition_count = partition_count,
                                "Received resume command for partitions after store setup"
                            );
                            if let Err(e) = consumer.resume(&partitions) {
                                error!(
                                    partition_count = partition_count,
                                    error = ?e,
                                    "Failed to resume partitions"
                                );
                            } else {
                                info!(
                                    partition_count = partition_count,
                                    "Successfully resumed partitions - messages will now be delivered"
                                );
                            }
                        }
                        ConsumerCommand::SeekPartitions(offsets) => {
                            let partition_count = offsets.count();
                            info!(
                                partition_count = partition_count,
                                "Received seek_partitions command after checkpoint import"
                            );
                            let seek_start = Instant::now();
                            match consumer.seek_partitions(offsets, self.seek_timeout) {
                                Ok(result_tpl) => {
                                    metrics::histogram!(BATCH_CONSUMER_SEEK_DURATION_MS)
                                        .record(seek_start.elapsed().as_millis() as f64);
                                    let mut error_count = 0u64;
                                    for elem in result_tpl.elements() {
                                        if elem.error().is_err() {
                                            warn!(
                                                topic = elem.topic(),
                                                partition = elem.partition(),
                                                error = ?elem.error(),
                                                "Failed to seek partition"
                                            );
                                            error_count += 1;
                                        }
                                    }
                                    if error_count > 0 {
                                        metrics::counter!(BATCH_CONSUMER_SEEK_ERROR)
                                            .increment(error_count);
                                    }
                                    info!(
                                        partition_count = partition_count,
                                        error_count = error_count,
                                        "Batch seek_partitions completed"
                                    );
                                }
                                Err(e) => {
                                    metrics::counter!(BATCH_CONSUMER_SEEK_ERROR)
                                        .increment(partition_count as u64);
                                    error!(
                                        error = %e,
                                        partition_count = partition_count,
                                        "seek_partitions call failed"
                                    );
                                }
                            }
                        }
                    }
                }

                // Poll for messages
                batch_result = Self::consume_batch(&mut stream, batch_size, batch_timeout) => {
                    match batch_result {
                        Ok((batch, collection_duration)) => {
                            // Record batch collection duration
                            metrics::histogram!(BATCH_CONSUMER_BATCH_COLLECTION_DURATION_MS)
                                .record(collection_duration.as_millis() as f64);

                            // if there are no errors or messages to report, skip sending
                            if batch.is_empty() {
                                continue;
                            }
                            let message_count = batch.message_count();
                            metrics::counter!(BATCH_CONSUMER_MESSAGES_RECEIVED, "status" => "success")
                                .increment(message_count as u64);
                            metrics::counter!(BATCH_CONSUMER_MESSAGES_RECEIVED, "status" => "error")
                                .increment(batch.error_count() as u64);
                            metrics::histogram!(BATCH_CONSUMER_BATCH_SIZE)
                                .record(message_count as f64);

                            // Record batch fill ratio (how full the batch was)
                            let fill_ratio = message_count as f64 / batch_size as f64;
                            metrics::histogram!(BATCH_CONSUMER_BATCH_FILL_RATIO)
                                .record(fill_ratio);

                            let (messages, _errors) = batch.unpack();
                            if let Err(e) = self.processor.process_batch(messages).await {
                                // TODO: stat this
                                error!("Error processing batch: {e:#}");
                            }
                        }

                        Err(e) => {
                            // Kafka error handler logs/stats these in detail prior to bubbling up here
                            return Err(e.into());
                        }
                    }
                }

                // Commit offsets periodically from the offset tracker
                // The offset tracker contains offsets that have been successfully processed
                // by partition workers, ensuring we only commit what's been processed
                _ = commit_interval.tick() => {
                    Self::commit_tracked_offsets(&consumer, &self.offset_tracker, &self.on_commit);
                }
            }
        }
        info!("Batch consumer loop shutting down...");

        info!("Graceful shutdown completed");

        Ok(())
    }

    // NOT FOR PROD - handy for integration smoke tests
    pub fn inner_consumer(&self) -> &StreamConsumer<BatchConsumerContext> {
        &self.consumer
    }

    /// Commit offsets from the offset tracker to Kafka
    ///
    /// This commits only offsets that have been successfully processed by partition
    /// workers, ensuring we never commit offsets for messages that haven't been processed.
    ///
    /// Commits are skipped during rebalancing to avoid committing offsets for partitions
    /// that may have been revoked.
    ///
    /// After a successful commit, updates the offset tracker's committed offsets which
    /// are used for checkpointing to track the true recovery point.
    fn commit_tracked_offsets(
        consumer: &StreamConsumer<BatchConsumerContext>,
        offset_tracker: &OffsetTracker,
        on_commit: &Option<Arc<dyn OnCommit>>,
    ) {
        let offsets = match offset_tracker.get_committable_offsets() {
            Ok(offsets) => offsets,
            Err(crate::kafka::offset_tracker::OffsetTrackerError::RebalanceInProgress) => {
                info!("Skipping offset commit during rebalancing");
                metrics::counter!(
                    crate::kafka::metrics_consts::OFFSET_TRACKER_COMMITS_SKIPPED_REBALANCING
                )
                .increment(1);
                return;
            }
        };

        if offsets.is_empty() {
            return;
        }

        let mut list = TopicPartitionList::new();
        for (partition, next_offset) in &offsets {
            let _ = list.add_partition_offset(
                partition.topic(),
                partition.partition_number(),
                rdkafka::Offset::Offset(*next_offset),
            );
        }

        // Use synchronous commit so we know exactly when offsets are committed.
        // This is important for checkpointing - we need to track the committed
        // offset (not just processed) for disaster recovery.
        match consumer.commit(&list, CommitMode::Sync) {
            Ok(_) => {
                info!("Committed offsets for {} partitions", offsets.len());
                // Update the offset tracker with the committed offsets
                // These are used for checkpointing to track the true recovery point
                offset_tracker.mark_committed(&offsets);

                // Notify the on_commit callback (fire-and-forget).
                // Failures are non-fatal — handled internally by the callback.
                if let Some(callback) = on_commit {
                    let callback = Arc::clone(callback);
                    let offsets = offsets.clone();
                    tokio::spawn(async move {
                        callback.on_commit(&offsets).await;
                    });
                }
            }
            Err(e) => {
                warn!("Failed to commit tracked offsets: {e:#}");
            }
        }
    }

    /// Consumes a batch of messages based on the configured batch size and timeout.
    /// Returns the batch and the duration spent collecting it.
    async fn consume_batch(
        stream: &mut MessageStream<'_, BatchConsumerContext>,
        batch_size: usize,
        batch_timeout: Duration,
    ) -> KafkaResult<(Batch<T>, Duration)> {
        let start = Instant::now();
        let mut batch = Batch::new_with_size_hint(batch_size);
        let mut batch_complete = tokio::time::interval(batch_timeout);
        let mut kafka_error_count = 0;

        loop {
            tokio::select! {
                // Exit if the batch timeout is reached before a full batch is collected
                _ = batch_complete.tick() => {
                    break;
                }

                // Try to get next message within the remaining batch time
                next_msg = stream.next() => {
                    match next_msg {
                        Some(Ok(borrowed_message)) => {
                            match KafkaMessage::<T>::from_borrowed_message(&borrowed_message) {
                                Ok(kafka_message) => {
                                    batch.push_message(kafka_message);
                                    kafka_error_count = 0;
                                }
                                Err(e) => {
                                    let wrapped_err = e.context("Error deserializing message");
                                    batch.push_error(BatchError::new(
                                        wrapped_err,
                                        Some(Partition::new(
                                            borrowed_message.topic().to_owned(),
                                            borrowed_message.partition(),
                                        )),
                                        Some(borrowed_message.offset()),
                                    ));
                                }
                            }
                        }
                        Some(Err(e)) => {
                            kafka_error_count += 1;
                            if let Some(ke) =
                                error_handling::handle_kafka_error(e, kafka_error_count, BATCH_CONSUMER_KAFKA_ERROR).await
                            {
                                // only fatal, unhandleable, or retriable errors that have
                                // exhausted attempts will be returned, which breaks the
                                // consume loop and ends processing, causing pod to reset
                                return Err(ke);
                            }
                        }
                        None => {
                            // Stream ended - return what we have
                            break;
                        }
                    }

                    // if the batch is now at size, bail out and return it
                    if batch.message_count() >= batch_size {
                        break;
                    }
                }
            }
        }

        Ok((batch, start.elapsed()))
    }
}