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