agentmux_srv_core/
boot_timing.rs1use std::sync::{Mutex, OnceLock};
31use std::time::Instant;
32
33pub struct BootTimings {
35 started: Instant,
36 steps: Vec<(&'static str, u64)>,
37}
38
39impl BootTimings {
40 pub fn new() -> Self {
41 Self { started: Instant::now(), steps: Vec::new() }
42 }
43
44 #[cfg(test)]
46 pub fn time<T>(&mut self, step: &'static str, f: impl FnOnce() -> T) -> T {
47 let t = Instant::now();
48 let out = f();
49 self.steps.push((step, t.elapsed().as_millis() as u64));
50 out
51 }
52
53 #[cfg(test)]
54 pub fn steps(&self) -> &[(&'static str, u64)] {
55 &self.steps
56 }
57
58 pub fn accounted_ms(&self) -> u64 {
63 self.steps.iter().map(|(_, ms)| ms).sum()
64 }
65
66 pub fn total_ms(&self) -> u64 {
69 self.started.elapsed().as_millis() as u64
70 }
71
72 pub fn summary(&self) -> String {
78 let mut sorted: Vec<_> = self.steps.clone();
79 sorted.sort_by(|a, b| b.1.cmp(&a.1));
80 let steps = sorted
81 .iter()
82 .map(|(step, ms)| format!("{step}={ms}ms"))
83 .collect::<Vec<_>>()
84 .join(" ");
85 format!(
86 "total={}ms accounted={}ms | {}",
87 self.total_ms(),
88 self.accounted_ms(),
89 steps
90 )
91 }
92}
93
94impl Default for BootTimings {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100fn recorder() -> &'static Mutex<Option<BootTimings>> {
103 static RECORDER: OnceLock<Mutex<Option<BootTimings>>> = OnceLock::new();
104 RECORDER.get_or_init(|| Mutex::new(None))
105}
106
107pub fn init() {
109 *recorder().lock().unwrap() = Some(BootTimings::new());
110}
111
112pub fn time<T>(step: &'static str, f: impl FnOnce() -> T) -> T {
119 let t = Instant::now();
120 let out = f();
121 let ms = t.elapsed().as_millis() as u64;
122 if let Ok(mut guard) = recorder().lock() {
123 if let Some(timings) = guard.as_mut() {
124 timings.steps.push((step, ms));
125 }
126 }
127 out
128}
129
130pub fn step<T: StepOutcome>(id: &'static str, label: &str, f: impl FnOnce() -> T) -> T {
137 eprintln!("{}", agentmux_common::srv_stderr::step_begin_line(id, label));
138 let t = Instant::now();
139 let out = time(id, f);
140 eprintln!("{}", agentmux_common::srv_stderr::step_end_line(id, t.elapsed().as_millis() as u64, out.succeeded()));
141 out
142}
143
144pub trait StepOutcome {
147 fn succeeded(&self) -> bool;
148}
149
150impl<T, E> StepOutcome for Result<T, E> {
151 fn succeeded(&self) -> bool {
152 self.is_ok()
153 }
154}
155
156pub const SLOW_STEP: std::time::Duration = std::time::Duration::from_millis(250);
158
159pub fn step_if_slow<T: StepOutcome>(id: &'static str, label: &str, f: impl FnOnce() -> T) -> T {
164 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
165 let begin = agentmux_common::srv_stderr::step_begin_line(id, label);
166 let watcher = std::thread::spawn(move || {
167 let slow = done_rx.recv_timeout(SLOW_STEP).is_err();
168 if slow {
169 eprintln!("{begin}");
170 }
171 slow
172 });
173 let t = Instant::now();
174 let out = time(id, f);
175 let _ = done_tx.send(());
176 if watcher.join().unwrap_or(false) {
179 eprintln!("{}", agentmux_common::srv_stderr::step_end_line(id, t.elapsed().as_millis() as u64, out.succeeded()));
180 }
181 out
182}
183
184pub async fn time_async<T>(step: &'static str, fut: impl std::future::Future<Output = T>) -> T {
186 let t = Instant::now();
187 let out = fut.await;
188 let ms = t.elapsed().as_millis() as u64;
189 if let Ok(mut guard) = recorder().lock() {
190 if let Some(timings) = guard.as_mut() {
191 timings.steps.push((step, ms));
192 }
193 }
194 out
195}
196
197pub fn log_summary() {
199 let Ok(guard) = recorder().lock() else { return };
200 let Some(timings) = guard.as_ref() else { return };
201 tracing::info!(target: "boot_timing", "boot_timing: {}", timings.summary());
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use std::thread::sleep;
214 use std::time::Duration;
215
216 #[test]
217 fn time_returns_the_inner_value() {
218 let mut t = BootTimings::new();
219 assert_eq!(t.time("step", || 42), 42);
220 }
221
222 #[test]
223 fn steps_are_recorded_in_call_order() {
224 let mut t = BootTimings::new();
225 t.time("first", || {});
226 t.time("second", || {});
227 let names: Vec<_> = t.steps().iter().map(|(n, _)| *n).collect();
228 assert_eq!(names, vec!["first", "second"]);
229 }
230
231 #[test]
232 fn a_steps_duration_reflects_real_elapsed_time() {
233 let mut t = BootTimings::new();
234 t.time("slow", || sleep(Duration::from_millis(12)));
235 let (_, ms) = t.steps()[0];
236 assert!(ms >= 10, "expected >=10ms for a 12ms sleep, got {ms}ms");
237 }
238
239 #[test]
240 fn summary_lists_every_step_slowest_first() {
241 let mut t = BootTimings::new();
242 t.steps.push(("fast", 2));
243 t.steps.push(("slowest", 300));
244 t.steps.push(("middle", 40));
245 let s = t.summary();
246 let slowest = s.find("slowest=300ms").expect("slowest step must appear");
247 let middle = s.find("middle=40ms").expect("middle step must appear");
248 let fast = s.find("fast=2ms").expect("fast step must appear");
249 assert!(slowest < middle && middle < fast, "steps must be ordered slowest-first: {s}");
250 }
251
252 #[test]
253 fn summary_reports_total_and_accounted_separately() {
254 let mut t = BootTimings::new();
257 t.steps.push(("a", 10));
258 t.steps.push(("b", 20));
259 let s = t.summary();
260 assert!(s.contains("accounted=30ms"), "{s}");
261 assert!(s.contains("total="), "{s}");
262 }
263
264 #[test]
265 fn global_time_runs_the_closure_even_when_uninitialized() {
266 let mut ran = false;
269 time("never-initialized", || ran = true);
270 assert!(ran);
271 }
272
273 #[test]
274 fn nested_global_timing_does_not_deadlock() {
275 let out = time("outer", || time("inner", || 7));
278 assert_eq!(out, 7);
279 }
280
281 #[test]
282 fn step_if_slow_passes_the_result_through_fast_or_slow() {
283 let fast: Result<u8, String> = step_if_slow("fast_step", "Fast", || Ok(1));
284 assert_eq!(fast, Ok(1));
285 let t = std::time::Instant::now();
286 let slow: Result<u8, String> = step_if_slow("slow_step", "Slow", || {
287 sleep(SLOW_STEP + Duration::from_millis(50));
288 Err("timed out".into())
289 });
290 assert_eq!(slow, Err("timed out".to_string()));
291 assert!(t.elapsed() < SLOW_STEP * 4, "the watcher must not hold the caller up");
292 }
293}