Skip to main content

oxtel_tower/
metrics_service.rs

1//! Prometheus `/metrics` as a tower service.
2
3use std::convert::Infallible;
4use std::future::{Ready, ready};
5use std::task::{Context, Poll};
6
7use http::{Request, Response, StatusCode, header};
8use oxtel_prometheus::PrometheusExporter;
9use tower_service::Service;
10
11/// Answers every request with a Prometheus scrape of the exporter's
12/// metrics, in the format the `Accept` header negotiates: OpenMetrics with
13/// exemplars for Prometheus, the classic text format otherwise. Mount it at
14/// `/metrics`: with axum, `Router::route_service("/metrics", ...)`; with
15/// hyper, through hyper-util's `TowerToHyperService`.
16#[derive(Clone)]
17pub struct MetricsService {
18    exporter: PrometheusExporter,
19}
20
21impl MetricsService {
22    /// A service rendering `exporter`.
23    pub fn new(exporter: PrometheusExporter) -> Self {
24        MetricsService { exporter }
25    }
26}
27
28impl<B> Service<Request<B>> for MetricsService {
29    type Response = Response<String>;
30    type Error = Infallible;
31    type Future = Ready<Result<Response<String>, Infallible>>;
32
33    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
34        Poll::Ready(Ok(()))
35    }
36
37    fn call(&mut self, req: Request<B>) -> Self::Future {
38        let accept = req
39            .headers()
40            .get(header::ACCEPT)
41            .and_then(|v| v.to_str().ok());
42        let (content_type, body) = self.exporter.render(accept);
43        let response = Response::builder()
44            .status(StatusCode::OK)
45            .header(header::CONTENT_TYPE, content_type)
46            .body(body)
47            .unwrap_or_else(|_| Response::new(String::new()));
48        ready(Ok(response))
49    }
50}