Skip to main content

oxtel_tower/
server.rs

1//! The HTTP server layer.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6use std::task::{Context, Poll, ready};
7use std::time::Instant;
8
9use http::{Request, Response};
10use metrics::Label;
11use oxtel_sdk::propagation::extract_trace_context;
12use oxtel_sdk::trace::attach_remote_parent;
13use tower_layer::Layer;
14use tower_service::Service;
15use tracing::Span;
16
17use crate::request::{RequestInfo, method_name, protocol_version, server_address};
18
19type RouteFn = Arc<dyn for<'a> Fn(&'a http::Extensions) -> Option<&'a str> + Send + Sync>;
20type SpanFn = Arc<dyn Fn(&RequestInfo<'_>) -> Span + Send + Sync>;
21
22#[derive(Clone)]
23struct Config {
24    propagate: bool,
25    metrics: bool,
26    access_log: bool,
27    scheme: &'static str,
28    route: Option<RouteFn>,
29    make_span: SpanFn,
30}
31
32/// Instruments an HTTP server, as the OpenTelemetry semantic conventions
33/// for HTTP servers describe:
34///
35/// - **A span per request**, a child of the caller's when the request
36///   carries W3C `traceparent`. Named `{method} {route}`, with
37///   `http.request.method`, `url.path`, `url.scheme`, `http.route`,
38///   `server.address`, `server.port`, `network.protocol.version`,
39///   `user_agent.original`, `http.response.status_code`, and `error.type`
40///   with status Error for 5xx responses.
41/// - **Metrics**, through the `metrics` facade: `http.server.request.duration`
42///   (seconds) by method, scheme, route, status, protocol version and
43///   `error.type`; and `http.server.active_requests` by method and scheme.
44/// - **An access log event**, if asked for: `request` at `info`, or `error`
45///   for 5xx, with the status and duration.
46///
47/// The duration runs until the response's head is ready; a streamed body
48/// may take longer. The query string isn't recorded.
49#[derive(Clone)]
50pub struct HttpServerLayer {
51    config: Arc<Config>,
52}
53
54impl Default for HttpServerLayer {
55    fn default() -> Self {
56        HttpServerLayer::new()
57    }
58}
59
60impl HttpServerLayer {
61    /// A layer with spans, propagation, metrics and the access log on. With
62    /// the `axum` feature, `http.route` comes from axum's
63    /// `MatchedPath`. Make it after installing the `metrics` recorder; see
64    /// [`describe_metrics`](crate::describe_metrics).
65    pub fn new() -> Self {
66        #[cfg(feature = "axum")]
67        let route: Option<RouteFn> = Some(Arc::new(|ext: &http::Extensions| {
68            ext.get::<axum::extract::MatchedPath>().map(|m| m.as_str())
69        }));
70        #[cfg(not(feature = "axum"))]
71        let route: Option<RouteFn> = None;
72        crate::describe_metrics();
73        HttpServerLayer {
74            config: Arc::new(Config {
75                propagate: true,
76                metrics: true,
77                access_log: true,
78                scheme: "http",
79                route,
80                make_span: Arc::new(|info| crate::server_span!(info)),
81            }),
82        }
83    }
84
85    fn config(&mut self) -> &mut Config {
86        Arc::make_mut(&mut self.config)
87    }
88
89    /// Continue the caller's trace from W3C `traceparent` and `tracestate`
90    /// headers. Default: true. Turn it off at a trust boundary, where
91    /// callers shouldn't choose your trace ids or sampling.
92    pub fn with_propagation(mut self, enabled: bool) -> Self {
93        self.config().propagate = enabled;
94        self
95    }
96
97    /// Record the request metrics. Default: true.
98    pub fn with_metrics(mut self, enabled: bool) -> Self {
99        self.config().metrics = enabled;
100        self
101    }
102
103    /// Log each finished request as an event: `request` at `info`, or at
104    /// `error` for a 5xx. Default: true. `RUST_LOG=info,oxtel_tower=warn`
105    /// also hides it, but keeps the errors.
106    pub fn with_access_log(mut self, enabled: bool) -> Self {
107        self.config().access_log = enabled;
108        self
109    }
110
111    /// The `url.scheme` for requests whose URI has none, as on a server
112    /// behind a proxy that ends TLS. Default: `http`.
113    pub fn with_scheme(mut self, scheme: &'static str) -> Self {
114        self.config().scheme = scheme;
115        self
116    }
117
118    /// Where the matched route template comes from, for routers other than
119    /// axum's.
120    pub fn with_route(
121        mut self,
122        route: impl for<'a> Fn(&'a http::Extensions) -> Option<&'a str> + Send + Sync + 'static,
123    ) -> Self {
124        self.config().route = Some(Arc::new(route));
125        self
126    }
127
128    /// Make each request's span yourself, to declare fields of your own
129    /// for later middleware to record. Use [`server_span!`](crate::server_span)
130    /// so the standard fields are declared too:
131    ///
132    /// ```
133    /// use oxtel_tower::{HttpServerLayer, server_span};
134    ///
135    /// let layer = HttpServerLayer::new()
136    ///     .with_span(|info| server_span!(info, app.user.id = tracing::field::Empty));
137    /// ```
138    pub fn with_span(
139        mut self,
140        make_span: impl Fn(&RequestInfo<'_>) -> Span + Send + Sync + 'static,
141    ) -> Self {
142        self.config().make_span = Arc::new(make_span);
143        self
144    }
145}
146
147impl<S> Layer<S> for HttpServerLayer {
148    type Service = HttpServer<S>;
149
150    fn layer(&self, inner: S) -> Self::Service {
151        HttpServer {
152            inner,
153            config: Arc::clone(&self.config),
154        }
155    }
156}
157
158/// The service [`HttpServerLayer`] wraps around yours.
159#[derive(Clone)]
160pub struct HttpServer<S> {
161    inner: S,
162    config: Arc<Config>,
163}
164
165impl<S, B, RB> Service<Request<B>> for HttpServer<S>
166where
167    S: Service<Request<B>, Response = Response<RB>>,
168{
169    type Response = Response<RB>;
170    type Error = S::Error;
171    type Future = ResponseFuture<S::Future>;
172
173    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
174        self.inner.poll_ready(cx)
175    }
176
177    fn call(&mut self, req: Request<B>) -> Self::Future {
178        let config = &self.config;
179        let (method, method_original) = method_name(req.method());
180        let (server_address, server_port) = server_address(&req);
181        let route = config.route.as_ref().and_then(|f| f(req.extensions()));
182        let info = RequestInfo {
183            method,
184            method_original,
185            path: req.uri().path(),
186            scheme: req.uri().scheme_str().unwrap_or(config.scheme),
187            route,
188            server_address,
189            server_port,
190            protocol_version: protocol_version(req.version()),
191            user_agent: req
192                .headers()
193                .get(http::header::USER_AGENT)
194                .and_then(|v| v.to_str().ok()),
195        };
196        let span = {
197            let _parent = config
198                .propagate
199                .then(|| extract_trace_context(req.headers()).map(attach_remote_parent))
200                .flatten();
201            (config.make_span)(&info)
202        };
203        let finish = Finish {
204            method,
205            scheme: info.scheme.to_string(),
206            route: info.route.map(str::to_string),
207            protocol_version: info.protocol_version,
208            config: Arc::clone(config),
209        };
210        let active = config
211            .metrics
212            .then(|| Active::start(method, finish.scheme.clone()));
213        let inner = span.in_scope(|| self.inner.call(req));
214        ResponseFuture {
215            inner,
216            span,
217            started: Instant::now(),
218            finish: Some(finish),
219            _active: active,
220        }
221    }
222}
223
224pin_project_lite::pin_project! {
225    /// The response future of [`HttpServer`].
226    pub struct ResponseFuture<F> {
227        #[pin]
228        inner: F,
229        span: Span,
230        started: Instant,
231        finish: Option<Finish>,
232        _active: Option<Active>,
233    }
234}
235
236impl<F, RB, E> Future for ResponseFuture<F>
237where
238    F: Future<Output = Result<Response<RB>, E>>,
239{
240    type Output = Result<Response<RB>, E>;
241
242    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
243        let this = self.project();
244        let _entered = this.span.enter();
245        let result = ready!(this.inner.poll(cx));
246        if let Some(finish) = this.finish.take() {
247            finish.finish(this.span, &result, this.started.elapsed());
248        }
249        Poll::Ready(result)
250    }
251}
252
253/// What's recorded once the response is ready.
254struct Finish {
255    method: &'static str,
256    scheme: String,
257    route: Option<String>,
258    protocol_version: &'static str,
259    config: Arc<Config>,
260}
261
262impl Finish {
263    fn finish<RB, E>(
264        self,
265        span: &Span,
266        result: &Result<Response<RB>, E>,
267        elapsed: std::time::Duration,
268    ) {
269        let status = result.as_ref().ok().map(|r| r.status().as_u16());
270        let error_type = match (status, result) {
271            (Some(s), _) if s >= 500 => Some(s.to_string()),
272            (_, Err(_)) => Some(std::any::type_name::<E>().to_string()),
273            _ => None,
274        };
275        if let Some(status) = status {
276            span.record("http.response.status_code", status);
277        }
278        if let Some(error) = &error_type {
279            span.record("error.type", error.as_str());
280            span.record("otel.status_code", "error");
281        }
282        if self.config.access_log {
283            let duration = elapsed.as_secs_f64();
284            if error_type.is_some() {
285                tracing::error!(
286                    http.response.status_code = status,
287                    http.server.request.duration = duration,
288                    error.type = error_type.as_deref(),
289                    "request"
290                );
291            } else {
292                tracing::info!(
293                    http.response.status_code = status,
294                    http.server.request.duration = duration,
295                    "request"
296                );
297            }
298        }
299        if self.config.metrics {
300            let mut labels = vec![
301                Label::new("http.request.method", self.method),
302                Label::new("url.scheme", self.scheme),
303                Label::new("network.protocol.version", self.protocol_version),
304            ];
305            if let Some(route) = self.route {
306                labels.push(Label::new("http.route", route));
307            }
308            if let Some(status) = status {
309                labels.push(Label::new("http.response.status_code", status.to_string()));
310            }
311            if let Some(error) = error_type {
312                labels.push(Label::new("error.type", error));
313            }
314            metrics::histogram!("http.server.request.duration", labels)
315                .record(elapsed.as_secs_f64());
316        }
317    }
318}
319
320/// Counts a request in `http.server.active_requests` while it lives, so
321/// cancelled requests are uncounted too.
322struct Active {
323    gauge: metrics::Gauge,
324}
325
326impl Active {
327    fn start(method: &'static str, scheme: String) -> Self {
328        let gauge = metrics::gauge!(
329            "http.server.active_requests",
330            "http.request.method" => method,
331            "url.scheme" => scheme
332        );
333        gauge.increment(1.0);
334        Active { gauge }
335    }
336}
337
338impl Drop for Active {
339    fn drop(&mut self) {
340        self.gauge.decrement(1.0);
341    }
342}