calmlens 0.42.0

Rust SDK for CalmLens moderation, storage and CDN delivery
Documentation
//! The API's `Server-Timing` response header.
use std::{collections::BTreeMap, time::Duration};

/// The time the API reports spending on a request, from its `Server-Timing` response header.
/// Subtracting [`total`](Self::total) from an attempt's duration leaves the time spent outside
/// CalmLens: the network, TLS, sending the request body and the caller's own machine.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ServerTiming {
    /// How long the API took to handle the request, from receiving it to responding.
    pub total: Duration,
    /// The named parts of `total` the API reports, such as `db`, `moderation` or `upload-body`
    /// (receiving an upload's body). They can overlap, so they need not add up to `total`.
    pub phases: BTreeMap<String, Duration>,
    /// Whether the request was the first one an API instance handled, which includes starting it.
    pub cold: bool,
}

impl ServerTiming {
    /// Parses a `Server-Timing` header value: `total` becomes [`total`](Self::total), every
    /// other metric with a valid `dur` (a plain decimal number of milliseconds) a phase, and a
    /// `cold` metric sets [`cold`](Self::cold). The first metric of each name and the first
    /// `dur` of each metric count. Returns `None` for an empty header or one without a valid
    /// `total`; it never panics.
    pub fn parse(header: &str) -> Option<Self> {
        let mut timing = Self::default();
        let mut seen = std::collections::BTreeSet::new();
        let mut has_total = false;
        for metric in split_quoted(header, b',') {
            let params = split_quoted(metric, b';');
            let name = trim_blanks(params[0]);
            if name.is_empty() || !seen.insert(name) {
                continue;
            }
            if name == "cold" {
                timing.cold = true;
                continue;
            }
            match (name, metric_duration(&params[1..])) {
                (_, None) => {}
                ("total", Some(duration)) => {
                    timing.total = duration;
                    has_total = true;
                }
                (name, Some(duration)) => {
                    timing.phases.insert(name.to_owned(), duration);
                }
            }
        }
        has_total.then_some(timing)
    }

    /// The largest `limit` phases, largest first.
    #[cfg_attr(not(feature = "async"), allow(dead_code))]
    pub(crate) fn largest_phases(&self, limit: usize) -> Vec<(&str, Duration)> {
        let mut phases: Vec<_> = self
            .phases
            .iter()
            .map(|(name, duration)| (name.as_str(), *duration))
            .collect();
        phases.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
        phases.truncate(limit);
        phases
    }
}

/// The part of `duration` spent outside the API, never negative, or `None` without a timing.
#[cfg_attr(not(feature = "async"), allow(dead_code))]
pub(crate) fn client_overhead(
    duration: Duration,
    timing: Option<&ServerTiming>,
) -> Option<Duration> {
    timing.map(|timing| duration.saturating_sub(timing.total))
}

/// `text` split at `separator` outside double-quoted strings, in which a backslash escapes the
/// next character.
fn split_quoted(text: &str, separator: u8) -> Vec<&str> {
    let mut parts = Vec::new();
    let (mut start, mut quoted, mut escaped) = (0, false, false);
    for (index, &byte) in text.as_bytes().iter().enumerate() {
        if escaped {
            escaped = false;
        } else if quoted && byte == b'\\' {
            escaped = true;
        } else if byte == b'"' {
            quoted = !quoted;
        } else if !quoted && byte == separator {
            parts.push(&text[start..index]);
            start = index + 1;
        }
    }
    parts.push(&text[start..]);
    parts
}

/// `text` without leading or trailing spaces and tabs.
fn trim_blanks(text: &str) -> &str {
    text.trim_matches([' ', '\t'])
}

/// The duration of a metric's first `dur` parameter, or `None` when it has none or it isn't a
/// plain decimal number of milliseconds.
fn metric_duration(params: &[&str]) -> Option<Duration> {
    let param = params.iter().find(|param| {
        let key = param.split_once('=').map_or(**param, |(key, _)| key);
        trim_blanks(key).eq_ignore_ascii_case("dur")
    })?;
    let value = trim_blanks(param.split_once('=').map_or("", |(_, value)| value));
    if !is_decimal(value) {
        return None;
    }
    Duration::try_from_secs_f64(value.parse::<f64>().ok()? / 1000.0).ok()
}

/// Whether `value` matches `^[0-9]+(\.[0-9]+)?$`.
fn is_decimal(value: &str) -> bool {
    let (whole, fraction) = match value.split_once('.') {
        Some((whole, fraction)) => (whole, Some(fraction)),
        None => (value, None),
    };
    !whole.is_empty()
        && fraction.is_none_or(|fraction| !fraction.is_empty())
        && whole
            .bytes()
            .chain(fraction.unwrap_or("").bytes())
            .all(|byte| byte.is_ascii_digit())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Replays the `overhead` cases of `testdata/server-timing.json`.
    #[test]
    fn client_overhead_follows_the_shared_fixture() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/testdata/server-timing.json");
        let fixture: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
        let millis = |value: &serde_json::Value| {
            value
                .as_f64()
                .map(|ms| Duration::from_secs_f64(ms / 1000.0))
        };
        for case in fixture["overhead"].as_array().unwrap() {
            let timing = ServerTiming::parse(case["header"].as_str().unwrap_or(""));
            let duration = millis(&case["durationMs"]).unwrap();
            assert_eq!(
                client_overhead(duration, timing.as_ref()),
                millis(&case["clientOverheadMs"]),
                "{case}"
            );
        }
    }
}