1use 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
32pub const METRICS: &[MetricDoc] = &[HTTP_REQUESTS, LOG_PROXY_ERRORS];
34
35#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
37pub struct RequestLabels {
38 pub route: String,
40 pub status: u16,
42}
43
44#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
46pub struct LogErrorLabels {
47 pub kind: String,
49}
50
51#[derive(Debug, Clone, Default)]
53pub struct ApiMetrics {
54 pub requests: Family<RequestLabels, Counter>,
56 pub log_errors: Family<LogErrorLabels, Counter>,
58}
59
60impl ApiMetrics {
61 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 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
87pub 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}