Skip to main content

schedr_api/
metrics.rs

1//! The webserver's metrics (see archive/PROJECT.md, Observability), registered in the process's
2//! registry and served on the ops port: requests by route template (never a raw path, which
3//! holds IDs) and status, and why the log proxy couldn't serve a log.
4
5use axum::extract::{MatchedPath, Request, State};
6use axum::middleware::Next;
7use axum::response::Response;
8use prometheus_client::encoding::EncodeLabelSet;
9use prometheus_client::metrics::counter::Counter;
10use prometheus_client::metrics::family::Family;
11use prometheus_client::registry::Registry;
12use schedr_model::metric_doc::{MetricDoc, MetricKind};
13
14use crate::state::ApiState;
15
16#[cfg(test)]
17mod tests;
18
19const HTTP_REQUESTS: MetricDoc = MetricDoc {
20    name: "http_requests",
21    kind: MetricKind::Counter,
22    labels: &["route", "status"],
23    help: "Requests to the REST API, by route template and status",
24};
25const LOG_PROXY_ERRORS: MetricDoc = MetricDoc {
26    name: "log_proxy_errors",
27    kind: MetricKind::Counter,
28    labels: &["kind"],
29    help: "Logs the webserver couldn't read from a worker, by why",
30};
31
32/// The webserver's metrics, as registered (under `schedr_`).
33pub const METRICS: &[MetricDoc] = &[HTTP_REQUESTS, LOG_PROXY_ERRORS];
34
35/// A request's route template and its answer's status.
36#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
37pub struct RequestLabels {
38    /// The route template, e.g. `/api/v1/runs/{run_id}`; `unmatched` for a path no route has.
39    pub route: String,
40    /// The HTTP status.
41    pub status: u16,
42}
43
44/// Why a log couldn't be served.
45#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
46pub struct LogErrorLabels {
47    /// `missing`, `stale_address`, `unreachable`, `worker_gone` or `no_endpoint`.
48    pub kind: String,
49}
50
51/// The webserver's metrics (cheap to clone; clones share them).
52#[derive(Debug, Clone, Default)]
53pub struct ApiMetrics {
54    /// Requests by route template and status.
55    pub requests: Family<RequestLabels, Counter>,
56    /// Logs the proxy couldn't serve, by why.
57    pub log_errors: Family<LogErrorLabels, Counter>,
58}
59
60impl ApiMetrics {
61    /// Registers every metric in `registry` (names get the `schedr_` prefix there), as
62    /// [`METRICS`] describes them.
63    pub fn register(&self, registry: &mut Registry) {
64        let r = registry;
65        r.register(
66            HTTP_REQUESTS.name,
67            HTTP_REQUESTS.help,
68            self.requests.clone(),
69        );
70        r.register(
71            LOG_PROXY_ERRORS.name,
72            LOG_PROXY_ERRORS.help,
73            self.log_errors.clone(),
74        );
75    }
76
77    /// Counts a log the proxy couldn't serve.
78    pub fn log_error(&self, kind: &str) {
79        self.log_errors
80            .get_or_create(&LogErrorLabels {
81                kind: kind.to_owned(),
82            })
83            .inc();
84    }
85}
86
87/// Middleware counting each request by its route template and status, those the version check
88/// refuses included.
89pub async fn count_requests(
90    State(state): State<ApiState>,
91    request: Request,
92    next: Next,
93) -> Response {
94    let route = request
95        .extensions()
96        .get::<MatchedPath>()
97        .map_or("unmatched", MatchedPath::as_str)
98        .to_owned();
99    let response = next.run(request).await;
100    state
101        .metrics
102        .requests
103        .get_or_create(&RequestLabels {
104            route,
105            status: response.status().as_u16(),
106        })
107        .inc();
108    response
109}