servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Export serially, interrupt current I/O at the shared shutdown deadline, and count losses.
use super::{config::TraceLimits, processor::Item, stats::Counters};
use opentelemetry_sdk::trace::{SpanData, SpanExporter};
use std::sync::{Arc, atomic::Ordering};
use tokio::{
    sync::{mpsc, watch},
    time::{Instant, timeout_at},
};

pub(super) async fn run<E: SpanExporter>(
    exporter: E,
    mut queue: mpsc::Receiver<Item>,
    mut stop: watch::Receiver<Option<Instant>>,
    limits: Arc<TraceLimits>,
    counts: Arc<Counters>,
) {
    let mut batch = Vec::with_capacity(limits.batch);
    let mut tick = Instant::now() + limits.interval;
    loop {
        let deadline = *stop.borrow_and_update();
        if deadline.is_some() {
            queue.close();
        }
        if deadline.is_some_and(|d| Instant::now() >= d) {
            break;
        }
        let item = tokio::select! {
            biased;
            _ = stop.changed(), if deadline.is_none() => { continue; },
            item = queue.recv() => item,
            _ = tokio::time::sleep_until(deadline.map_or(tick, |d| tick.min(d))) => {
                export(&exporter, &mut batch, &mut stop, &limits, &counts).await;
                tick = Instant::now() + limits.interval; continue;
            },
        };
        match item {
            Some(Item::Span(span)) => {
                counts.queued.fetch_sub(1, Ordering::Relaxed);
                batch.push(*span);
                if batch.len() >= limits.batch {
                    export(&exporter, &mut batch, &mut stop, &limits, &counts).await;
                    tick = Instant::now() + limits.interval;
                }
            }
            Some(Item::Flush(done)) => {
                let success = export(&exporter, &mut batch, &mut stop, &limits, &counts).await;
                let _ = done.send(success);
                tick = Instant::now() + limits.interval;
            }
            None => {
                export(&exporter, &mut batch, &mut stop, &limits, &counts).await;
                break;
            }
        }
    }
    counts
        .shutdown
        .fetch_add(batch.len() as u64, Ordering::Relaxed);
    queue.close();
    while let Some(item) = queue.recv().await {
        if let Item::Span(_) = item {
            counts.queued.fetch_sub(1, Ordering::Relaxed);
            counts.shutdown.fetch_add(1, Ordering::Relaxed);
        }
    }
    let _ = exporter.shutdown_with_timeout(std::time::Duration::ZERO);
}
async fn export<E: SpanExporter>(
    exporter: &E,
    batch: &mut Vec<SpanData>,
    stop: &mut watch::Receiver<Option<Instant>>,
    limits: &TraceLimits,
    counts: &Counters,
) -> bool {
    if batch.is_empty() {
        return true;
    }
    let count = batch.len() as u64;
    let attempt = Instant::now() + limits.export_timeout;
    let shutdown = *stop.borrow_and_update();
    if shutdown.is_some_and(|d| Instant::now() >= d) {
        counts.shutdown.fetch_add(count, Ordering::Relaxed);
        batch.clear();
        return false;
    }
    let mut export = Box::pin(exporter.export(std::mem::take(batch)));
    let deadline = shutdown.map_or(attempt, |d| d.min(attempt));
    let result = tokio::select! {
        result = timeout_at(deadline, &mut export) => result,
        _ = stop.changed(), if shutdown.is_none() => {
            let deadline = stop.borrow_and_update().map_or(attempt, |d| d.min(attempt));
            timeout_at(deadline, &mut export).await
        }
    };
    let success = matches!(result, Ok(Ok(())));
    if success {
        counts.exported.fetch_add(count, Ordering::Relaxed);
    } else {
        counts.failed.fetch_add(1, Ordering::Relaxed);
        counts.lost.fetch_add(count, Ordering::Relaxed);
    }
    success
}