1
//! Unified profiling gate.
2
//!
3
//! Reads `AZ_PROFILE` once on first access, caches the result forever.
4
//! Value is a comma-separated list of tokens; unknown tokens are ignored,
5
//! whitespace is trimmed, matching is case-insensitive.
6
//!
7
//! Tokens:
8
//! - `memory`  — heap-breakdown dumps (StyledDom, LayoutCache, text cache, cascade maps, RSS).
9
//!   Printed to stderr once per frame.
10
//! - `cpu`     — per-phase wall-clock timings from `Probe::span` (layout, style, cascade, paint,
11
//!   callbacks, …), dumped once per frame so stuttering frames are easy to spot.
12
//! - `cascade` — narrow diagnostic for prop-cache work: top-N CSS properties by cascade-walk count
13
//!   per frame.
14
//! - `heap`    — phase-boundary heap probes in `regenerate_layout` (`emit_phase_heap`). By
15
//!   themselves print nothing — pair with `jsonl` + `AZ_PROFILE_OUT` to persist.
16
//! - `jsonl`   — format heap probes as JSONL to the file named by `AZ_PROFILE_OUT=<path>`. Requires
17
//!   `heap` to do anything.
18
//! - `detail`  — opt-in to the fine-grained per-step probes inside each phase (e.g. `rf_*` labels
19
//!   inside `rust_fontconfig::request_fonts`, and the `_extra` cache-size payloads). Layered on top
20
//!   of `heap`.
21
//!
22
//! ## Examples
23
//! - `AZ_PROFILE=cpu` — per-phase CPU timings to stderr.
24
//! - `AZ_PROFILE=heap,jsonl AZ_PROFILE_OUT=/tmp/run.jsonl` → coarse phase heap probes to JSONL.
25
//! - `AZ_PROFILE=heap,jsonl,detail AZ_PROFILE_OUT=/tmp/detail.jsonl` → fine-grained (per-step) heap
26
//!   probes to JSONL.
27
//! - `AZ_PROFILE=cpu,cascade` — both dumps simultaneously.
28
//!
29
//! Tokens are independent flags, not mutually exclusive modes. Unset
30
//! or empty leaves every quick path silent.
31
//!
32
//! ## Path for jsonl output
33
//! `AZ_PROFILE_OUT` is read separately (not folded into `AZ_PROFILE`
34
//! because the value can contain `,` and `=` and a path is a different
35
//! shape from a flag). When `jsonl` is set but `AZ_PROFILE_OUT` is
36
//! unset, writers silently skip — no stderr fallback so benchmarks
37
//! don't get polluted.
38
//!
39
//! ## Portability
40
//! - **macOS / Linux**: full support. Span timings via `Instant`; RSS checkpoints via `task_info` /
41
//!   `/proc/self/statm`.
42
//! - **Windows**: span timings work. RSS checkpoints silently read 0 (the RSS helpers in
43
//!   `azul_layout::probe` are `cfg(unix)`-gated).
44
//! - **WASM (`target_family = "wasm"`)**: `Instant::now()` panics on browser WASM (no monotonic
45
//!   clock) and `libc::getrusage` isn't available. The probe module detects WASM at compile time
46
//!   and forces the no-op impl.
47

            
48
#[cfg(feature = "std")]
49
use std::sync::OnceLock;
50

            
51
/// Set of active `AZ_PROFILE` tokens. Parsed once from the env var.
52
// independent profile toggles parsed from the env var; a bitflags type would
53
// not improve this flat set of named booleans.
54
#[allow(clippy::struct_excessive_bools)]
55
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
56
pub struct ProfileFlags {
57
    pub memory: bool,
58
    pub cpu: bool,
59
    pub cascade: bool,
60
    pub heap: bool,
61
    pub jsonl: bool,
62
    pub detail: bool,
63
}
64

            
65
impl ProfileFlags {
66
4333
    fn parse(value: &str) -> Self {
67
4333
        let mut f = Self::default();
68
2366674
        for tok in value.split(',') {
69
2366674
            let t = tok.trim();
70
2366674
            if t.eq_ignore_ascii_case("memory") || t.eq_ignore_ascii_case("mem") {
71
179
                f.memory = true;
72
2366495
            } else if t.eq_ignore_ascii_case("cpu") || t.eq_ignore_ascii_case("perf") {
73
250254
                f.cpu = true;
74
2116241
            } else if t.eq_ignore_ascii_case("cascade") || t.eq_ignore_ascii_case("css") {
75
171
                f.cascade = true;
76
2116070
            } else if t.eq_ignore_ascii_case("heap") {
77
152
                f.heap = true;
78
2115918
            } else if t.eq_ignore_ascii_case("jsonl") {
79
136
                f.jsonl = true;
80
2115782
            } else if t.eq_ignore_ascii_case("detail") {
81
130
                f.detail = true;
82
2115652
            }
83
        }
84
4333
        f
85
4333
    }
86
}
87

            
88
#[cfg(feature = "std")]
89
#[inline]
90
5962
pub fn flags() -> ProfileFlags {
91
    static FLAGS: OnceLock<ProfileFlags> = OnceLock::new();
92
5962
    *FLAGS.get_or_init(|| {
93
206
        let raw = std::env::var("AZ_PROFILE").ok();
94
206
        let f = raw
95
206
            .as_deref()
96
206
            .map(ProfileFlags::parse)
97
206
            .unwrap_or_default();
98
        // A typo'd token must WARN and keep running, never silently parse to
99
        // nothing - AZ_PROFILE=phases looked exactly like AZ_PROFILE unset,
100
        // and "a zero is not a measurement".
101
206
        if let Some(raw) = &raw {
102
            let known = |t: &str| {
103
                matches!(
104
                    t.to_ascii_lowercase().as_str(),
105
                    "memory" | "mem" | "cpu" | "perf" | "cascade" | "css" | "heap" | "jsonl"
106
                        | "detail" | ""
107
                )
108
            };
109
            let mut unknown: Vec<&str> =
110
                raw.split(',').map(str::trim).filter(|t| !known(t)).collect();
111
            unknown.truncate(8); // a garbage value must not flood stderr
112
            if !unknown.is_empty() {
113
                eprintln!(
114
                    "[azul][profile] AZ_PROFILE={raw:?}: unknown token(s) {unknown:?} ignored -                      valid values are cpu (perf), memory (mem), cascade (css), heap, jsonl,                      detail; combine with commas, e.g. AZ_PROFILE=cpu,memory"
115
                );
116
            }
117
206
        }
118
        // The announce table: a profile mode that silently emits NOTHING
119
        // reads as "not looking" and has repeatedly burned real debugging
120
        // time ("a zero is not a measurement"). One line, once, at the
121
        // single point every mode resolves through.
122
206
        if f.heap && !f.jsonl {
123
            eprintln!(
124
                "[azul][profile] AZ_PROFILE=heap alone emits nothing: use \
125
                 AZ_PROFILE=heap,jsonl with AZ_PROFILE_OUT=<file> for the \
126
                 per-phase heap table (and note builds without the `probe` \
127
                 feature report heap as 0)."
128
            );
129
206
        }
130
206
        if f.heap && f.jsonl && std::env::var("AZ_PROFILE_OUT").is_err() {
131
            eprintln!(
132
                "[azul][profile] AZ_PROFILE=heap,jsonl is set but \
133
                 AZ_PROFILE_OUT is not — no destination, nothing will be \
134
                 written."
135
            );
136
206
        }
137
206
        f
138
206
    })
139
5962
}
140

            
141
/// `no_std` builds have no environment; profiling is always off.
142
#[cfg(not(feature = "std"))]
143
#[inline]
144
pub fn flags() -> ProfileFlags {
145
    let _ = ProfileFlags::parse;
146
    ProfileFlags::default()
147
}
148

            
149
/// `AZ_PROFILE_OUT=<path>` — destination for JSONL heap probes.
150
/// Returns `None` if unset. Cached on first access.
151
#[cfg(feature = "std")]
152
#[inline]
153
101
pub fn out_path() -> Option<&'static str> {
154
    static PATH: OnceLock<Option<String>> = OnceLock::new();
155
101
    PATH.get_or_init(|| std::env::var("AZ_PROFILE_OUT").ok())
156
101
        .as_deref()
157
101
}
158

            
159
/// `no_std` builds have no environment; no output path.
160
#[cfg(not(feature = "std"))]
161
#[inline]
162
pub fn out_path() -> Option<&'static str> {
163
    None
164
}
165

            
166
#[inline]
167
#[must_use]
168
835
pub fn memory_enabled() -> bool {
169
835
    flags().memory
170
835
}
171

            
172
#[inline]
173
#[must_use]
174
335
pub fn cpu_enabled() -> bool {
175
335
    flags().cpu
176
335
}
177

            
178
#[inline]
179
#[must_use]
180
388
pub fn cascade_enabled() -> bool {
181
388
    flags().cascade
182
388
}
183

            
184
#[inline]
185
#[must_use]
186
290
pub fn heap_enabled() -> bool {
187
290
    flags().heap
188
290
}
189

            
190
#[inline]
191
#[must_use]
192
201
pub fn jsonl_enabled() -> bool {
193
201
    flags().jsonl
194
201
}
195

            
196
#[inline]
197
#[must_use]
198
1312
pub fn detail_enabled() -> bool {
199
1312
    flags().detail
200
1312
}
201

            
202
#[cfg(test)]
203
#[path = "profile_test.rs"]
204
mod profile_test;