1use std::{
5 future::Future,
6 io::Write,
7 path::Path,
8 sync::Mutex,
9 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
10};
11
12use anyhow::{Result, anyhow};
13use serde_json::{Value, json};
14
15use crate::paths;
16
17const MAX_FILE_BYTES: u64 = 512 * 1024;
18const KEEP_FILES: usize = 32;
19static WRITER: Mutex<()> = Mutex::new(());
20
21pub fn now_ms() -> u128 {
22 SystemTime::now()
23 .duration_since(UNIX_EPOCH)
24 .map(|d| d.as_millis())
25 .unwrap_or(0)
26}
27
28pub fn record(stage: &str, status: &str, elapsed_ms: u128, details: Value) {
29 let Ok(_guard) = WRITER.lock() else { return };
30 let _ = append(
32 &paths::state_dir().join("events"),
33 &json!({
34 "at": crate::clock::now_utc(), "unix_ms": now_ms(), "pid": std::process::id(),
35 "stage": stage, "status": status, "elapsed_ms": elapsed_ms, "details": details,
36 }),
37 );
38}
39
40fn append(dir: &Path, event: &Value) -> std::io::Result<()> {
41 paths::ensure_private_dir(dir)?;
42 let path = dir.join(format!("{}.jsonl", std::process::id()));
43 if std::fs::metadata(&path).is_ok_and(|m| m.len() >= MAX_FILE_BYTES) {
44 let previous = path.with_extension("previous.jsonl");
45 let _ = std::fs::remove_file(&previous);
46 std::fs::rename(&path, previous)?;
47 }
48 let mut file = paths::private_file()
49 .create(true)
50 .append(true)
51 .open(&path)?;
52 writeln!(file, "{event}")?;
53 let mut files: Vec<_> = std::fs::read_dir(dir)?
56 .flatten()
57 .filter(|e| e.path().extension().is_some_and(|s| s == "jsonl"))
58 .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
59 .collect();
60 files.sort_by_key(|(modified, _)| *modified);
61 let excess = files.len().saturating_sub(KEEP_FILES);
62 for (_, old) in files.into_iter().take(excess) {
63 if old != path {
64 let _ = std::fs::remove_file(old);
65 }
66 }
67 Ok(())
68}
69
70pub async fn step<T, E: std::fmt::Debug>(
72 name: &str,
73 details: Value,
74 timeout: Duration,
75 future: impl Future<Output = std::result::Result<T, E>>,
76) -> Result<T> {
77 let started = Instant::now();
78 record(name, "started", 0, details.clone());
79 let result = match tokio::time::timeout(timeout, future).await {
80 Ok(Ok(value)) => Ok(value),
81 Ok(Err(error)) => Err(anyhow!("{name}: {error:?}")),
82 Err(_) => Err(anyhow!(
83 "{name}: timed out after {} ms",
84 timeout.as_millis()
85 )),
86 };
87 let mut details = json!({ "context": details });
88 if let Err(error) = &result {
89 details["error"] = json!(format!("{error:#}"));
90 }
91 record(
92 name,
93 if result.is_ok() { "ok" } else { "error" },
94 started.elapsed().as_millis(),
95 details,
96 );
97 result
98}
99
100pub fn init_tracing() {
102 let filter = std::env::var("IPH_LOG").unwrap_or_else(|_| "warn".into());
103 let _ = tracing_subscriber::fmt()
104 .with_env_filter(tracing_subscriber::EnvFilter::new(filter))
105 .with_writer(std::io::stderr)
106 .with_ansi(false)
107 .try_init();
108}