webserver-base 0.4.6

A Rust library which contains shared logic for all of my webserver projects.
Documentation
//! Metrics for calls the app makes to other services.

use std::time::{Duration, Instant};

use super::telemetry::byte_sample;

/// Records one outbound HTTP call:
/// `http_client_request_duration_seconds`,
/// `http_client_request_body_size_bytes` and
/// `http_client_response_body_size_bytes`, all labelled `target`, `route`,
/// `status`.
///
/// `target` (the service: `"accounts"`, `"apns"`) and `route` (the call's
/// template: `"/v1/users/{id}"`, never the filled-in URL) are `&'static str`
/// on purpose: each distinct value is a new series, so they must come from a
/// fixed set, never from ids, user input or IPs.
///
/// `status` is the HTTP status (`other` outside 100 to 599); `None` (no response: timeout, refused
/// connection) is labelled `error`. A size that is unknown (a streamed body)
/// is `None` and records nothing.
pub fn record_outbound(
    target: &'static str,
    route: &'static str,
    status: Option<u16>,
    elapsed: Duration,
    request_bytes: Option<u64>,
    response_bytes: Option<u64>,
) {
    let status: String = status_label(status);
    metrics::histogram!(
        "http_client_request_duration_seconds",
        "target" => target, "route" => route, "status" => status.clone()
    )
    .record(elapsed.as_secs_f64());
    if let Some(bytes) = request_bytes {
        metrics::histogram!(
            "http_client_request_body_size_bytes",
            "target" => target, "route" => route, "status" => status.clone()
        )
        .record(byte_sample(bytes));
    }
    if let Some(bytes) = response_bytes {
        metrics::histogram!(
            "http_client_response_body_size_bytes",
            "target" => target, "route" => route, "status" => status
        )
        .record(byte_sample(bytes));
    }
}

/// A timer around one outbound call; see [`record_outbound`] for the labels.
///
/// ```
/// use webserver_base::webserver::OutboundCall;
///
/// let call: OutboundCall = OutboundCall::start("accounts", "/v1/users/{id}").request_bytes(120);
/// // ... send the request ...
/// call.finish(Some(200), Some(2048));
/// ```
///
/// Dropping it without `finish` (a timeout or refused connection that exits
/// early through `?`) records the duration so far as `status="error"`, with no
/// sizes.
#[derive(Debug)]
#[must_use = "call finish() when the response (or the failure) arrives"]
pub struct OutboundCall {
    target: &'static str,
    route: &'static str,
    started: Instant,
    request_bytes: Option<u64>,
    finished: bool,
}

impl OutboundCall {
    /// Starts the clock.
    pub fn start(target: &'static str, route: &'static str) -> Self {
        Self {
            target,
            route,
            started: Instant::now(),
            request_bytes: None,
            finished: false,
        }
    }

    /// The request body's size, when known.
    pub const fn request_bytes(mut self, bytes: u64) -> Self {
        self.request_bytes = Some(bytes);
        self
    }

    /// Records the call: its status (`None` when no response came) and the
    /// response body's size, when known.
    pub fn finish(mut self, status: Option<u16>, response_bytes: Option<u64>) {
        self.finished = true;
        record_outbound(
            self.target,
            self.route,
            status,
            self.started.elapsed(),
            self.request_bytes,
            response_bytes,
        );
    }
}

impl Drop for OutboundCall {
    fn drop(&mut self) {
        if !self.finished {
            record_outbound(
                self.target,
                self.route,
                None,
                self.started.elapsed(),
                None,
                None,
            );
        }
    }
}

/// A status outside 100 to 599 cannot come from a well-formed response.
fn status_label(status: Option<u16>) -> String {
    match status {
        Some(code @ 100..=599) => code.to_string(),
        Some(_) => String::from("other"),
        None => String::from("error"),
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{OutboundCall, record_outbound, status_label};
    use crate::webserver::telemetry::handle;

    #[test]
    fn a_status_outside_the_http_range_cannot_grow_the_series_count() {
        assert_eq!("204", status_label(Some(204)));
        assert_eq!("other", status_label(Some(999)));
        assert_eq!("other", status_label(Some(0)));
        assert_eq!("error", status_label(None));
    }

    #[test]
    fn an_outbound_call_records_duration_and_both_sizes_under_its_labels() {
        let _ = handle();
        record_outbound(
            "unit_target",
            "/v1/things/{id}",
            Some(200),
            Duration::from_millis(30),
            Some(300),
            Some(5000),
        );

        let rendered: String = handle().render();
        let labels: &str = r#"target="unit_target",route="/v1/things/{id}",status="200""#;
        for series in [
            "http_client_request_duration_seconds_count",
            "http_client_request_body_size_bytes_count",
            "http_client_response_body_size_bytes_count",
        ] {
            let line: String = format!("{series}{{{labels}}} 1");
            assert!(rendered.contains(&line), "{line} missing: {rendered}");
        }
        let sum: String = format!("http_client_request_body_size_bytes_sum{{{labels}}} 300");
        assert!(rendered.contains(&sum), "{rendered}");
        let bucket: String =
            format!("http_client_response_body_size_bytes_bucket{{{labels},le=\"16384\"}} 1");
        assert!(rendered.contains(&bucket), "{rendered}");
    }

    #[test]
    fn a_failed_call_without_sizes_records_only_the_duration_as_error() {
        let _ = handle();
        OutboundCall::start("unit_down", "/ping").finish(None, None);

        let rendered: String = handle().render();
        assert!(
            rendered.contains(
                r#"http_client_request_duration_seconds_count{target="unit_down",route="/ping",status="error"} 1"#
            ),
            "{rendered}"
        );
        assert!(
            !rendered.contains(r#"body_size_bytes_count{target="unit_down""#),
            "unknown sizes record nothing"
        );
    }

    #[test]
    fn a_call_dropped_without_finish_records_one_error() {
        let _ = handle();
        {
            let _call: OutboundCall =
                OutboundCall::start("unit_dropped", "/early").request_bytes(10);
        }
        OutboundCall::start("unit_finished", "/once").finish(Some(200), None);

        let rendered: String = handle().render();
        assert!(
            rendered.contains(
                r#"http_client_request_duration_seconds_count{target="unit_dropped",route="/early",status="error"} 1"#
            ),
            "{rendered}"
        );
        assert!(
            !rendered.contains(r#"body_size_bytes_count{target="unit_dropped""#),
            "a dropped call records no sizes"
        );
        assert!(
            rendered.contains(
                r#"http_client_request_duration_seconds_count{target="unit_finished",route="/once",status="200"} 1"#
            ),
            "{rendered}"
        );
        assert!(
            !rendered.contains(r#"target="unit_finished",route="/once",status="error""#),
            "finish must not also record on drop"
        );
    }
}