1#![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
47pub const REQUEST_ID: http::HeaderName = http::HeaderName::from_static("x-request-id");
49pub type MakeSpan = fn() -> tracing::Span;
51pub 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)]
60pub enum Protocol {
62 Http,
66 Grpc,
68}
69
70impl Protocol {
71 #[inline(always)]
72 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 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)]
108pub 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 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 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]
182macro_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 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 client.address = field::Empty,
240 http.response.status_code = field::Empty,
242 error.message = field::Empty,
243 $(
244 $fields
245 )*
246 )
247 }
248 };
249}
250
251#[derive(Clone, Debug)]
252pub struct RequestInfo {
256 pub protocol: Protocol,
258 pub request_id: RequestId,
260 pub client_ip: Option<IpAddr>,
262}
263
264pub struct RequestSpan {
268 pub span: tracing::Span,
270 pub info: RequestInfo,
272}
273
274impl RequestSpan {
275 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 _ => 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)]
336pub 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 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 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 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
383pub 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
430pub 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}