session_core/
startup_trace.rs1use std::io::Write;
7use std::path::Path;
8use std::sync::OnceLock;
9
10pub const TRACE_ENV: &str = "ULTRON_STARTUP_TRACE";
11
12pub fn trace_line(at: f64, origin: f64, pid: u32, label: &str) -> String {
14 let line = serde_json::json!({"at": at, "origin": origin, "pid": pid, "label": label});
15 format!("{line}\n")
16}
17
18pub fn append(path: &Path, at: f64, origin: f64, pid: u32, label: &str) {
19 let file = std::fs::OpenOptions::new().create(true).append(true).open(path);
20 if let Ok(mut file) = file {
21 let _ = file.write_all(trace_line(at, origin, pid, label).as_bytes());
22 }
23}
24
25fn now_ms() -> f64 {
26 std::time::SystemTime::now()
27 .duration_since(std::time::UNIX_EPOCH)
28 .map_or(0.0, |d| d.as_secs_f64() * 1000.0)
29}
30
31fn origin() -> f64 {
34 static ORIGIN: OnceLock<f64> = OnceLock::new();
35 *ORIGIN.get_or_init(|| {
36 let start = || -> Option<f64> {
37 let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
38 let rest = &stat[stat.rfind(')')? + 2..];
40 let ticks: f64 = rest.split(' ').nth(19)?.parse().ok()?;
41 let boot = std::fs::read_to_string("/proc/stat").ok()?;
42 let btime: f64 = boot
43 .lines()
44 .find_map(|l| l.strip_prefix("btime "))?
45 .trim()
46 .parse()
47 .ok()?;
48 Some(btime * 1000.0 + ticks * 10.0)
49 };
50 start().unwrap_or_else(now_ms)
51 })
52}
53
54pub fn trace_startup(path: Option<&str>, label: &str) {
56 let Some(path) = path.filter(|p| !p.is_empty()) else {
57 return;
58 };
59 let origin = origin();
60 append(Path::new(path), now_ms().max(origin), origin, std::process::id(), label);
61}