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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! Http OpenTelemetry [`Layer`] Support for Rama.
//!
//! [`Layer`]: crate::service::Layer

use crate::{
    http::RequestContext,
    telemetry::opentelemetry::{
        global,
        metrics::{Histogram, Meter, UpDownCounter},
        semantic_conventions, KeyValue,
    },
};
use crate::{
    http::{
        self,
        headers::{HeaderMapExt, UserAgent},
        IntoResponse, Request, Response,
    },
    net::stream::SocketInfo,
    service::{Context, Layer, Service},
};
use headers::ContentLength;
use std::{fmt, sync::Arc, time::SystemTime};

// Follows the experimental semantic conventions for HTTP metrics:
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md

use semantic_conventions::attribute::{
    CLIENT_ADDRESS, CLIENT_PORT, HTTP_REQUEST_BODY_SIZE, HTTP_REQUEST_METHOD,
    HTTP_RESPONSE_BODY_SIZE, HTTP_RESPONSE_STATUS_CODE, NETWORK_PROTOCOL_VERSION, SERVER_ADDRESS,
    SERVER_PORT, URL_PATH, URL_QUERY, URL_SCHEME, USER_AGENT_ORIGINAL,
};

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

// TODO: do we also want to track actual calculated body size?
// this would mean we _need_ to buffer the body, which is not ideal
// Perhaps make it opt-in?
// NOTE: we could also make this opt-in via BytesRWTrackerHandle (rama::net::stream::BytesRWTrackerHandle)
// this would however not work properly (I think) with h2/h3...
// const HTTP_SERVER_REQUEST_SIZE: &str = "http.server.request.size";
// const HTTP_SERVER_RESPONSE_SIZE: &str = "http.server.response.size";

/// Records http server metrics
///
/// See the [spec] for details.
///
/// [spec]: https://github.com/open-telemetry/semantic-conventions/blob/v1.21.0/docs/http/http-metrics.md#http-server
#[derive(Clone, Debug)]
struct Metrics {
    http_server_duration: Histogram<f64>,
    http_server_active_requests: UpDownCounter<i64>,
    // http_server_request_size: Histogram<u64>,
    // http_server_response_size: Histogram<u64>,
}

impl Metrics {
    /// Create a new [`RequestMetrics`]
    fn new(meter: Meter) -> Self {
        let http_server_duration = meter
            .f64_histogram(HTTP_SERVER_DURATION)
            .with_description("Measures the duration of inbound HTTP requests.")
            .with_unit("s")
            .init();

        let http_server_active_requests = meter
            .i64_up_down_counter(HTTP_SERVER_ACTIVE_REQUESTS)
            .with_description(
                "Measures the number of concurrent HTTP requests that are currently in-flight.",
            )
            .init();

        // let http_server_request_size = meter
        //     .u64_histogram(HTTP_SERVER_REQUEST_SIZE)
        //     .with_description("Measures the size of HTTP request messages (compressed).")
        //     .with_unit(Unit::new("By"))
        //     .init();

        // let http_server_response_size = meter
        //     .u64_histogram(HTTP_SERVER_RESPONSE_SIZE)
        //     .with_description("Measures the size of HTTP response messages (compressed).")
        //     .with_unit(Unit::new("By"))
        //     .init();

        Metrics {
            http_server_active_requests,
            http_server_duration,
            // http_server_request_size,
            // http_server_response_size,
        }
    }
}

#[derive(Debug, Clone)]
/// A layer that records http server metrics using OpenTelemetry.
pub struct RequestMetricsLayer {
    metrics: Arc<Metrics>,
}

impl RequestMetricsLayer {
    /// Create a new [`RequestMetricsLayer`] using the global [`Meter`] provider.
    pub fn new() -> Self {
        let meter = get_versioned_meter();
        let metrics = Metrics::new(meter);
        Self {
            metrics: Arc::new(metrics),
        }
    }
}

impl Default for RequestMetricsLayer {
    fn default() -> Self {
        Self::new()
    }
}

/// construct meters for this crate
fn get_versioned_meter() -> Meter {
    global::meter_with_version(
        crate::utils::info::NAME,
        Some(crate::utils::info::VERSION),
        Some(semantic_conventions::SCHEMA_URL),
        None,
    )
}

impl<S> Layer<S> for RequestMetricsLayer {
    type Service = RequestMetricsService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RequestMetricsService {
            inner,
            metrics: self.metrics.clone(),
        }
    }
}

/// A [`Service`] that records [http] server metrics using OpenTelemetry.
pub struct RequestMetricsService<S> {
    inner: S,
    metrics: Arc<Metrics>,
}

impl<S> RequestMetricsService<S> {
    /// Create a new [`RequestMetricsService`].
    pub fn new(inner: S) -> Self {
        RequestMetricsLayer::new().layer(inner)
    }

    define_inner_service_accessors!();
}

impl<S: fmt::Debug> fmt::Debug for RequestMetricsService<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestMetricsService")
            .field("inner", &self.inner)
            .field("metrics", &self.metrics)
            .finish()
    }
}

impl<S: Clone> Clone for RequestMetricsService<S> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            metrics: self.metrics.clone(),
        }
    }
}

impl<S, State, Body> Service<State, Request<Body>> for RequestMetricsService<S>
where
    S: Service<State, Request<Body>>,
    S::Response: IntoResponse,
    State: Send + Sync + 'static,
    Body: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;

    async fn serve(
        &self,
        mut ctx: Context<State>,
        req: Request<Body>,
    ) -> Result<Self::Response, Self::Error> {
        let mut attributes: Vec<KeyValue> = compute_attributes(&mut ctx, &req);

        self.metrics.http_server_active_requests.add(1, &attributes);

        // used to compute the duration of the request
        let timer = SystemTime::now();

        let result = self.inner.serve(ctx, req).await;
        self.metrics
            .http_server_active_requests
            .add(-1, &attributes);

        match result {
            Ok(res) => {
                let res = res.into_response();

                attributes.push(KeyValue::new(
                    HTTP_RESPONSE_STATUS_CODE,
                    res.status().as_u16() as i64,
                ));

                if let Some(content_length) = res.headers().typed_get::<ContentLength>() {
                    attributes.push(KeyValue::new(
                        HTTP_RESPONSE_BODY_SIZE,
                        content_length.0 as i64,
                    ));
                }

                self.metrics.http_server_duration.record(
                    timer.elapsed().map(|t| t.as_secs_f64()).unwrap_or_default(),
                    &attributes,
                );

                Ok(res)
            }
            Err(err) => Err(err),
        }
    }
}

fn compute_attributes<State, Body>(ctx: &mut Context<State>, req: &Request<Body>) -> Vec<KeyValue> {
    let mut attributes = Vec::with_capacity(12);

    // client info
    if let Some(socket_info) = ctx.get::<SocketInfo>() {
        let peer_addr = socket_info.peer_addr();
        attributes.push(KeyValue::new(CLIENT_ADDRESS, peer_addr.ip().to_string()));
        attributes.push(KeyValue::new(CLIENT_PORT, peer_addr.port() as i64));
    }

    // server info
    let request_ctx: Option<&mut RequestContext> = ctx
        .get_or_try_insert_with_ctx(|ctx| (ctx, req).try_into())
        .ok();
    if let Some(authority) = request_ctx.as_ref().map(|rc| &rc.authority) {
        attributes.push(KeyValue::new(SERVER_ADDRESS, authority.host().to_string()));
        attributes.push(KeyValue::new(SERVER_PORT, authority.port() as i64));
    }

    // Request Info
    let uri = req.uri();
    match uri.path() {
        "" | "/" => (),
        path => attributes.push(KeyValue::new(URL_PATH, path.to_owned())),
    }
    match uri.query() {
        Some("") | None => (),
        Some(query) => attributes.push(KeyValue::new(URL_QUERY, query.to_owned())),
    }
    if let Some(protocol) = request_ctx.as_ref().map(|rc| &rc.protocol) {
        attributes.push(KeyValue::new(URL_SCHEME, protocol.to_string()));
    }

    // Common attrs (Request Info)
    // <https://github.com/open-telemetry/semantic-conventions/blob/v1.21.0/docs/http/http-spans.md#common-attributes>

    attributes.push(KeyValue::new(HTTP_REQUEST_METHOD, req.method().to_string()));
    if let Some(http_version) = request_ctx.as_ref().and_then(|rc| match rc.http_version {
        http::Version::HTTP_09 => Some("0.9"),
        http::Version::HTTP_10 => Some("1.0"),
        http::Version::HTTP_11 => Some("1.1"),
        http::Version::HTTP_2 => Some("2"),
        http::Version::HTTP_3 => Some("3"),
        _ => None,
    }) {
        attributes.push(KeyValue::new(NETWORK_PROTOCOL_VERSION, http_version));
    }

    if let Some(ua) = req.headers().typed_get::<UserAgent>() {
        attributes.push(KeyValue::new(USER_AGENT_ORIGINAL, ua.to_string()));
    }

    if let Some(content_length) = req.headers().typed_get::<ContentLength>() {
        attributes.push(KeyValue::new(
            HTTP_REQUEST_BODY_SIZE,
            content_length.0 as i64,
        ));
    }

    attributes
}