1#![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
41pub const REQUEST_ID: http::HeaderName = http::HeaderName::from_static("x-request-id");
43pub type MakeSpan = fn() -> tracing::Span;
45pub 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)]
54pub enum Protocol {
56 Http,
60 Grpc,
62}
63
64impl Protocol {
65 #[inline(always)]
66 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 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)]
102pub 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 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 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]
176macro_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 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 http.client.ip = field::Empty,
227 http.status_code = field::Empty,
229 error.message = field::Empty,
230 $(
231 $fields
232 )*
233 )
234 }
235 };
236}
237
238#[derive(Clone, Debug)]
239pub struct RequestInfo {
243 pub protocol: Protocol,
245 pub request_id: RequestId,
247 pub client_ip: Option<IpAddr>,
249}
250
251pub struct RequestSpan {
255 pub span: tracing::Span,
257 pub info: RequestInfo,
259}
260
261impl RequestSpan {
262 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)]
307pub 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 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 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 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
354pub 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
397pub 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}