Skip to main content

capy_framework/
diagnostics.rs

1use axum::{
2    extract::{MatchedPath, Request, State},
3    http::HeaderValue,
4    middleware::Next,
5    response::Response,
6};
7use capy_core::ErrorKind;
8use std::{
9    sync::Arc,
10    time::{Duration, Instant},
11};
12use tracing::Instrument;
13
14pub(crate) const DEFAULT_FILTER: &str = "info,sqlx=warn,sea_orm=warn";
15
16/// Safe response-header completion data for optional application telemetry.
17#[derive(Clone, Debug)]
18pub struct RequestObservation {
19    /// Untrusted correlation label, validated for log-safe characters and length.
20    pub request_id: String,
21    /// HTTP request method.
22    pub method: String,
23    /// Matched route template, or the fixed label `<unmatched>` (never query data).
24    pub route: String,
25    /// HTTP response status.
26    pub status: u16,
27    /// Duration until response headers; streaming body completion is not measured.
28    pub duration: Duration,
29    /// Safe error category, without driver errors or request content.
30    pub error_kind: Option<&'static str>,
31}
32
33/// Application-owned telemetry adapter. Callbacks must be fast, nonblocking, and
34/// must not panic. Enqueue bounded events in your adapter for async exporters.
35/// No vendor, exporter, global registry, or background worker is installed by Capy.
36pub trait RequestObserver: Send + Sync + 'static {
37    /// Observe completion of a request's response headers, including timeouts.
38    fn on_response(&self, observation: &RequestObservation);
39}
40
41impl<F: Fn(&RequestObservation) + Send + Sync + 'static> RequestObserver for F {
42    fn on_response(&self, observation: &RequestObservation) {
43        self(observation);
44    }
45}
46
47pub(crate) type Observer = Option<Arc<dyn RequestObserver>>;
48
49pub(crate) async fn request(
50    State(observer): State<Observer>,
51    mut request: Request,
52    next: Next,
53) -> Response {
54    let id = request
55        .headers()
56        .get("x-request-id")
57        .and_then(|value| value.to_str().ok())
58        .filter(|value| {
59            !value.is_empty()
60                && value.len() <= 128
61                && value
62                    .bytes()
63                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
64        })
65        .map(str::to_owned)
66        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
67    let header = HeaderValue::from_str(&id).expect("validated ASCII request ID");
68    request.headers_mut().insert("x-request-id", header.clone());
69    let method = request.method().clone();
70    // Never record the query string. Prefer the route template over path parameters.
71    let route = request
72        .extensions()
73        .get::<MatchedPath>()
74        .map(|path| path.as_str())
75        .unwrap_or_else(|| request.uri().path())
76        .to_owned();
77    let observed_route = request
78        .extensions()
79        .get::<MatchedPath>()
80        .map(|path| path.as_str())
81        .unwrap_or("<unmatched>")
82        .to_owned();
83    let span = tracing::info_span!("http.request", request_id = %id, %method, %route);
84    async move {
85        let started = Instant::now();
86        let mut response = next.run(request).await;
87        response.headers_mut().insert("x-request-id", header);
88        let status = response.status().as_u16();
89        let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
90        if let Some(observer) = observer {
91            observer.on_response(&RequestObservation {
92                request_id: id.clone(), method: method.to_string(), route: observed_route,
93                status, duration: started.elapsed(),
94                error_kind: response.extensions().get::<ErrorKind>().map(|kind| kind.0),
95            });
96        }
97        if response.status().is_server_error() {
98            let error_kind = response.extensions().get::<ErrorKind>().map_or("internal", |kind| kind.0);
99            tracing::error!(request_id = %id, %method, %route, status, latency_ms, error_kind, "request failed");
100        } else {
101            tracing::info!(request_id = %id, %method, %route, status, latency_ms, "request completed");
102        }
103        response
104    }.instrument(span).await
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::{App, AppConfig, AppContext, AppError, Routes};
111    use capy_testing::TestApp;
112    use std::{
113        io::Write,
114        sync::{Arc, Mutex},
115    };
116    use tracing::instrument::WithSubscriber;
117
118    #[derive(Clone)]
119    struct Capture(Arc<Mutex<Vec<u8>>>);
120    impl Write for Capture {
121        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
122            self.0.lock().unwrap().extend_from_slice(bytes);
123            Ok(bytes.len())
124        }
125        fn flush(&mut self) -> std::io::Result<()> {
126            Ok(())
127        }
128    }
129
130    #[tokio::test]
131    async fn production_diagnostics_correlate_requests_without_secrets() {
132        let bytes = Arc::new(Mutex::new(Vec::new()));
133        let capture = Capture(bytes.clone());
134        let subscriber = tracing_subscriber::fmt()
135            .with_env_filter(tracing_subscriber::EnvFilter::new(DEFAULT_FILTER))
136            .json()
137            .with_ansi(false)
138            .with_writer(move || capture.clone())
139            .finish();
140        async {
141            let mut config = AppConfig::default();
142            config.app.environment = "production".into();
143            config.database.url = "sqlite::memory:".into();
144            let context = AppContext {
145                db: capy_db::connect(&config.database).await.unwrap(),
146                config: Arc::new(config),
147            };
148            let app = TestApp::new(
149                App::new()
150                    .routes(
151                        Routes::new()
152                            .get("/posts/{id}", crate::health)
153                            .get("/failure", || async {
154                                AppError::Database(sea_orm::DbErr::Custom(
155                                    "postgres://secret:password@host/private SQL SELECT".into(),
156                                ))
157                            })
158                            .get("/native", || async {
159                                axum::http::StatusCode::INTERNAL_SERVER_ERROR
160                            }),
161                    )
162                    .into_router(context),
163            );
164            let response = app
165                .get("/posts/123?token=secret-query")
166                .header(
167                    "x-request-id".parse().unwrap(),
168                    HeaderValue::from_static("request-123"),
169                )
170                .header(
171                    "authorization".parse().unwrap(),
172                    HeaderValue::from_static("Bearer secret-header"),
173                )
174                .send()
175                .await;
176            response.assert_ok();
177            assert_eq!(response.headers["x-request-id"], "request-123");
178            let failure = app.get("/failure").send().await;
179            failure.assert_json(serde_json::json!({"message": "Internal server error"}));
180            assert!(
181                uuid::Uuid::parse_str(failure.headers["x-request-id"].to_str().unwrap()).is_ok()
182            );
183            for id in ["", "bad id", "x\"y", &"a".repeat(129)] {
184                let response = app
185                    .get("/native")
186                    .header(
187                        "x-request-id".parse().unwrap(),
188                        HeaderValue::from_str(id).unwrap(),
189                    )
190                    .send()
191                    .await;
192                assert!(
193                    uuid::Uuid::parse_str(response.headers["x-request-id"].to_str().unwrap())
194                        .is_ok()
195                );
196            }
197            app.get("/missing?token=secret-query")
198                .send()
199                .await
200                .assert_status(axum::http::StatusCode::NOT_FOUND);
201        }
202        .with_subscriber(subscriber)
203        .await;
204        let output = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
205        for secret in [
206            "password",
207            "secret",
208            "SQL SELECT",
209            "authorization",
210            "123?token",
211        ] {
212            assert!(!output.contains(secret), "{output}");
213        }
214        let events: Vec<serde_json::Value> = output
215            .lines()
216            .map(|line| serde_json::from_str(line).unwrap())
217            .collect();
218        let requests: Vec<_> = events
219            .iter()
220            .filter(|event| event["fields"]["status"].is_number())
221            .collect();
222        assert_eq!(requests.len(), 7, "one completion per request: {output}");
223        let success = requests
224            .iter()
225            .find(|e| e["fields"]["status"] == 200)
226            .unwrap();
227        assert_eq!(success["level"], "INFO");
228        assert_eq!(success["fields"]["route"], "/posts/{id}");
229        assert_eq!(success["fields"]["request_id"], "request-123");
230        assert_eq!(success["span"]["request_id"], "request-123");
231        assert!(requests
232            .iter()
233            .any(|e| e["fields"]["route"] == "/missing" && e["fields"]["status"] == 404));
234        assert!(requests.iter().any(|e| e["level"] == "ERROR"
235            && e["fields"]["error_kind"] == "database"
236            && e["fields"]["status"] == 500));
237        for event in requests {
238            assert_eq!(event["fields"]["method"], "GET");
239            assert!(event["fields"]["latency_ms"].is_number());
240            assert!(event["fields"]["request_id"].is_string());
241        }
242    }
243
244    #[tokio::test]
245    async fn startup_errors_retain_native_causes_but_format_safely() {
246        use std::error::Error;
247        let settings = crate::DatabaseSettings {
248            url: "postgres://private-user:private-password@127.0.0.1:1/private-db".into(),
249            connect_timeout_seconds: 1,
250            ..Default::default()
251        };
252        let error = capy_db::connect(&settings).await.unwrap_err();
253        assert!(error
254            .source()
255            .unwrap()
256            .downcast_ref::<sea_orm::DbErr>()
257            .is_some());
258        let display = format!("{error} {error:?}");
259        assert!(display.contains("Failed to connect to database"));
260        for secret in [
261            "private-user",
262            "private-password",
263            "private-db",
264            "postgres://",
265        ] {
266            assert!(!display.contains(secret));
267        }
268        let error = AppError::DatabaseConnection(sea_orm::DbErr::Conn(
269            sea_orm::RuntimeErr::SqlxError(sea_orm::SqlxError::Io(std::io::Error::new(
270                std::io::ErrorKind::ConnectionRefused,
271                "private-password",
272            ))),
273        ));
274        assert!(error.to_string().contains("connection refused"));
275        assert!(!format!("{error:?}").contains("private-password"));
276        assert!(error.source().unwrap().source().is_some());
277    }
278}