footing 0.1.5

Feature-gated foundations for Rust backend services
Documentation
use std::{
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::Body,
    extract::MatchedPath,
    http::{Request, header::CONTENT_TYPE},
    response::{IntoResponse, Response},
};
use tower::{Layer, Service};

use crate::{
    clock::{SharedClock, system_clock},
    observability::{
        MetricLabels, MetricRecorder, MetricRegistry, MetricsExporter, MetricsSnapshot,
        OpenMetricsExporter, metric_labels, metric_names,
    },
};

/// OpenMetrics content type.
pub const OPENMETRICS_CONTENT_TYPE: &str = OpenMetricsExporter::CONTENT_TYPE;
/// HTTP metrics unmatched route.
pub const HTTP_METRICS_UNMATCHED_ROUTE: &str = "unmatched";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
/// Enumerates the supported HTTP metric route label values.
pub enum HttpMetricRouteLabel {
    #[default]
    /// Indicates matched path.
    MatchedPath,
    /// Indicates raw path.
    RawPath,
}

impl HttpMetricRouteLabel {
    #[must_use]
    /// Returns the label for.
    pub fn label_for<B>(self, request: &Request<B>) -> &str {
        match self {
            Self::MatchedPath => request
                .extensions()
                .get::<MatchedPath>()
                .map(MatchedPath::as_str)
                .unwrap_or(HTTP_METRICS_UNMATCHED_ROUTE),
            Self::RawPath => request.uri().path(),
        }
    }
}

#[derive(Clone)]
/// Tower layer that applies HTTP metrics.
pub struct HttpMetricsLayer {
    recorder: Arc<dyn MetricRecorder>,
    clock: SharedClock,
    route_label: HttpMetricRouteLabel,
}

impl HttpMetricsLayer {
    #[must_use]
    /// Creates a new instance.
    pub fn new(recorder: Arc<dyn MetricRecorder>) -> Self {
        Self {
            recorder,
            clock: system_clock(),
            route_label: HttpMetricRouteLabel::default(),
        }
    }

    #[must_use]
    /// Creates in memory.
    pub fn in_memory() -> (Self, Arc<MetricRegistry>) {
        let registry = Arc::new(MetricRegistry::new());
        (Self::new(registry.clone()), registry)
    }

    #[must_use]
    /// Configures clock and returns the updated value.
    pub fn with_clock(mut self, clock: SharedClock) -> Self {
        self.clock = clock;
        self
    }

    #[must_use]
    /// Configures route label and returns the updated value.
    pub const fn with_route_label(mut self, route_label: HttpMetricRouteLabel) -> Self {
        self.route_label = route_label;
        self
    }

    #[must_use]
    /// Configures raw path route labels and returns the updated value.
    pub const fn with_raw_path_route_labels(self) -> Self {
        self.with_route_label(HttpMetricRouteLabel::RawPath)
    }

    #[must_use]
    /// Returns the recorder.
    pub fn recorder(&self) -> &Arc<dyn MetricRecorder> {
        &self.recorder
    }

    #[must_use]
    /// Returns the clock.
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }

    #[must_use]
    /// Returns the route label.
    pub const fn route_label(&self) -> HttpMetricRouteLabel {
        self.route_label
    }
}

impl fmt::Debug for HttpMetricsLayer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HttpMetricsLayer")
            .finish_non_exhaustive()
    }
}

impl<S> Layer<S> for HttpMetricsLayer {
    type Service = HttpMetricsService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        HttpMetricsService {
            inner,
            recorder: self.recorder.clone(),
            clock: self.clock.clone(),
            route_label: self.route_label,
        }
    }
}

#[derive(Clone)]
/// Service for HTTP metrics.
pub struct HttpMetricsService<S> {
    inner: S,
    recorder: Arc<dyn MetricRecorder>,
    clock: SharedClock,
    route_label: HttpMetricRouteLabel,
}

impl<S> fmt::Debug for HttpMetricsService<S>
where
    S: fmt::Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HttpMetricsService")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<S> Service<Request<Body>> for HttpMetricsService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(context)
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let start = self.clock.now();
        let recorder = self.recorder.clone();
        let clock = self.clock.clone();
        let method = request.method().as_str().to_owned();
        let route = self.route_label.label_for(&request).to_owned();
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);

        Box::pin(async move {
            let result = inner.call(request).await;
            match &result {
                Ok(response) => {
                    record_http_metrics(
                        recorder.as_ref(),
                        &method,
                        &route,
                        response.status().as_u16(),
                        clock.now().saturating_duration_since(start),
                    );
                }
                Err(_) => {
                    let _ = recorder.increment_counter(
                        metric_names::HTTP_SERVER_ERRORS_TOTAL,
                        1,
                        MetricLabels::from_lossy([
                            (metric_labels::METHOD, method.as_str()),
                            (metric_labels::ROUTE, route.as_str()),
                            (metric_labels::ERROR, "service"),
                        ]),
                    );
                }
            }
            result
        })
    }
}

/// A response containing metrics.
pub struct MetricsResponse(pub MetricsSnapshot);

impl IntoResponse for MetricsResponse {
    fn into_response(self) -> Response {
        let export = match OpenMetricsExporter.export(&self.0) {
            Ok(export) => export,
            Err(never) => match never {},
        };
        let mut response = export.into_body().into_response();
        response.headers_mut().insert(
            CONTENT_TYPE,
            axum::http::HeaderValue::from_static(OPENMETRICS_CONTENT_TYPE),
        );
        response
    }
}

/// Records HTTP metrics.
pub fn record_http_metrics(
    recorder: &dyn MetricRecorder,
    method: &str,
    route: &str,
    status: u16,
    elapsed: Duration,
) {
    let status = status.to_string();
    let labels = MetricLabels::from_lossy([
        (metric_labels::METHOD, method),
        (metric_labels::ROUTE, route),
        (metric_labels::STATUS, status.as_str()),
    ]);
    let _ = recorder.increment_counter(metric_names::HTTP_SERVER_REQUESTS_TOTAL, 1, labels.clone());
    let _ = recorder.observe_histogram(
        metric_names::HTTP_SERVER_REQUEST_DURATION_SECONDS,
        elapsed.as_secs_f64(),
        labels,
    );
}

#[cfg(test)]
mod tests {
    use axum::{Router, body::to_bytes, http::StatusCode, routing::get};
    use tower::ServiceExt;

    use super::*;

    #[tokio::test]
    async fn metrics_layer_records_requests() {
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let response = Router::new()
            .route("/health", get(|| async { "ok" }))
            .layer(layer)
            .oneshot(
                Request::get("/health")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");

        assert_eq!(response.status(), StatusCode::OK);
        let snapshot = registry.snapshot().expect("snapshot should build");
        let sample = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .expect("request counter should be recorded");
        assert_eq!(
            sample
                .labels()
                .iter()
                .find(|(name, _)| name == metric_labels::ROUTE)
                .map(|(_, value)| value.as_str()),
            Some("/health")
        );
    }

    #[tokio::test]
    async fn metrics_layer_allows_explicit_raw_path_route_labels() {
        let (layer, registry) = HttpMetricsLayer::in_memory();
        let response = Router::new()
            .route("/users/{id}", get(|| async { "ok" }))
            .layer(layer.with_raw_path_route_labels())
            .oneshot(
                Request::get("/users/123")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");

        assert_eq!(response.status(), StatusCode::OK);
        let snapshot = registry.snapshot().expect("snapshot should build");
        let sample = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == metric_names::HTTP_SERVER_REQUESTS_TOTAL)
            .expect("request counter should be recorded");
        assert_eq!(
            sample
                .labels()
                .iter()
                .find(|(name, _)| name == metric_labels::ROUTE)
                .map(|(_, value)| value.as_str()),
            Some("/users/123")
        );
    }

    #[test]
    fn route_label_strategy_never_uses_raw_path_by_default() {
        let request = Request::get("/users/123")
            .body(Body::empty())
            .expect("request should build");

        assert_eq!(
            HttpMetricRouteLabel::MatchedPath.label_for(&request),
            HTTP_METRICS_UNMATCHED_ROUTE
        );
        assert_eq!(
            HttpMetricRouteLabel::RawPath.label_for(&request),
            "/users/123"
        );
    }

    #[tokio::test]
    async fn metrics_response_uses_openmetrics_content_type() {
        let response = MetricsResponse(MetricsSnapshot::new(vec![
            crate::observability::MetricSample::counter("jobs_total", 1)
                .expect("metric sample should build"),
        ]))
        .into_response();

        assert_eq!(
            response
                .headers()
                .get(CONTENT_TYPE)
                .and_then(|value| value.to_str().ok()),
            Some(OPENMETRICS_CONTENT_TYPE)
        );
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should read");
        assert!(String::from_utf8_lossy(&body).contains("jobs_total"));
    }
}