Skip to main content

waratah_api/
debug.rs

1//! SPARQL request tracing for `--debug` (`waratah start --foreground` /
2//! `waratah standalone`; the daemonized `waratah start` targets debug.txt).
3//!
4//! Lines go to stderr (or the daemon's debug file) so they stay out of SPARQL
5//! result output (stdout) and HTTP response bodies. Overlapping requests
6//! share a monotonic query id so "received" and "finished"/"failed" lines can
7//! be matched up.
8
9use std::fmt;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
13
14use axum::http::StatusCode;
15use waratah_compute::{LogLevel, LogSink, QueryContext, TraceSink};
16
17use crate::error::ApiError;
18
19/// SPARQL arrival / completion / client-error logger.
20///
21/// Cheap to clone: the query-id counter is shared, so overlapping HTTP
22/// requests keep a single sequence.
23#[derive(Debug, Clone)]
24pub struct QueryDebug {
25    enabled: bool,
26    next_id: Arc<AtomicU64>,
27    emit: Emit,
28}
29
30#[derive(Debug, Clone)]
31enum Emit {
32    Stderr,
33    /// Append to a shared file. The same handle goes into the compute
34    /// log/trace sinks so one debug file carries everything.
35    File(Arc<std::sync::Mutex<std::fs::File>>),
36    #[cfg(test)]
37    Capture(Arc<std::sync::Mutex<Vec<String>>>),
38}
39
40/// Token for one debug-traced SPARQL request.
41///
42/// Always carries a [`Self::query_id`] so compute log/trace can correlate even
43/// when stderr debug is off. Call [`finished`](QuerySpan::finished) or
44/// [`failed`](QuerySpan::failed) (or [`fail_msg`](QuerySpan::fail_msg) on the
45/// CLI path) so completion is logged when debug is on.
46#[must_use = "call finished(rows), failed(), or fail_msg() to log query completion"]
47pub struct QuerySpan {
48    id: u64,
49    inner: Option<ActiveSpan>,
50}
51
52struct ActiveSpan {
53    debug: QueryDebug,
54    id: u64,
55    started: Instant,
56}
57
58impl QueryDebug {
59    /// No debug output (default for tests and production-shaped serving).
60    pub fn off() -> Self {
61        Self {
62            enabled: false,
63            next_id: Arc::new(AtomicU64::new(1)),
64            emit: Emit::Stderr,
65        }
66    }
67
68    /// Log SPARQL arrivals, completions, and client errors to stderr.
69    pub fn on() -> Self {
70        Self {
71            enabled: true,
72            next_id: Arc::new(AtomicU64::new(1)),
73            emit: Emit::Stderr,
74        }
75    }
76
77    /// [`on`](Self::on) when `enabled`, otherwise [`off`](Self::off).
78    pub fn from_enabled(enabled: bool) -> Self {
79        if enabled { Self::on() } else { Self::off() }
80    }
81
82    /// Log SPARQL arrivals, completions, and client errors to an
83    /// already-open file, and point the compute log/trace sinks at the same
84    /// file (the daemonized `waratah start` debug log).
85    pub fn to_file(file: Arc<std::sync::Mutex<std::fs::File>>) -> Self {
86        Self {
87            enabled: true,
88            next_id: Arc::new(AtomicU64::new(1)),
89            emit: Emit::File(file),
90        }
91    }
92
93    /// Whether this logger will print anything.
94    pub fn enabled(&self) -> bool {
95        self.enabled
96    }
97
98    /// Log that a SPARQL query arrived, including the full query text.
99    ///
100    /// Always allocates a monotonic `query_id` so [`QueryContext`] can correlate
101    /// compute events even when this logger is off.
102    pub fn received(&self, sparql: &str) -> QuerySpan {
103        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
104        if !self.enabled {
105            return QuerySpan { id, inner: None };
106        }
107        let started = Instant::now();
108        let ts = format_utc(SystemTime::now());
109        self.emit_line(&received_message(id, &ts, sparql));
110        QuerySpan {
111            id,
112            inner: Some(ActiveSpan {
113                debug: self.clone(),
114                id,
115                started,
116            }),
117        }
118    }
119
120    /// Build the compute [`QueryContext`] for `span`: the engine's own base
121    /// context plus the query id and, when `--debug` is on, the log/trace
122    /// sinks (stderr, or the daemon's debug file).
123    ///
124    /// `base` MUST come from the engine (see [`ComputeBackend::query_context`](crate::ComputeBackend::query_context)).
125    /// Re-assembling a context here instead of deriving it drops everything
126    /// the engine knows: a `None` temporal epoch gates the temporal
127    /// comparison rewrite off entirely, so such a context would silently
128    /// answer every `?t >= const` from the unindexed residual — right
129    /// answers, no index — with nothing to log. That is exactly the bug this
130    /// signature is shaped to prevent.
131    pub fn query_context(&self, span: &QuerySpan, base: QueryContext) -> QueryContext {
132        let mut ctx = base.with_query_id(span.query_id());
133        if self.enabled {
134            ctx = match &self.emit {
135                Emit::Stderr => ctx
136                    .with_log(LogSink::stderr(LogLevel::Debug))
137                    .with_trace(TraceSink::stderr()),
138                Emit::File(file) => {
139                    let log = LogSink::file(LogLevel::Debug, Arc::clone(file));
140                    let trace = TraceSink::file(Arc::clone(file));
141                    ctx.with_log(log).with_trace(trace)
142                }
143                #[cfg(test)]
144                Emit::Capture(_) => ctx
145                    .with_log(LogSink::stderr(LogLevel::Debug))
146                    .with_trace(TraceSink::stderr()),
147            };
148        }
149        ctx
150    }
151
152    /// Log an HTTP error that never became a timed query (missing body, bad
153    /// content-type, and similar). Returns `error` unchanged for `?` / `return`.
154    pub fn client_error(&self, error: ApiError) -> ApiError {
155        if self.enabled {
156            let ts = format_utc(SystemTime::now());
157            self.emit_line(&client_error_message(
158                &ts,
159                error.status(),
160                &error.to_string(),
161            ));
162        }
163        error
164    }
165
166    fn emit_line(&self, line: &str) {
167        match &self.emit {
168            Emit::Stderr => eprintln!("{line}"),
169            Emit::File(file) => {
170                use std::io::Write;
171                // A poisoned mutex (a panic mid-write) must not disable the
172                // debug log forever: the file handle itself stays valid, so
173                // recover the guard and keep logging. Write failures stay
174                // swallowed — a lost diagnostic must not abort a query.
175                let mut file = file.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
176                let _ = writeln!(file, "{line}");
177            }
178            #[cfg(test)]
179            Emit::Capture(lines) => lines.lock().expect("debug log mutex").push(line.to_owned()),
180        }
181    }
182}
183
184impl QuerySpan {
185    /// Id allocated for this request (matches compute [`QueryContext::query_id`]).
186    pub fn query_id(&self) -> u64 {
187        self.id
188    }
189
190    /// Log successful completion and elapsed time.
191    pub fn finished(self, rows: usize) {
192        let Some(active) = self.inner else {
193            return;
194        };
195        let ts = format_utc(SystemTime::now());
196        let elapsed = format_duration(active.started.elapsed());
197        active.debug.emit_line(&finished_message(
198            active.id,
199            &ts,
200            &rows.to_string(),
201            &elapsed,
202        ));
203    }
204
205    /// Log failure (with HTTP status) and elapsed time. Returns `error` so
206    /// handlers can `return Err(span.failed(err))`.
207    pub fn failed(self, error: ApiError) -> ApiError {
208        if let Some(active) = &self.inner {
209            let ts = format_utc(SystemTime::now());
210            let elapsed = format_duration(active.started.elapsed());
211            active.debug.emit_line(&failed_message(
212                active.id,
213                &ts,
214                &elapsed,
215                error.status(),
216                &error.to_string(),
217            ));
218        }
219        error
220    }
221
222    /// Log failure without an HTTP status (CLI `--query` / REPL).
223    pub fn fail_msg(self, error: &dyn fmt::Display) {
224        let Some(active) = self.inner else {
225            return;
226        };
227        let ts = format_utc(SystemTime::now());
228        let elapsed = format_duration(active.started.elapsed());
229        active.debug.emit_line(&format!(
230            "debug [{ts}] SPARQL query #{} failed in {elapsed}: {error}",
231            active.id
232        ));
233    }
234}
235
236fn received_message(id: u64, ts: &str, sparql: &str) -> String {
237    format!("debug [{ts}] SPARQL query #{id} received:\n{sparql}")
238}
239
240fn finished_message(id: u64, ts: &str, len: &str, elapsed: &str) -> String {
241    format!("debug [{ts}] SPARQL query #{id} finished in {elapsed} (rows: {len})")
242}
243
244fn failed_message(id: u64, ts: &str, elapsed: &str, status: StatusCode, error: &str) -> String {
245    format!("debug [{ts}] SPARQL query #{id} failed in {elapsed} ({status}): {error}")
246}
247
248fn client_error_message(ts: &str, status: StatusCode, error: &str) -> String {
249    format!("debug [{ts}] SPARQL client error ({status}): {error}")
250}
251
252/// `YYYY-MM-DD HH:MM:SS.mmm UTC` from a [`SystemTime`].
253///
254/// Civil date conversion is Howard Hinnant's public-domain `civil_from_days`
255/// so we do not take a datetime crate just for debug timestamps.
256fn format_utc(now: SystemTime) -> String {
257    let duration = now.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
258    format_utc_parts(duration.as_secs(), duration.subsec_millis())
259}
260
261fn format_utc_parts(unix_secs: u64, millis: u32) -> String {
262    let days = (unix_secs / 86_400) as i64;
263    let tod = (unix_secs % 86_400) as u32;
264    let (year, month, day) = civil_from_unix_days(days);
265    let hour = tod / 3_600;
266    let min = (tod % 3_600) / 60;
267    let sec = tod % 60;
268    format!("{year:04}-{month:02}-{day:02} {hour:02}:{min:02}:{sec:02}.{millis:03} UTC")
269}
270
271/// Calendar date for `days` elapsed since 1970-01-01 (Unix day 0).
272fn civil_from_unix_days(days: i64) -> (i32, u32, u32) {
273    // Shift so day 0 is 0000-03-01, which puts leap days at the end of the
274    // year and simplifies the era / day-of-era arithmetic.
275    let z = days + 719_468;
276    let era = z.div_euclid(146_097);
277    let doe = (z - era * 146_097) as u32;
278    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
279    let mut year = yoe as i64 + era * 400;
280    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
281    let mp = (5 * doy + 2) / 153;
282    let day = doy - (153 * mp + 2) / 5 + 1;
283    let month = if mp < 10 { mp + 3 } else { mp - 9 };
284    if month <= 2 {
285        year += 1;
286    }
287    (year as i32, month, day)
288}
289
290fn format_duration(duration: Duration) -> String {
291    if duration < Duration::from_millis(1) {
292        format!("{}µs", duration.as_micros())
293    } else if duration < Duration::from_secs(1) {
294        format!("{:.3}ms", duration.as_secs_f64() * 1_000.0)
295    } else {
296        format!("{:.3}s", duration.as_secs_f64())
297    }
298}
299
300#[cfg(test)]
301impl QueryDebug {
302    pub(crate) fn capture(lines: Arc<std::sync::Mutex<Vec<String>>>) -> Self {
303        Self {
304            enabled: true,
305            next_id: Arc::new(AtomicU64::new(1)),
306            emit: Emit::Capture(lines),
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    use std::sync::Mutex;
315    use waratah_storage::SnapshotId;
316
317    #[test]
318    fn unix_epoch_formats_as_utc() {
319        assert_eq!(format_utc_parts(0, 0), "1970-01-01 00:00:00.000 UTC");
320        assert_eq!(
321            format_utc_parts(946_684_800, 123),
322            "2000-01-01 00:00:00.123 UTC"
323        );
324        assert_eq!(
325            format_utc_parts(1_000_000_000, 0),
326            "2001-09-09 01:46:40.000 UTC"
327        );
328    }
329
330    #[test]
331    fn leap_day_formats() {
332        // 2012-02-29 00:00:00 UTC
333        assert_eq!(
334            format_utc_parts(1_330_473_600, 0),
335            "2012-02-29 00:00:00.000 UTC"
336        );
337    }
338
339    #[test]
340    fn duration_picks_units() {
341        assert_eq!(format_duration(Duration::from_micros(42)), "42µs");
342        assert_eq!(format_duration(Duration::from_millis(12)), "12.000ms");
343        assert_eq!(format_duration(Duration::from_millis(1500)), "1.500s");
344    }
345
346    #[test]
347    fn capture_logs_received_and_finished() {
348        let lines = Arc::new(Mutex::new(Vec::new()));
349        let debug = QueryDebug::capture(lines.clone());
350        let span = debug.received("SELECT ?s WHERE { ?s ?p ?o }");
351        // Drop the guard before `finished`: it re-locks the same mutex to
352        // emit `(rows: N)`, and a temporary guard would live to the `;`.
353        let rows = lines.lock().unwrap().len();
354        span.finished(rows);
355        let logged = lines.lock().unwrap();
356        assert_eq!(logged.len(), 2);
357        assert!(logged[0].contains("SPARQL query #1 received:"));
358        assert!(logged[0].contains("SELECT ?s WHERE { ?s ?p ?o }"));
359        assert!(logged[1].contains("SPARQL query #1 finished in"));
360        assert!(logged[0].starts_with("debug ["));
361    }
362
363    #[test]
364    fn capture_logs_client_error() {
365        let lines = Arc::new(Mutex::new(Vec::new()));
366        let debug = QueryDebug::capture(lines.clone());
367        let _ = debug.client_error(ApiError::MissingQuery);
368        let logged = lines.lock().unwrap();
369        assert_eq!(logged.len(), 1);
370        assert!(logged[0].contains("SPARQL client error (400 Bad Request)"));
371        assert!(logged[0].contains("missing SPARQL query"));
372    }
373
374    #[test]
375    fn off_emits_nothing() {
376        let debug = QueryDebug::off();
377        let span = debug.received("SELECT * WHERE { ?s ?p ?o }");
378        assert_eq!(span.query_id(), 1);
379        span.finished(0);
380        let _ = debug.client_error(ApiError::MissingQuery);
381        assert!(!debug.enabled());
382    }
383
384    #[test]
385    fn off_still_allocates_monotonic_query_ids() {
386        let debug = QueryDebug::off();
387        let a = debug.received("ASK { }");
388        let b = debug.received("ASK { }");
389        assert_eq!(a.query_id(), 1);
390        assert_eq!(b.query_id(), 2);
391        a.finished(1);
392        b.finished(1);
393    }
394
395    #[test]
396    fn query_context_copies_query_id_and_default_union() {
397        let debug = QueryDebug::off();
398        let span = debug.received("ASK { }");
399        let base = QueryContext::from_snapshot(SnapshotId::latest()).with_default_union(true);
400        let ctx = debug.query_context(&span, base);
401        assert_eq!(ctx.query_id(), span.query_id());
402        assert!(ctx.default_union());
403        span.finished(1);
404    }
405
406    /// The engine's index trust epochs must ride every query context.
407    ///
408    /// `QueryDebug` used to re-assemble its context from (snapshot,
409    /// default_union) alone, which dropped both epochs: harmless for geo
410    /// (whose gate treats a missing epoch as trusted) but fatal for temporal
411    /// (whose gate treats a missing epoch as UNTRUSTED and refuses the
412    /// rewrite). One assertion per gate so a regression names its victim.
413    #[test]
414    fn query_context_keeps_the_base_context_index_epochs() {
415        let debug = QueryDebug::off();
416        let span = debug.received("ASK { }");
417        let base = QueryContext::from_snapshot(SnapshotId::latest())
418            .with_default_union(true)
419            .with_geo_index_epoch(Some(7))
420            .with_temporal_index_epoch(Some(9));
421        let ctx = debug.query_context(&span, base);
422        assert_eq!(ctx.query_id(), span.query_id());
423        assert!(ctx.default_union());
424        assert_eq!(
425            ctx.geo_index_epoch(),
426            Some(7),
427            "geo epoch dropped: geo rewrite would still work, so this one is silent"
428        );
429        assert_eq!(
430            ctx.temporal_index_epoch(),
431            Some(9),
432            "temporal epoch dropped: the comparison rewrite is gated OFF"
433        );
434        span.finished(1);
435    }
436
437    #[test]
438    fn message_shapes() {
439        let received = received_message(3, "ts", "ASK { ?s ?p ?o }");
440        assert_eq!(
441            received,
442            "debug [ts] SPARQL query #3 received:\nASK { ?s ?p ?o }"
443        );
444        assert_eq!(
445            finished_message(3, "ts", "7", "12.000ms"),
446            "debug [ts] SPARQL query #3 finished in 12.000ms (rows: 7)"
447        );
448        assert_eq!(
449            failed_message(3, "ts", "1.500s", StatusCode::BAD_REQUEST, "boom"),
450            "debug [ts] SPARQL query #3 failed in 1.500s (400 Bad Request): boom"
451        );
452    }
453}