ftui_runtime/debug_trace.rs
1#![forbid(unsafe_code)]
2
3//! Zero-cost debug tracing controlled by environment variable.
4//!
5//! Enable runtime debug output by setting `FTUI_DEBUG_TRACE=1` before launching
6//! your application, with stderr redirected. When disabled (the default), the
7//! trace checks compile down to a single static bool load with no other
8//! overhead.
9//!
10//! The trace stays off while stderr is a terminal: that is the terminal the UI
11//! draws on, and a trace line written there lands between frames
12//! (bd-g00-root-epic-ewths.33.4).
13//!
14//! # Usage
15//!
16//! ```bash
17//! FTUI_DEBUG_TRACE=1 cargo run -p ftui-demo-showcase 2>trace.log
18//! ```
19//!
20//! This module provides `debug_trace!` macro for conditional debug output:
21//!
22//! ```ignore
23//! use ftui_runtime::debug_trace;
24//! debug_trace!("loop iteration {}", count);
25//! ```
26
27use std::sync::LazyLock;
28use web_time::Instant;
29
30/// Static flag checked once at startup. After initialization, this is just a bool load.
31static DEBUG_TRACE_ENABLED: LazyLock<bool> = LazyLock::new(|| {
32 trace_enabled(
33 std::env::var("FTUI_DEBUG_TRACE").ok().as_deref(),
34 std::io::IsTerminal::is_terminal(&std::io::stderr()),
35 )
36});
37
38/// `FTUI_DEBUG_TRACE` is `1` or `true`, and stderr is not a terminal.
39fn trace_enabled(flag: Option<&str>, stderr_is_terminal: bool) -> bool {
40 let requested = flag.is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
41 requested && !stderr_is_terminal
42}
43
44/// Startup timestamp for relative timing in debug output.
45static START_TIME: LazyLock<Instant> = LazyLock::new(Instant::now);
46
47/// Check if debug tracing is enabled.
48///
49/// This function is inlined and after the first call, compiles down to a single
50/// static bool load - effectively zero cost when disabled.
51#[inline]
52pub fn is_enabled() -> bool {
53 *DEBUG_TRACE_ENABLED
54}
55
56/// Get elapsed time since program start in milliseconds.
57///
58/// Useful for correlating debug output across threads.
59#[inline]
60pub fn elapsed_ms() -> u64 {
61 START_TIME.elapsed().as_millis() as u64
62}
63
64/// Conditionally print debug trace output to stderr.
65///
66/// When `FTUI_DEBUG_TRACE=1` is set and stderr is not a terminal, prints
67/// timestamped debug messages. When disabled, compiles to a single bool check
68/// (effectively zero cost).
69///
70/// # Example
71///
72/// ```ignore
73/// debug_trace!("subscription started: id={}", sub_id);
74/// debug_trace!("main loop heartbeat: frame={}", frame_count);
75/// ```
76#[macro_export]
77macro_rules! debug_trace {
78 ($($arg:tt)*) => {
79 if $crate::debug_trace::is_enabled() {
80 eprintln!(
81 "[FTUI {:>8}ms] {}",
82 $crate::debug_trace::elapsed_ms(),
83 format_args!($($arg)*)
84 );
85 }
86 };
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn trace_needs_the_flag_and_a_stderr_that_is_not_the_terminal() {
95 assert!(trace_enabled(Some("1"), false));
96 assert!(trace_enabled(Some("TRUE"), false));
97 assert!(
98 !trace_enabled(Some("1"), true),
99 "stderr is the UI's terminal"
100 );
101 assert!(!trace_enabled(Some("0"), false));
102 assert!(!trace_enabled(None, false));
103 }
104
105 #[test]
106 fn test_is_enabled_returns_bool() {
107 // Just verify it returns a bool without panicking
108 let _ = is_enabled();
109 }
110
111 #[test]
112 fn test_elapsed_ms_increases() {
113 let t1 = elapsed_ms();
114 std::thread::sleep(std::time::Duration::from_millis(10));
115 let t2 = elapsed_ms();
116 assert!(t2 >= t1);
117 }
118}