servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! One native registry and one bounded registration ledger per application.
use super::{Family, Labels, MetricError};
use prometheus::{
    Encoder,
    core::{Collector, MetricVec, MetricVecBuilder},
};
use std::{
    collections::BTreeSet,
    io::{self, Write},
    sync::{Arc, Mutex},
};

struct State {
    native: prometheus::Registry,
    names: BTreeSet<String>,
    definitions: usize,
    series: usize,
    attached: bool,
    sealed: bool,
}

/// A non-global Prometheus registry with at most 128 definitions and 4096 series.
///
/// Families have at most 64 approved label combinations. Histograms count each
/// bucket, sum and count toward the series allowance. A registry may attach to only
/// one application, including through clones. Once setup ends, registration seals.
#[derive(Clone)]
pub struct Registry(Arc<Mutex<State>>);
impl Default for Registry {
    fn default() -> Self {
        Self::new()
    }
}
impl std::fmt::Debug for Registry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let state = self.0.lock().unwrap_or_else(|error| error.into_inner());
        f.debug_struct("Registry")
            .field("definitions", &state.definitions)
            .field("series", &state.series)
            .field("sealed", &state.sealed)
            .finish()
    }
}
impl Registry {
    /// Construct an empty registry without registering process-global state.
    pub fn new() -> Self {
        Self(Arc::new(Mutex::new(State {
            native: prometheus::Registry::new(),
            names: BTreeSet::new(),
            definitions: 0,
            series: 0,
            attached: false,
            sealed: false,
        })))
    }
    pub(crate) fn owned() -> Self {
        let registry = Self::new();
        registry.attach().expect("fresh registry is unowned");
        registry
    }
    pub(crate) fn attach(&self) -> Result<(), MetricError> {
        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
        if state.attached {
            return Err(MetricError::AlreadyAttached);
        }
        state.attached = true;
        Ok(())
    }
    pub(crate) fn seal(&self) {
        self.0
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .sealed = true;
    }
    /// Render Prometheus text through the native encoder, bounded to 4 MiB.
    /// Counts are observational snapshots; instruments are not updated atomically together.
    pub fn encode(&self) -> Result<String, MetricError> {
        let native = self
            .0
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .native
            .clone();
        let mut output = Bounded(Vec::new());
        prometheus::TextEncoder::new()
            .encode(&native.gather(), &mut output)
            .map_err(|_| MetricError::Encoding)?;
        String::from_utf8(output.0).map_err(|_| MetricError::Encoding)
    }
    // Only trusted managed integrations call this; application definitions cannot
    // claim servlet_ names or supply arbitrary collectors. Budgets are shared.
    #[cfg(any(feature = "postgres", feature = "client"))]
    pub(crate) fn register_managed(
        &self,
        collector: Box<dyn Collector>,
        definitions: usize,
        series: usize,
    ) -> Result<(), MetricError> {
        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
        if state.sealed {
            return Err(MetricError::Sealed);
        }
        if state.definitions + definitions > 128 || state.series + series > 4096 {
            return Err(MetricError::Capacity);
        }
        state
            .native
            .register(collector)
            .map_err(|_| MetricError::NameConflict)?;
        state.definitions += definitions;
        state.series += series;
        Ok(())
    }

    pub(super) fn install<B: MetricVecBuilder>(
        &self,
        name: &str,
        help: &str,
        labels: &[Labels],
        histogram: Option<usize>,
        build: impl FnOnce(&[&str]) -> prometheus::Result<MetricVec<B>>,
    ) -> Result<Family<B::M>, MetricError>
    where
        MetricVec<B>: 'static,
    {
        super::validation::definition(name, help, labels)?;
        let names = if histogram.is_some() {
            vec![
                name.to_owned(),
                format!("{name}_bucket"),
                format!("{name}_sum"),
                format!("{name}_count"),
            ]
        } else {
            vec![name.to_owned()]
        };
        let series = labels.len() * histogram.map_or(1, |buckets| buckets + 3);
        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
        if state.sealed {
            return Err(MetricError::Sealed);
        }
        if state.definitions >= 128 || state.series + series > 4096 {
            return Err(MetricError::Capacity);
        }
        if names.iter().any(|name| state.names.contains(name)) {
            return Err(MetricError::NameConflict);
        }
        let label_names: Vec<&str> = labels[0].0.iter().map(|(name, _)| name.as_str()).collect();
        let collector = build(&label_names).map_err(|_| MetricError::InvalidDefinition)?;
        let metrics = labels
            .iter()
            .map(|labels| {
                collector
                    .get_metric_with_label_values(&labels.values())
                    .map_err(|_| MetricError::InvalidDefinition)
            })
            .collect::<Result<Vec<_>, _>>()?;
        // Native vectors key children by hashes. Reject any collapsed label sets
        // instead of returning aliased handles for distinct approved combinations.
        let children: usize = collector
            .collect()
            .iter()
            .map(|family| family.get_metric().len())
            .sum();
        if children != labels.len() {
            return Err(MetricError::InvalidDefinition);
        }
        state
            .native
            .register(Box::new(collector))
            .map_err(|_| MetricError::NameConflict)?;
        state.names.extend(names);
        state.definitions += 1;
        state.series += series;
        Ok(Family {
            members: labels.iter().cloned().zip(metrics).collect(),
        })
    }
}

struct Bounded(Vec<u8>);
impl Write for Bounded {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if self.0.len() + bytes.len() > 4 * 1024 * 1024 {
            return Err(io::Error::other("metric output limit exceeded"));
        }
        self.0.extend_from_slice(bytes);
        Ok(bytes.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

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