tower_http_tracing/
lib.rs

1//!Tower tracing middleware to annotate every HTTP request with tracing's span.
2//!
3//!## Span creation
4//!
5//!Use [macro](macro.make_request_spanner.html) to declare function that creates desirable span
6//!
7//!## Example
8//!
9//!Below is illustration of how to initialize request layer for passing into your service
10//!
11//!```rust
12//!use std::net::IpAddr;
13//!
14//!use tower_http_tracing::HttpRequestLayer;
15//!
16//!//Logic to extract client ip has to be written by user
17//!//You can use utilities in separate crate to design this logic:
18//!//https://docs.rs/http-ip/latest/http_ip/
19//!fn extract_client_ip(_parts: &http::request::Parts) -> Option<IpAddr> {
20//!    None
21//!}
22//!tower_http_tracing::make_request_spanner!(make_my_request_span("my_request", tracing::Level::INFO));
23//!let layer = HttpRequestLayer::new(make_my_request_span).with_extract_client_ip(extract_client_ip)
24//!                                                       .with_inspect_headers(&[&http::header::FORWARDED]);
25//!//Use above layer in your service
26//!```
27//!
28//!## Features
29//!
30//!- `opentelemetry` - Enables integration with opentelemetry to propagate context from requests and into responses
31
32#![warn(missing_docs)]
33#![allow(clippy::style)]
34
35mod grpc;
36mod headers;
37#[cfg(feature = "opentelemetry")]
38pub mod opentelemetry;
39
40use std::net::IpAddr;
41use core::{cmp, fmt, ptr, task};
42use core::pin::Pin;
43use core::future::Future;
44
45pub use tracing;
46
47///RequestId's header name
48pub const REQUEST_ID: http::HeaderName = http::HeaderName::from_static("x-request-id");
49///Alias to function signature required to create span
50pub type MakeSpan = fn() -> tracing::Span;
51///ALias to function signature to extract client's ip from request
52pub type ExtractClientIp = fn(&http::request::Parts) -> Option<IpAddr>;
53
54#[inline]
55fn default_client_ip(_: &http::request::Parts) -> Option<IpAddr> {
56    None
57}
58
59#[derive(Copy, Clone, PartialEq, Eq)]
60///Possible request protocol
61pub enum Protocol {
62    ///Regular HTTP call
63    ///
64    ///Default value for all requests
65    Http,
66    ///gRPC call, identified by presence of `Content-Type` with grpc protocol signature
67    Grpc,
68}
69
70impl Protocol {
71    #[inline(always)]
72    ///Determines protocol from value of `Content-Type`
73    pub fn from_content_type(typ: &[u8]) -> Self {
74        if typ.starts_with(b"application/grpc") {
75            Self::Grpc
76        } else {
77            Self::Http
78        }
79    }
80
81    #[inline(always)]
82    ///Returns textual representation of the `self`
83    pub const fn as_str(&self) -> &'static str {
84        match self {
85            Self::Grpc => "grpc",
86            Self::Http => "http"
87        }
88    }
89}
90
91impl fmt::Debug for Protocol {
92    #[inline(always)]
93    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
94        fmt::Debug::fmt(self.as_str(), fmt)
95    }
96}
97
98impl fmt::Display for Protocol {
99    #[inline(always)]
100    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
101        fmt::Display::fmt(self.as_str(), fmt)
102    }
103}
104
105type RequestIdBuffer = [u8; 64];
106
107#[derive(Clone)]
108///Request's id
109///
110///By default it is extracted from `X-Request-Id` header
111pub struct RequestId {
112    buffer: RequestIdBuffer,
113    len: u8,
114}
115
116impl RequestId {
117    fn from_bytes(bytes: &[u8]) -> Self {
118        let mut buffer: RequestIdBuffer = [0; 64];
119
120        let len = cmp::min(buffer.len(), bytes.len());
121
122        unsafe {
123            ptr::copy_nonoverlapping(bytes.as_ptr(), buffer.as_mut_ptr(), len)
124        };
125
126        Self {
127            buffer,
128            len: len as _,
129        }
130    }
131
132    fn from_uuid(uuid: uuid::Uuid) -> Self {
133        let mut buffer: RequestIdBuffer = [0; 64];
134        let uuid = uuid.as_hyphenated();
135        let len = uuid.encode_lower(&mut buffer).len();
136
137        Self {
138            buffer,
139            len: len as _,
140        }
141    }
142
143    #[inline]
144    ///Returns slice to already written data.
145    pub const fn as_bytes(&self) -> &[u8] {
146        unsafe {
147            core::slice::from_raw_parts(self.buffer.as_ptr(), self.len as _)
148        }
149    }
150
151    #[inline(always)]
152    ///Gets textual representation of the request id, if header value is string
153    pub const fn as_str(&self) -> Option<&str> {
154        match core::str::from_utf8(self.as_bytes()) {
155            Ok(header) => Some(header),
156            Err(_) => None,
157        }
158    }
159}
160
161impl fmt::Debug for RequestId {
162    #[inline(always)]
163    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
164        match self.as_str() {
165            Some(id) => fmt::Debug::fmt(id, fmt),
166            None => fmt::Debug::fmt(self.as_bytes(), fmt),
167        }
168    }
169}
170
171impl fmt::Display for RequestId {
172    #[inline(always)]
173    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
174        match self.as_str() {
175            Some(id) => fmt::Display::fmt(id, fmt),
176            None => fmt::Display::fmt("<non-utf8>", fmt),
177        }
178    }
179}
180
181#[macro_export]
182///Declares `fn` function compatible with `MakeSpan` using provided parameters
183///
184///## Span fields
185///
186///Following fields are declared when span is created:
187///- `http.request.method`
188///- `url.path`
189///- `url.query`
190///- `url.scheme`
191///- `http.request_id` - Inherited from request 'X-Request-Id' or random uuid
192///- `user_agent.original` - Only populated if user agent header is present
193///- `http.headers` - Optional. Populated if more than 1 header specified via layer [config](struct.HttpRequestLayer.html#method.with_inspect_headers)
194///- `network.protocol.name` - Either `http` or `grpc` depending on `content-type`
195///- `network.protocol.version` - Set to HTTP version in case of plain `http` protocol.
196///- `client.address` - Optionally added if IP extractor is specified via layer [config](struct.HttpRequestLayer.html#method.with_extract_client_ip)
197///- `http.response.status_code` - Semantics of this code depends on `protocol`
198///- `error.type` - Populated with `core::any::type_name` value of error type used by the service.
199///- `error.message` - Populated with `Display` content of the error, returned by underlying service, after processing request.
200///
201///Loosely follows <https://opentelemetry.io/docs/specs/semconv/http/http-spans/#http-server>
202///
203///## Usage
204///
205///```
206///use tower_http_tracing::make_request_spanner;
207///
208///make_request_spanner!(make_my_request_span("my_request", tracing::Level::INFO));
209/////Customize span with extra fields. You can use tracing::field::Empty if you want to omit value
210///make_request_spanner!(make_my_service_request_span("my_request", tracing::Level::INFO, service_name = "<your name>"));
211///
212///let span = make_my_request_span();
213///span.record("url.path", "I can override span field");
214///
215///```
216macro_rules! make_request_spanner {
217    ($fn:ident($name:literal, $level:expr)) => {
218        $crate::make_request_spanner!($fn($name, $level,));
219    };
220    ($fn:ident($name:literal, $level:expr, $($fields:tt)*)) => {
221        #[track_caller]
222        pub fn $fn() -> $crate::tracing::Span {
223            use $crate::tracing::field;
224
225            $crate::tracing::span!(
226                $level,
227                $name,
228                //Assigned on creation of span
229                http.request.method = field::Empty,
230                url.path = field::Empty,
231                url.query = field::Empty,
232                url.scheme = field::Empty,
233                http.request_id = field::Empty,
234                user_agent.original = field::Empty,
235                http.headers = field::Empty,
236                network.protocol.name = field::Empty,
237                network.protocol.version = field::Empty,
238                //Optional
239                client.address = field::Empty,
240                //Assigned after request is complete
241                http.response.status_code = field::Empty,
242                error.message = field::Empty,
243                $(
244                    $fields
245                )*
246            )
247        }
248    };
249}
250
251#[derive(Clone, Debug)]
252///Request's information
253///
254///It is accessible via [extensions](https://docs.rs/http/latest/http/struct.Extensions.html)
255pub struct RequestInfo {
256    ///Request's protocol
257    pub protocol: Protocol,
258    ///Request's id
259    pub request_id: RequestId,
260    ///Client's IP address extracted, if available.
261    pub client_ip: Option<IpAddr>,
262}
263
264///Request's span information
265///
266///Created on every request by the middleware, but not accessible to the user directly
267pub struct RequestSpan {
268    ///Underlying tracing span
269    pub span: tracing::Span,
270    ///Request's information
271    pub info: RequestInfo,
272}
273
274impl RequestSpan {
275    ///Creates new request span
276    pub fn new(span: tracing::Span, extract_client_ip: ExtractClientIp, parts: &http::request::Parts) -> Self {
277        let _entered = span.enter();
278
279        let client_ip = (extract_client_ip)(parts);
280        let protocol = parts.headers
281                            .get(http::header::CONTENT_TYPE)
282                            .map_or(Protocol::Http, |content_type| Protocol::from_content_type(content_type.as_bytes()));
283
284        let request_id = if let Some(request_id) = parts.headers.get(REQUEST_ID) {
285            RequestId::from_bytes(request_id.as_bytes())
286        } else {
287            RequestId::from_uuid(uuid::Uuid::new_v4())
288        };
289
290        if let Some(user_agent) = parts.headers.get(http::header::USER_AGENT).and_then(|header| header.to_str().ok()) {
291            span.record("user_agent.original", user_agent);
292        }
293        span.record("http.request.method", parts.method.as_str());
294        span.record("url.path", parts.uri.path());
295        if let Some(query) = parts.uri.query() {
296            span.record("url.query", query);
297        }
298        if let Some(scheme) = parts.uri.scheme() {
299            span.record("url.scheme", scheme.as_str());
300        }
301        if let Some(request_id) = request_id.as_str() {
302            span.record("http.request_id", &request_id);
303        } else {
304            span.record("http.request_id", request_id.as_bytes());
305        }
306        if let Some(client_ip) = client_ip {
307            span.record("client.address", tracing::field::display(client_ip));
308        }
309        span.record("network.protocol.name", protocol.as_str());
310        if let Protocol::Http = protocol {
311            match parts.version {
312                http::Version::HTTP_09 => span.record("network.protocol.version", 0.9),
313                http::Version::HTTP_10 => span.record("network.protocol.version", 1.0),
314                http::Version::HTTP_11 => span.record("network.protocol.version", 1.1),
315                http::Version::HTTP_2 => span.record("network.protocol.version", 2),
316                http::Version::HTTP_3 => span.record("network.protocol.version", 3),
317                //Invalid version so just set 0
318                _ => span.record("network.protocol.version", 0),
319            };
320        }
321
322        drop(_entered);
323
324        Self {
325            span,
326            info: RequestInfo {
327                protocol,
328                request_id,
329                client_ip
330            }
331        }
332    }
333}
334
335#[derive(Clone)]
336///Tower layer
337pub struct HttpRequestLayer {
338    make_span: MakeSpan,
339    inspect_headers: &'static [&'static http::HeaderName],
340    extract_client_ip: ExtractClientIp,
341}
342
343impl HttpRequestLayer {
344    #[inline]
345    ///Creates new layer with provided span maker
346    pub fn new(make_span: MakeSpan) -> Self {
347        Self {
348            make_span,
349            inspect_headers: &[],
350            extract_client_ip: default_client_ip
351        }
352    }
353
354    #[inline]
355    ///Specifies list of headers you want to inspect via `http.headers` attribute.
356    ///
357    ///By default none of the headers are inspected
358    pub fn with_inspect_headers(mut self, inspect_headers: &'static [&'static http::HeaderName]) -> Self {
359        self.inspect_headers = inspect_headers;
360        self
361    }
362
363    ///Customizes client ip extraction method
364    ///
365    ///Default extracts none
366    pub fn with_extract_client_ip(mut self, extract_client_ip: ExtractClientIp) -> Self {
367        self.extract_client_ip = extract_client_ip;
368        self
369    }
370}
371
372impl<S> tower_layer::Layer<S> for HttpRequestLayer {
373    type Service = HttpRequestService<S>;
374    #[inline(always)]
375    fn layer(&self, inner: S) -> Self::Service {
376        HttpRequestService {
377            layer: self.clone(),
378            inner,
379        }
380    }
381}
382
383///Tower service to annotate requests with span
384pub struct HttpRequestService<S> {
385    layer: HttpRequestLayer,
386    inner: S
387}
388
389impl<ReqBody, ResBody, S: tower_service::Service<http::Request<ReqBody>, Response = http::Response<ResBody>>> tower_service::Service<http::Request<ReqBody>> for HttpRequestService<S> where S::Error: std::error::Error {
390    type Response = S::Response;
391    type Error = S::Error;
392    type Future = ResponseFut<S::Future>;
393
394    #[inline(always)]
395    fn poll_ready(&mut self, ctx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
396        self.inner.poll_ready(ctx)
397    }
398
399    fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
400        let (parts, body) = req.into_parts();
401        let RequestSpan { span, info } = RequestSpan::new((self.layer.make_span)(), self.layer.extract_client_ip, &parts);
402
403        let mut req = http::Request::from_parts(parts, body);
404        #[cfg(feature = "opentelemetry")]
405        opentelemetry::on_request(&span, &req);
406
407        let _entered = span.enter();
408        if !self.layer.inspect_headers.is_empty() {
409            span.record("http.headers", tracing::field::debug(headers::InspectHeaders {
410                header_list: self.layer.inspect_headers,
411                headers: req.headers()
412            }));
413        }
414        let request_id = info.request_id.clone();
415        let protocol = info.protocol;
416        req.extensions_mut().insert(info);
417
418        let inner = self.inner.call(req);
419
420        drop(_entered);
421        ResponseFut {
422            inner,
423            span,
424            protocol,
425            request_id
426        }
427    }
428}
429
430///Middleware's response future
431pub struct ResponseFut<F> {
432    inner: F,
433    span: tracing::Span,
434    protocol: Protocol,
435    request_id: RequestId,
436}
437
438impl<ResBody, E: std::error::Error, F: Future<Output = Result<http::Response<ResBody>, E>>> Future for ResponseFut<F> {
439    type Output = F::Output;
440
441    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
442        let (fut, span, protocol, request_id) = unsafe {
443            let this = self.get_unchecked_mut();
444            (
445                Pin::new_unchecked(&mut this.inner),
446                &this.span,
447                this.protocol,
448                &this.request_id,
449            )
450        };
451        let _entered = span.enter();
452        match Future::poll(fut, ctx) {
453            task::Poll::Ready(Ok(mut resp)) => {
454                if let Ok(request_id) = http::HeaderValue::from_bytes(request_id.as_bytes()) {
455                    resp.headers_mut().insert(REQUEST_ID, request_id);
456                }
457                let status = match protocol {
458                    Protocol::Http => resp.status().as_u16(),
459                    Protocol::Grpc => match resp.headers().get("grpc-status") {
460                        Some(status) => grpc::parse_grpc_status(status.as_bytes()),
461                        None => 2,
462                    }
463                };
464                span.record("http.response.status_code", status);
465
466                #[cfg(feature = "opentelemetry")]
467                opentelemetry::on_response_ok(&span, &mut resp);
468
469                task::Poll::Ready(Ok(resp))
470            }
471            task::Poll::Ready(Err(error)) => {
472                let status = match protocol {
473                    Protocol::Http => 500u16,
474                    Protocol::Grpc => 13,
475                };
476                span.record("http.response.status_code", status);
477                span.record("error.type", core::any::type_name::<E>());
478                span.record("error.message", tracing::field::display(&error));
479
480                #[cfg(feature = "opentelemetry")]
481                opentelemetry::on_response_error(&span, &error);
482
483                task::Poll::Ready(Err(error))
484            },
485            task::Poll::Pending => task::Poll::Pending
486        }
487    }
488}