servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Bounded nonblocking completion queue with an independent, deadline-aware export worker.
use super::{config::TraceLimits, stats::Counters, worker};
use crate::{Error, Result};
use opentelemetry::{Context, trace::SpanContext};
use opentelemetry_sdk::{
    error::{OTelSdkError, OTelSdkResult},
    trace::{Span, SpanData, SpanExporter, SpanProcessor},
};
use std::{
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
        mpsc,
    },
    time::Duration,
};
use tokio::{
    sync::{mpsc as channel, watch},
    time::Instant,
};

#[derive(Debug)]
pub(super) enum Item {
    Span(Box<SpanData>),
    Flush(mpsc::SyncSender<bool>),
}
#[derive(Debug)]
pub(super) struct Processor {
    sender: channel::Sender<Item>,
    stop: watch::Sender<Option<Instant>>,
    closed: AtomicBool,
    done: Mutex<mpsc::Receiver<()>>,
    counters: Arc<Counters>,
    timeout: Duration,
}
impl Processor {
    pub(super) fn new<E: SpanExporter + 'static>(
        exporter: E,
        limits: Arc<TraceLimits>,
        counters: Arc<Counters>,
    ) -> Result<Self> {
        let (sender, receiver) = channel::channel(limits.queue);
        let (stop, stopping) = watch::channel(None);
        let (finished, done) = mpsc::sync_channel(1);
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|_| Error::Telemetry("trace executor initialization failed"))?;
        let stats = counters.clone();
        let timeout = limits.export_timeout;
        std::thread::Builder::new()
            .name("servlet-traces".into())
            .spawn(move || {
                runtime.block_on(worker::run(exporter, receiver, stopping, limits, stats));
                runtime.shutdown_timeout(Duration::ZERO);
                let _ = finished.send(());
            })
            .map_err(|_| Error::Telemetry("trace worker initialization failed"))?;
        Ok(Self {
            sender,
            stop,
            closed: AtomicBool::new(false),
            done: Mutex::new(done),
            counters,
            timeout,
        })
    }
}
impl SpanProcessor for Processor {
    fn on_start(&self, _span: &mut Span, _context: &Context) {}
    fn on_end(&self, span: SpanData) {
        let context: &SpanContext = &span.span_context;
        if !context.is_sampled() {
            return;
        }
        if self.closed.load(Ordering::Acquire) {
            self.counters.dropped.fetch_add(1, Ordering::Relaxed);
            return;
        }
        self.counters.queued.fetch_add(1, Ordering::Relaxed);
        if self.sender.try_send(Item::Span(Box::new(span))).is_err() {
            self.counters.queued.fetch_sub(1, Ordering::Relaxed);
            self.counters.dropped.fetch_add(1, Ordering::Relaxed);
        }
    }
    fn force_flush(&self) -> OTelSdkResult {
        if self.closed.load(Ordering::Acquire) {
            return Err(OTelSdkError::AlreadyShutdown);
        }
        let (send, done) = mpsc::sync_channel(1);
        self.sender
            .try_send(Item::Flush(send))
            .map_err(|_| OTelSdkError::InternalFailure("trace flush queue unavailable".into()))?;
        match done.recv_timeout(self.timeout) {
            Ok(true) => Ok(()),
            Ok(false) => Err(OTelSdkError::InternalFailure("trace batch failed".into())),
            Err(_) => Err(OTelSdkError::Timeout(self.timeout)),
        }
    }
    fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {
        if self.closed.swap(true, Ordering::AcqRel) {
            return Err(OTelSdkError::AlreadyShutdown);
        }
        self.stop.send_replace(Some(Instant::now() + timeout));
        self.done
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .recv_timeout(timeout)
            .map_err(|_| OTelSdkError::Timeout(timeout))
    }
}

impl Drop for Processor {
    fn drop(&mut self) {
        if !self.closed.swap(true, Ordering::AcqRel) {
            self.stop.send_replace(Some(Instant::now()));
        }
    }
}

#[cfg(test)]
#[path = "processor_test.rs"]
mod processor_test;