servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Six native metric families with fixed series per registered client.
use super::ClientError;
use crate::metrics::Registry;
use prometheus::{
    Histogram, HistogramOpts, IntCounter, IntCounterVec, IntGauge, Opts,
    core::{Collector, Desc},
    proto::MetricFamily,
};
use std::collections::HashMap;

const OUTCOMES: [&str; 12] = [
    "ok",
    "http_error",
    "capacity_rejected",
    "capacity_timeout",
    "deadline",
    "connect_timeout",
    "read_timeout",
    "transport_error",
    "response_too_large",
    "closed",
    "cancelled",
    "invalid_request",
];
const STATUSES: [&str; 6] = ["1xx", "2xx", "3xx", "4xx", "5xx", "other"];
const BUCKETS: [f64; 6] = [0.001, 0.005, 0.025, 0.1, 0.5, 2.0];

#[derive(Clone, Copy)]
pub(super) enum Outcome {
    Ok,
    HttpError,
    Rejected,
    CapacityTimeout,
    Deadline,
    ConnectTimeout,
    ReadTimeout,
    Transport,
    ResponseTooLarge,
    Closed,
    Cancelled,
    InvalidRequest,
}
impl Outcome {
    pub(super) fn label(self) -> &'static str {
        OUTCOMES[self as usize]
    }
    pub(super) fn error(error: ClientError) -> Self {
        match error {
            ClientError::Capacity => Self::Rejected,
            ClientError::CapacityTimeout => Self::CapacityTimeout,
            ClientError::Deadline => Self::Deadline,
            ClientError::ConnectTimeout => Self::ConnectTimeout,
            ClientError::ReadTimeout => Self::ReadTimeout,
            ClientError::Transport => Self::Transport,
            ClientError::ResponseTooLarge => Self::ResponseTooLarge,
            ClientError::Closed => Self::Closed,
            ClientError::Configuration
            | ClientError::AmbientConfiguration
            | ClientError::Registration
            | ClientError::Destination
            | ClientError::RequestTooLarge => Self::InvalidRequest,
        }
    }
}
#[derive(Clone)]
pub(super) struct Measurements {
    pub duration: Histogram,
    pub capacity_duration: Histogram,
    pub waiting: IntGauge,
    pub active: IntGauge,
    outcomes: IntCounterVec,
    statuses: IntCounterVec,
    outcome_handles: Vec<IntCounter>,
    status_handles: Vec<IntCounter>,
}
impl Measurements {
    pub(super) fn new(name: &str) -> Result<Self, ClientError> {
        let labels = HashMap::from([("client".into(), name.into())]);
        let histogram = |metric, help| {
            Histogram::with_opts(
                HistogramOpts::new(metric, help)
                    .const_labels(labels.clone())
                    .buckets(BUCKETS.to_vec()),
            )
            .map_err(|_| ClientError::Registration)
        };
        let gauge = |metric, help| {
            IntGauge::with_opts(Opts::new(metric, help).const_labels(labels.clone()))
                .map_err(|_| ClientError::Registration)
        };
        let outcomes = IntCounterVec::new(
            Opts::new(
                "servlet_client_requests_total",
                "Completed or dropped managed HTTP attempts",
            )
            .const_labels(labels.clone()),
            &["outcome"],
        )
        .map_err(|_| ClientError::Registration)?;
        let statuses = IntCounterVec::new(
            Opts::new(
                "servlet_client_responses_total",
                "Received response headers by fixed status class",
            )
            .const_labels(labels.clone()),
            &["status_class"],
        )
        .map_err(|_| ClientError::Registration)?;
        let outcome_handles = OUTCOMES
            .iter()
            .map(|value| {
                outcomes
                    .get_metric_with_label_values(&[value])
                    .map_err(|_| ClientError::Registration)
            })
            .collect::<Result<Vec<_>, _>>()?;
        let status_handles = STATUSES
            .iter()
            .map(|value| {
                statuses
                    .get_metric_with_label_values(&[value])
                    .map_err(|_| ClientError::Registration)
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self {
            duration: histogram(
                "servlet_client_request_duration_seconds",
                "Managed request elapsed time through body completion or drop",
            )?,
            capacity_duration: histogram(
                "servlet_client_capacity_duration_seconds",
                "Managed request admission elapsed time including rejection or cancellation",
            )?,
            waiting: gauge(
                "servlet_client_waiting_requests",
                "Requests currently attempting admission",
            )?,
            active: gauge(
                "servlet_client_active_requests",
                "Admitted requests retaining managed body ownership",
            )?,
            outcomes,
            statuses,
            outcome_handles,
            status_handles,
        })
    }
    pub(super) fn register(&self, registry: &Registry) -> Result<(), ClientError> {
        // 2 histograms * (6 finite buckets + Inf + sum + count), 12 outcomes,
        // 6 status classes, 2 gauges = 38 series and 6 definitions per client.
        registry
            .register_managed(Box::new(self.clone()), 6, 38)
            .map_err(|_| ClientError::Registration)
    }
    pub(super) fn finish(&self, outcome: Outcome) {
        self.outcome_handles[outcome as usize].inc();
    }
    pub(super) fn received(&self, status: u16) {
        let index = if (100..600).contains(&status) {
            usize::from(status / 100 - 1)
        } else {
            5
        };
        self.status_handles[index].inc();
    }
    fn collectors(&self) -> [&dyn Collector; 6] {
        [
            &self.duration,
            &self.capacity_duration,
            &self.waiting,
            &self.active,
            &self.outcomes,
            &self.statuses,
        ]
    }
}
impl Collector for Measurements {
    fn desc(&self) -> Vec<&Desc> {
        self.collectors()
            .into_iter()
            .flat_map(Collector::desc)
            .collect()
    }
    fn collect(&self) -> Vec<MetricFamily> {
        self.collectors()
            .into_iter()
            .flat_map(Collector::collect)
            .collect()
    }
}