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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
//! Request metrics middleware with [OpenTelemetry].
//!
//! [OpenTelemetry]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md

use std::time::SystemTime;

use http::uri::Scheme;
use opentelemetry::{
    metrics::{Histogram, Meter, Unit, UpDownCounter},
    Context, KeyValue,
};
use opentelemetry_semantic_conventions::trace::{
    HTTP_CLIENT_IP,
    HTTP_FLAVOR,
    HTTP_HOST,
    HTTP_METHOD,
    // HTTP_RESPONSE_CONTENT_LENGTH,
    HTTP_ROUTE,
    HTTP_SCHEME, // , HTTP_SERVER_NAME
    HTTP_STATUS_CODE,
    HTTP_TARGET,
    HTTP_USER_AGENT,
    NET_HOST_PORT,
    NET_PEER_IP,
};

use crate::{
    async_trait, header::USER_AGENT, types::RealIp, Handler, IntoResponse, Request, RequestExt,
    Response, Result, Transform,
};

const HTTP_SERVER_ACTIVE_REQUESTS: &str = "http.server.active_requests";
const HTTP_SERVER_DURATION: &str = "http.server.duration";

/// Request metrics middleware config.
#[derive(Clone, Debug)]
pub struct Config {
    active_requests: UpDownCounter<i64>,
    duration: Histogram<f64>,
}

impl Config {
    /// Creates a new Config
    pub fn new(meter: Meter) -> Self {
        let active_requests = meter
            .i64_up_down_counter(HTTP_SERVER_ACTIVE_REQUESTS)
            .with_description("HTTP concurrent in-flight requests per route")
            .init();

        let duration = meter
            .f64_histogram(HTTP_SERVER_DURATION)
            .with_description("HTTP inbound request duration per route")
            .with_unit(Unit::new("ms"))
            .init();

        Config {
            active_requests,
            duration,
        }
    }
}

impl<H> Transform<H> for Config {
    type Output = MetricsMiddleware<H>;

    fn transform(&self, h: H) -> Self::Output {
        MetricsMiddleware {
            h,
            active_requests: self.active_requests.clone(),
            duration: self.duration.clone(),
        }
    }
}

/// Request metrics middleware with OpenTelemetry.
#[derive(Debug, Clone)]
pub struct MetricsMiddleware<H> {
    h: H,
    active_requests: UpDownCounter<i64>,
    duration: Histogram<f64>,
}

#[async_trait]
impl<H, O> Handler<Request> for MetricsMiddleware<H>
where
    O: IntoResponse,
    H: Handler<Request, Output = Result<O>> + Clone,
{
    type Output = Result<Response>;

    async fn call(&self, req: Request) -> Self::Output {
        let timer = SystemTime::now();
        let cx = Context::current();
        let mut attributes = build_attributes(&req, &req.route_info().pattern);

        self.active_requests.add(&cx, 1, &attributes);

        let res = self
            .h
            .call(req)
            .await
            .map(IntoResponse::into_response)
            .map(|resp| {
                self.active_requests.add(&cx, -1, &attributes);

                attributes.push(HTTP_STATUS_CODE.i64(resp.status().as_u16() as i64));

                resp
            });

        self.duration.record(
            &cx,
            timer
                .elapsed()
                .map(|t| t.as_secs_f64() * 1000.0)
                .unwrap_or_default(),
            &attributes,
        );

        res
    }
}

fn build_attributes(req: &Request, http_route: &String) -> Vec<KeyValue> {
    let mut attributes = Vec::with_capacity(10);
    attributes.push(
        HTTP_SCHEME.string(
            req.schema()
                .or(Some(&Scheme::HTTP))
                .map(ToString::to_string)
                .unwrap(),
        ),
    );
    attributes.push(HTTP_FLAVOR.string(format!("{:?}", req.version())));
    attributes.push(HTTP_METHOD.string(req.method().to_string()));
    attributes.push(HTTP_ROUTE.string(http_route.to_owned()));
    if let Some(path_and_query) = req.uri().path_and_query() {
        attributes.push(HTTP_TARGET.string(path_and_query.as_str().to_string()));
    }
    if let Some(host) = req.uri().host() {
        attributes.push(HTTP_HOST.string(host.to_string()));
    }
    if let Some(user_agent) = req.headers().get(USER_AGENT).and_then(|s| s.to_str().ok()) {
        attributes.push(HTTP_USER_AGENT.string(user_agent.to_string()));
    }
    let realip = RealIp::parse(req);
    if let Some(realip) = realip {
        attributes.push(HTTP_CLIENT_IP.string(realip.0.to_string()));
    }
    // if server_name != host {
    //     attributes.insert(HTTP_SERVER_NAME, server_name.to_string().into());
    // }
    if let Some(remote_ip) = req.remote_addr().map(|add| add.ip()) {
        if realip.map(|realip| realip.0 != remote_ip).unwrap_or(true) {
            // Client is going through a proxy
            attributes.push(NET_PEER_IP.string(remote_ip.to_string()));
        }
    }
    if let Some(port) = req
        .uri()
        .port_u16()
        .filter(|port| *port != 80 || *port != 443)
    {
        attributes.push(NET_HOST_PORT.i64(port as i64));
    }

    attributes
}