Skip to main content

session_core/
startup_trace.rs

1//! `traceStartup` (experimental/startup-trace.ts), the writer of the CLI, session-worker and client milestones:
2//! append one startup milestone to the file named by `ULTRON_STARTUP_TRACE` (every process of a start shares it), as
3//! a JSON line `{at, origin, pid, label}`: `at` the wall-clock time in milliseconds, `origin` the process's start
4//! (`performance.timeOrigin`). Off unless the variable is set; a failed write is ignored (tracing never affects startup).
5
6use std::io::Write;
7use std::path::Path;
8use std::sync::OnceLock;
9
10pub const TRACE_ENV: &str = "ULTRON_STARTUP_TRACE";
11
12/// The trace line of `label` at `at` for process `pid` started at `origin` (`JSON.stringify` key order).
13pub 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
31/// This process's start in milliseconds since the epoch: `/proc/self/stat` start time (clock ticks after boot,
32/// USER_HZ 100) plus `/proc/stat` `btime`; else the first trace's time.
33fn 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            // Fields after the parenthesized command name; starttime is field 22 overall.
39            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
54/// `traceStartup(label)` with the trace file `path` (`ULTRON_STARTUP_TRACE`; nothing when unset or empty).
55pub 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}