Skip to content

The platform for continuously improving AI agents.

17.5 KB
Raw Blame
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use axum::{
    extract::State,
    http::{HeaderMap, HeaderValue, StatusCode, header},
    response::{IntoResponse, Response},
};
use bytes::Bytes;
use opentelemetry_proto::tonic::collector::{
    logs::v1::{ExportLogsServiceRequest, ExportLogsServiceResponse},
    metrics::v1::{ExportMetricsServiceRequest, ExportMetricsServiceResponse},
    trace::v1::{ExportTraceServiceRequest, ExportTraceServiceResponse},
};
use serde::{Serialize, de::DeserializeOwned};
use tokio::sync::{mpsc, watch};
use tokio::time::Instant;

use crate::codec::{self, Format};
use crate::otlp;
use crate::store::{LogEntry, MetricPoint, SpanEventRecord, SpanRecord, Store};

pub const DEFAULT_QUEUE_CAP: usize = 2048;
pub const DEFAULT_FLUSH_MS: u64 = 50;
pub const DEFAULT_MAX_BATCH_SPANS: usize = 2000;
pub const DEFAULT_MAX_BATCH_METRICS: usize = 1000;
pub const DEFAULT_MAX_BATCH_LOGS: usize = 1000;
pub const DEFAULT_MAX_BATCH_EVENTS: usize = 500;

#[derive(Debug, Clone)]
pub struct IngestConfig {
    pub queue_cap: usize,
    pub flush_interval: Duration,
    pub max_batch_spans: usize,
    pub max_batch_metrics: usize,
    pub max_batch_logs: usize,
    pub max_batch_events: usize,
}

impl Default for IngestConfig {
    fn default() -> Self {
        Self {
            queue_cap: DEFAULT_QUEUE_CAP,
            flush_interval: Duration::from_millis(DEFAULT_FLUSH_MS),
            max_batch_spans: DEFAULT_MAX_BATCH_SPANS,
            max_batch_metrics: DEFAULT_MAX_BATCH_METRICS,
            max_batch_logs: DEFAULT_MAX_BATCH_LOGS,
            max_batch_events: DEFAULT_MAX_BATCH_EVENTS,
        }
    }
}

impl IngestConfig {
    pub fn from_env() -> Self {
        let queue_cap = std::env::var("OTEL_INGEST_QUEUE_CAP")
            .ok()
            .and_then(|v| v.trim().parse::<usize>().ok())
            .unwrap_or(DEFAULT_QUEUE_CAP)
            .max(1);
        let flush_ms = std::env::var("OTEL_INGEST_FLUSH_MS")
            .ok()
            .and_then(|v| v.trim().parse::<u64>().ok())
            .unwrap_or(DEFAULT_FLUSH_MS)
            .max(1);
        let max_batch_spans = std::env::var("OTEL_INGEST_MAX_BATCH_SPANS")
            .ok()
            .filter(|v| !v.trim().is_empty())
            .or_else(|| {
                std::env::var("OTEL_INGEST_BATCH_SIZE")
                    .ok()
                    .filter(|v| !v.trim().is_empty())
            })
            .and_then(|v| v.trim().parse::<usize>().ok())
            .unwrap_or(DEFAULT_MAX_BATCH_SPANS)
            .max(1);
        Self {
            queue_cap,
            flush_interval: Duration::from_millis(flush_ms),
            max_batch_spans,
            max_batch_metrics: DEFAULT_MAX_BATCH_METRICS,
            max_batch_logs: DEFAULT_MAX_BATCH_LOGS,
            max_batch_events: DEFAULT_MAX_BATCH_EVENTS,
        }
    }
}

#[derive(Debug)]
pub enum IngestBatch {
    Spans(Vec<SpanRecord>),
    Metrics(Vec<MetricPoint>),
    Logs(Vec<LogEntry>),
    SpanEvents(Vec<SpanEventRecord>),
}

impl IngestBatch {
    fn is_empty(&self) -> bool {
        match self {
            Self::Spans(v) => v.is_empty(),
            Self::Metrics(v) => v.is_empty(),
            Self::Logs(v) => v.is_empty(),
            Self::SpanEvents(v) => v.is_empty(),
        }
    }
}

/// Bounded async ingest queue decoupling HTTP POST handlers from DuckDB write locks.
#[derive(Clone)]
pub struct IngestQueue {
    tx: mpsc::Sender<IngestBatch>,
    invalidated: Arc<AtomicBool>,
}

/// Handle to the background batch flusher task for graceful shutdown.
pub struct IngestFlusher {
    shutdown_tx: watch::Sender<bool>,
    handle: tokio::task::JoinHandle<()>,
}

impl IngestFlusher {
    /// Signals the background flusher to drain all remaining queued batches to DuckDB and stop.
    pub async fn shutdown(self) {
        let _ = self.shutdown_tx.send(true);
        if let Err(err) = self.handle.await {
            tracing::error!(?err, "ingest flusher task panicked during shutdown");
        }
    }
}

impl IngestQueue {
    /// Spawns a bounded channel and background batch flusher that writes accumulated
    /// mega-batches into DuckDB in single transactions.
    pub fn spawn(store: Store, config: IngestConfig) -> (Self, IngestFlusher) {
        let (tx, rx) = mpsc::channel(config.queue_cap.max(1));
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        let invalidated = store.invalidated_flag();
        let handle = tokio::spawn(run_flusher(store, rx, shutdown_rx, config));
        (
            Self { tx, invalidated },
            IngestFlusher {
                shutdown_tx,
                handle,
            },
        )
    }

    /// Creates a raw bounded queue without spawning a flusher (useful for backpressure tests).
    pub fn channel(cap: usize) -> (Self, mpsc::Receiver<IngestBatch>) {
        let (tx, rx) = mpsc::channel(cap.max(1));
        (
            Self {
                tx,
                invalidated: Arc::new(AtomicBool::new(false)),
            },
            rx,
        )
    }

    pub fn is_invalidated(&self) -> bool {
        self.invalidated.load(Ordering::Acquire)
    }

    pub fn try_enqueue(
        &self,
        batch: IngestBatch,
    ) -> Result<(), mpsc::error::TrySendError<IngestBatch>> {
        if batch.is_empty() {
            return Ok(());
        }
        self.tx.try_send(batch)
    }

    pub fn try_enqueue_events(
        &self,
        events: Vec<SpanEventRecord>,
    ) -> Result<(), mpsc::error::TrySendError<IngestBatch>> {
        self.try_enqueue(IngestBatch::SpanEvents(events))
    }

    fn try_reserve(
        &self,
    ) -> Result<mpsc::OwnedPermit<IngestBatch>, mpsc::error::TrySendError<mpsc::Sender<IngestBatch>>>
    {
        self.tx.clone().try_reserve_owned()
    }
}

#[derive(Default)]
struct PendingBatch {
    spans: Vec<SpanRecord>,
    metrics: Vec<MetricPoint>,
    logs: Vec<LogEntry>,
    events: Vec<SpanEventRecord>,
}

impl PendingBatch {
    fn is_empty(&self) -> bool {
        self.spans.is_empty()
            && self.metrics.is_empty()
            && self.logs.is_empty()
            && self.events.is_empty()
    }

    fn push(&mut self, batch: IngestBatch) {
        match batch {
            IngestBatch::Spans(v) => self.spans.extend(v),
            IngestBatch::Metrics(v) => self.metrics.extend(v),
            IngestBatch::Logs(v) => self.logs.extend(v),
            IngestBatch::SpanEvents(v) => self.events.extend(v),
        }
    }

    fn should_flush(&self, cfg: &IngestConfig) -> bool {
        self.spans.len() >= cfg.max_batch_spans
            || self.metrics.len() >= cfg.max_batch_metrics
            || self.logs.len() >= cfg.max_batch_logs
            || self.events.len() >= cfg.max_batch_events
    }
    fn clear(&mut self) {
        self.spans.clear();
        self.metrics.clear();
        self.logs.clear();
        self.events.clear();
    }
}

async fn flush_pending(store: &Store, pending: &mut PendingBatch) {
    if pending.is_empty() {
        return;
    }
    if store.is_invalidated() {
        tracing::warn!(
            dropped_spans = pending.spans.len(),
            dropped_metrics = pending.metrics.len(),
            dropped_logs = pending.logs.len(),
            dropped_events = pending.events.len(),
            "dropping pending ingest batch because DuckDB store is fatally invalidated"
        );
        pending.clear();
        return;
    }
    let spans = std::mem::take(&mut pending.spans);
    let metrics = std::mem::take(&mut pending.metrics);
    let logs = std::mem::take(&mut pending.logs);
    let events = std::mem::take(&mut pending.events);
    let store_clone = store.clone();
    match tokio::task::spawn_blocking(move || {
        store_clone.insert_batch(spans, metrics, logs, events)
    })
    .await
    {
        Ok(Ok((s, m, l, e))) => {
            tracing::debug!(
                spans = s,
                metrics = m,
                logs = l,
                events = e,
                "flushed ingest mega-batch"
            );
        }
        Ok(Err(error)) => {
            if crate::store::is_fatal_invalidation_error(&error) {
                store.mark_invalidated(&error.to_string());
                tracing::error!(
                    ?error,
                    "CRITICAL: ingest mega-batch flush hit fatally invalidated DuckDB; pausing flushes until restart"
                );
            } else {
                tracing::error!(?error, "flushing ingest mega-batch failed");
            }
        }
        Err(error) => {
            tracing::error!(?error, "ingest flush task panicked");
        }
    }
}

async fn run_flusher(
    store: Store,
    mut rx: mpsc::Receiver<IngestBatch>,
    mut shutdown_rx: watch::Receiver<bool>,
    config: IngestConfig,
) {
    let mut pending = PendingBatch::default();
    let mut flush_deadline: Option<Instant> = None;

    loop {
        if pending.is_empty() {
            tokio::select! {
                maybe_batch = rx.recv() => {
                    match maybe_batch {
                        Some(batch) => {
                            pending.push(batch);
                            drain_ready(&mut rx, &mut pending, &config);
                            if pending.should_flush(&config) {
                                flush_pending(&store, &mut pending).await;
                                flush_deadline = None;
                            } else {
                                flush_deadline = Some(Instant::now() + config.flush_interval);
                            }
                        }
                        None => break,
                    }
                }
                _ = shutdown_rx.changed() => {
                    if *shutdown_rx.borrow() {
                        break;
                    }
                }
            }
        } else {
            let deadline = flush_deadline.unwrap_or_else(|| Instant::now() + config.flush_interval);
            tokio::select! {
                maybe_batch = rx.recv() => {
                    match maybe_batch {
                        Some(batch) => {
                            pending.push(batch);
                            drain_ready(&mut rx, &mut pending, &config);
                            if pending.should_flush(&config) {
                                flush_pending(&store, &mut pending).await;
                                flush_deadline = None;
                            }
                        }
                        None => {
                            flush_pending(&store, &mut pending).await;
                            break;
                        }
                    }
                }
                _ = tokio::time::sleep_until(deadline) => {
                    flush_pending(&store, &mut pending).await;
                    flush_deadline = None;
                }
                _ = shutdown_rx.changed() => {
                    if *shutdown_rx.borrow() {
                        break;
                    }
                }
            }
        }
    }

    // Drain any remaining queued batches in bounded chunks before exiting.
    loop {
        if store.is_invalidated() {
            pending.clear();
            break;
        }
        drain_ready(&mut rx, &mut pending, &config);
        if pending.is_empty() {
            break;
        }
        flush_pending(&store, &mut pending).await;
    }
    tracing::info!("ingest flusher drained and stopped");
}

fn drain_ready(
    rx: &mut mpsc::Receiver<IngestBatch>,
    pending: &mut PendingBatch,
    config: &IngestConfig,
) {
    while !pending.should_flush(config) {
        match rx.try_recv() {
            Ok(batch) => pending.push(batch),
            Err(_) => break,
        }
    }
}

enum ExportError {
    BadRequest(String),
    Storage(anyhow::Error),
}

pub async fn traces(State(store): State<Store>, headers: HeaderMap, body: Bytes) -> Response {
    export_sync::<ExportTraceServiceRequest, ExportTraceServiceResponse>(
        headers,
        body,
        move |req| store.insert_spans(otlp::span_records(req, now_ms())),
    )
    .await
}

pub async fn metrics(State(store): State<Store>, headers: HeaderMap, body: Bytes) -> Response {
    export_sync::<ExportMetricsServiceRequest, ExportMetricsServiceResponse>(
        headers,
        body,
        move |req| store.insert_metric_points(otlp::metric_points(req, now_ms())),
    )
    .await
}

pub async fn logs(State(store): State<Store>, headers: HeaderMap, body: Bytes) -> Response {
    export_sync::<ExportLogsServiceRequest, ExportLogsServiceResponse>(headers, body, move |req| {
        store.insert_logs(otlp::log_records(req, now_ms()))
    })
    .await
}

pub async fn traces_buffered(
    State(queue): State<IngestQueue>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    export_buffered::<ExportTraceServiceRequest, ExportTraceServiceResponse>(
        queue,
        headers,
        body,
        |req| IngestBatch::Spans(otlp::span_records(req, now_ms())),
    )
    .await
}

pub async fn metrics_buffered(
    State(queue): State<IngestQueue>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    export_buffered::<ExportMetricsServiceRequest, ExportMetricsServiceResponse>(
        queue,
        headers,
        body,
        |req| IngestBatch::Metrics(otlp::metric_points(req, now_ms())),
    )
    .await
}

pub async fn logs_buffered(
    State(queue): State<IngestQueue>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    export_buffered::<ExportLogsServiceRequest, ExportLogsServiceResponse>(
        queue,
        headers,
        body,
        |req| IngestBatch::Logs(otlp::log_records(req, now_ms())),
    )
    .await
}

async fn export_sync<Req, Resp>(
    headers: HeaderMap,
    body: Bytes,
    write: impl FnOnce(Req) -> anyhow::Result<usize> + Send + 'static,
) -> Response
where
    Req: prost::Message + Default + DeserializeOwned + Send + 'static,
    Resp: prost::Message + Default + Serialize,
{
    let Some(format) = Format::from_headers(&headers, &["application/x-protobuf"]) else {
        return unsupported_media_type();
    };

    let result = tokio::task::spawn_blocking(move || {
        let request = codec::decompress(&headers, "content-encoding", body)
            .and_then(|decompressed| format.decode::<Req>(&decompressed))
            .map_err(ExportError::BadRequest)?;
        write(request).map_err(ExportError::Storage)
    })
    .await;

    match result {
        Ok(Ok(count)) => tracing::debug!(count, "stored export"),
        Ok(Err(ExportError::BadRequest(message))) => {
            return (StatusCode::BAD_REQUEST, message).into_response();
        }
        Ok(Err(ExportError::Storage(error))) => {
            tracing::error!(?error, "storing export failed");
            return (StatusCode::INTERNAL_SERVER_ERROR, "storage failed").into_response();
        }
        Err(error) => {
            tracing::error!(?error, "storage task panicked");
            return (StatusCode::INTERNAL_SERVER_ERROR, "storage failed").into_response();
        }
    }

    ok_response::<Resp>(format)
}

async fn export_buffered<Req, Resp>(
    queue: IngestQueue,
    headers: HeaderMap,
    body: Bytes,
    convert: impl FnOnce(Req) -> IngestBatch + Send + 'static,
) -> Response
where
    Req: prost::Message + Default + DeserializeOwned + Send + 'static,
    Resp: prost::Message + Default + Serialize,
{
    let Some(format) = Format::from_headers(&headers, &["application/x-protobuf"]) else {
        return unsupported_media_type();
    };

    if queue.is_invalidated() {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            [(header::RETRY_AFTER, HeaderValue::from_static("1"))],
            "storage invalidated",
        )
            .into_response();
    }

    // Reserve a queue slot before doing decompression/decoding so full queues
    // shed load immediately with zero extra allocation on 512 MB containers.
    let permit = match queue.try_reserve() {
        Ok(permit) => permit,
        Err(_) => {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                [(header::RETRY_AFTER, HeaderValue::from_static("1"))],
                "ingest queue full",
            )
                .into_response();
        }
    };

    let decoded = tokio::task::spawn_blocking(move || {
        let request = codec::decompress(&headers, "content-encoding", body)
            .and_then(|decompressed| format.decode::<Req>(&decompressed))?;
        Ok::<IngestBatch, String>(convert(request))
    })
    .await;

    match decoded {
        Ok(Ok(batch)) => {
            if !batch.is_empty() {
                permit.send(batch);
            }
        }
        Ok(Err(message)) => {
            return (StatusCode::BAD_REQUEST, message).into_response();
        }
        Err(error) => {
            tracing::error!(?error, "decode task panicked");
            return (StatusCode::INTERNAL_SERVER_ERROR, "decode failed").into_response();
        }
    }

    ok_response::<Resp>(format)
}

fn unsupported_media_type() -> Response {
    (
        StatusCode::UNSUPPORTED_MEDIA_TYPE,
        "content-type must be application/x-protobuf or application/json",
    )
        .into_response()
}

fn ok_response<Resp: prost::Message + Default + Serialize>(format: Format) -> Response {
    let content_type = match format {
        Format::Proto => "application/x-protobuf",
        Format::Json => "application/json",
    };
    (
        [(header::CONTENT_TYPE, HeaderValue::from_static(content_type))],
        format.encode(&Resp::default()),
    )
        .into_response()
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or_default()
}