about summary refs log tree commit diff
path: root/src/metrics.rs
blob: 9f512ddb5f2cef8df4a844d51559114e9df98c22 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use async_trait::async_trait;
use lazy_static::lazy_static;
use prometheus::{
    self, register_histogram_vec, register_int_counter_vec, Encoder, HistogramVec, IntCounterVec,
    TextEncoder,
};
use std::time::{Duration, Instant};
use tide::{Next, Request, Response, Result};

// Copied from https://docs.rs/prometheus/0.12.0/src/prometheus/histogram.rs.html#885-889
#[inline]
fn duration_to_seconds(d: Duration) -> f64 {
    let nanos = f64::from(d.subsec_nanos()) / 1e9;
    d.as_secs() as f64 + nanos
}

lazy_static! {
    static ref HTTP_CONNS_COUNTER: IntCounterVec = register_int_counter_vec!(
        "http_requests_total",
        "Number of processed HTTP requests",
        &["code", "method", "url"]
    )
    .unwrap();
    static ref HTTP_REQUEST_DURATION_HISTOGRAM: HistogramVec = register_histogram_vec!(
        "http_request_duration_seconds",
        "Duration of HTTP requests",
        &["code", "method", "url"]
    )
    .unwrap();
}

pub struct InstrumentationMiddleware {}

#[async_trait]
impl<S> tide::Middleware<S> for InstrumentationMiddleware
where
    S: Send + Sync + Clone + 'static,
{
    async fn handle(&self, req: Request<S>, next: Next<'_, S>) -> Result {
        let url = req.url().to_string();
        let method = req.method().to_string();
        // Execute the request
        let instant = Instant::now();
        let res = next.run(req).await;
        let elapsed = duration_to_seconds(instant.elapsed());
        // Get the code from the response
        let code = res.status().to_string();

        HTTP_CONNS_COUNTER
            .with_label_values(&[&code, &method, &url])
            .inc();
        HTTP_REQUEST_DURATION_HISTOGRAM
            .with_label_values(&[&code, &method, &url])
            .observe(elapsed);

        Ok(res)
    }
}

pub async fn gather<S>(_: Request<S>) -> Result
where
    S: Send + Sync + Clone,
{
    let mut buffer: Vec<u8> = vec![];
    let encoder = TextEncoder::new();
    let metric_families = prometheus::gather();
    encoder.encode(&metric_families, &mut buffer).unwrap();

    Ok(Response::builder(200).body(buffer).build())
}