Skip to main content

rust_webx_host/
request_tracing.rs

1//! Structured request tracing middleware with trace_id injection.
2
3use rust_webx_core::error::Result;
4use rust_webx_core::http::IHttpContext;
5use rust_webx_core::middleware::IMiddleware;
6use std::ops::ControlFlow;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9static COUNTER: AtomicU64 = AtomicU64::new(0);
10static TRACE_SEQ: AtomicU64 = AtomicU64::new(0);
11
12pub struct RequestTracing {
13    pub log_all: bool,
14}
15
16impl RequestTracing {
17    pub fn new() -> Self {
18        Self { log_all: true }
19    }
20    pub fn errors_only() -> Self {
21        Self { log_all: false }
22    }
23}
24
25impl Default for RequestTracing {
26    fn default() -> Self {
27        Self::new()
28    }
29}
30
31#[async_trait::async_trait]
32impl IMiddleware for RequestTracing {
33    async fn invoke(&self, ctx: &mut dyn IHttpContext) -> Result<ControlFlow<()>> {
34        // Propagate existing request ID from upstream, or generate a new one.
35        let tid = ctx.request().header("x-request-id").map(|s| s.to_string())
36            .unwrap_or_else(next_trace_id);
37        ctx.response_mut().set_header("x-trace-id", &tid);
38        Ok(ControlFlow::Continue(()))
39    }
40
41    async fn after(&self, ctx: &mut dyn IHttpContext) -> Result<()> {
42        let status = ctx.response().status();
43        let is_err = status >= 400;
44
45        if self.log_all || is_err {
46            let count = COUNTER.fetch_add(1, Ordering::Relaxed);
47            let method = ctx.request().method().to_string();
48            let path = ctx.request().path().to_string();
49            let user = ctx.claims().map(|c| c.subject().to_string());
50
51            if is_err {
52                tracing::warn!(
53                    count = count, method = %method, path = %path,
54                    status = status, user = %user.as_deref().unwrap_or("anon"),
55                    "request error"
56                );
57            } else {
58                tracing::info!(
59                    count = count, method = %method, path = %path,
60                    status = status, user = %user.as_deref().unwrap_or("anon"),
61                    "request ok"
62                );
63            }
64        }
65        Ok(())
66    }
67}
68
69fn next_trace_id() -> String {
70    let id = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
71    format!("{:016x}", id)
72}