servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Scrapes observe local SQLx pool state without executing SQL or spawning a task.
use super::{PgError, PgPool};
use crate::metrics::Registry;
use prometheus::{
    IntGauge, Opts,
    core::{Collector, Desc},
    proto::MetricFamily,
};
use std::collections::HashMap;

struct PoolMetrics {
    pool: PgPool,
    size: IntGauge,
    idle: IntGauge,
    in_use: IntGauge,
}

pub(super) fn register(registry: &Registry, name: String, pool: PgPool) -> Result<(), PgError> {
    let gauge = |metric, help| {
        IntGauge::with_opts(
            Opts::new(metric, help).const_labels(HashMap::from([("pool".into(), name.clone())])),
        )
        .map_err(|_| PgError::Registration)
    };
    let metrics = PoolMetrics {
        pool,
        size: gauge("servlet_sql_pool_connections", "Current SQLx pool size")?,
        idle: gauge(
            "servlet_sql_pool_idle_connections",
            "Currently idle SQLx connections",
        )?,
        in_use: gauge(
            "servlet_sql_pool_in_use_connections",
            "Pool size minus idle; includes acquisition and connection work",
        )?,
    };
    registry
        .register_managed(Box::new(metrics), 3, 3)
        .map_err(|_| PgError::Registration)
}

impl Collector for PoolMetrics {
    fn desc(&self) -> Vec<&Desc> {
        [&self.size, &self.idle, &self.in_use]
            .into_iter()
            .flat_map(Collector::desc)
            .collect()
    }
    fn collect(&self) -> Vec<MetricFamily> {
        let size = self.pool.size();
        // SQLx exposes separate observations. Clamp a concurrent close/acquire
        // race so the derived gauge never underflows; this is not an atomic census.
        let idle = self.pool.num_idle().min(size as usize) as u32;
        self.size.set(i64::from(size));
        self.idle.set(i64::from(idle));
        self.in_use.set(i64::from(size - idle));
        [&self.size, &self.idle, &self.in_use]
            .into_iter()
            .flat_map(Collector::collect)
            .collect()
    }
}