agentmux_common/
record_events.rs1use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15
16const PREFIX: &str = "events-";
17const EXT: &str = "jsonl";
18const MAX_LINE_BYTES: usize = 2_048;
20
21pub fn record_dir() -> Option<PathBuf> {
24 crate::data_paths::DataPaths::from_env().map(|p| record_dir_in(&p))
25}
26
27pub fn record_dir_in(paths: &crate::data_paths::DataPaths) -> PathBuf {
29 paths.instance_dir.join("record")
30}
31
32fn year_month(t_ms: u64) -> (i64, u32) {
34 let z = (t_ms / 86_400_000) as i64 + 719_468;
36 let era = z.div_euclid(146_097);
37 let doe = z.rem_euclid(146_097);
38 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
39 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
40 let mp = (5 * doy + 2) / 153;
41 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
42 let year = yoe + era * 400 + i64::from(month <= 2);
43 (year, month)
44}
45
46pub fn file_name(t_ms: u64) -> String {
48 let (y, m) = year_month(t_ms);
49 format!("{PREFIX}{y:04}-{m:02}.{EXT}")
50}
51
52pub fn month_of_file(name: &str) -> Option<&str> {
54 let month = name.strip_prefix(PREFIX)?.strip_suffix(&format!(".{EXT}"))?;
55 let (y, m) = month.split_once('-')?;
56 (y.len() == 4 && m.len() == 2 && y.bytes().all(|b| b.is_ascii_digit()) && m.bytes().all(|b| b.is_ascii_digit())).then_some(month)
57}
58
59static WRITE: Mutex<()> = Mutex::new(());
62
63pub fn append_event(dir: &Path, t_ms: u64, kind: &str, fields: serde_json::Value) -> std::io::Result<()> {
67 let serde_json::Value::Object(mut line) = fields else {
68 return Err(std::io::Error::other("an event's fields are an object"));
69 };
70 line.insert("t".into(), t_ms.into());
71 line.insert("kind".into(), kind.into());
72 let mut text = serde_json::Value::Object(line).to_string();
73 if text.len() >= MAX_LINE_BYTES {
74 return Err(std::io::Error::other("an event is a few numbers"));
75 }
76 text.push('\n');
77 let _guard = WRITE.lock().unwrap_or_else(|e| e.into_inner());
78 std::fs::create_dir_all(dir)?;
79 let mut file = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(file_name(t_ms)))?;
80 file.write_all(text.as_bytes())
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use serde_json::json;
87
88 #[test]
89 fn the_month_is_the_utc_month_of_the_time() {
90 assert_eq!(file_name(0), "events-1970-01.jsonl");
91 assert_eq!(file_name(1_794_830_400_000), "events-2026-11.jsonl");
92 assert_eq!(file_name(951_782_400_000), "events-2000-02.jsonl");
94 assert_eq!(file_name(1_798_761_599_999), "events-2026-12.jsonl");
95 assert_eq!(file_name(1_798_761_600_000), "events-2027-01.jsonl");
96 }
97
98 #[test]
99 fn the_record_is_in_the_channels_folder_so_an_upgrade_keeps_it() {
100 let channel = PathBuf::from("home").join("channels").join("stable");
101 let version = channel.join("versions").join("0.60.35");
102 let paths = crate::data_paths::DataPaths {
103 home_dir: PathBuf::from("home"),
104 instance_dir: channel.clone(),
105 channel: "stable".to_string(),
106 data_dir: version.join("data"),
107 config_dir: channel.join("config"),
108 logs_dir: version.join("logs"),
109 cef_cache_dir: version.join("cef-cache"),
110 agents_dir: channel.join("agents"),
111 instance_runtime_dir: version.join("runtime"),
112 shared_dir: PathBuf::from("home").join("shared"),
113 mode: crate::RuntimeMode::Installed,
114 };
115 let dir = record_dir_in(&paths);
116 assert_eq!(dir, channel.join("record"));
117 assert!(!dir.starts_with(&version));
118 }
119
120 #[test]
121 fn only_an_events_file_is_one() {
122 assert_eq!(month_of_file("events-2026-11.jsonl"), Some("2026-11"));
123 for other in ["2026-11-16.jsonl", "rollup-2026-11.jsonl", "events-2026-1.jsonl", "events-26-11.jsonl", "events-2026-11.txt", "events-abcd-ef.jsonl"] {
124 assert_eq!(month_of_file(other), None, "{other}");
125 }
126 }
127
128 #[test]
129 fn an_event_is_one_line_with_its_time_and_kind() {
130 let tmp = tempfile::tempdir().unwrap();
131 let dir = tmp.path().join("record");
132 append_event(&dir, 1_794_830_400_000, "ui_stall", json!({ "ms": 55_000, "host_mb": 310 })).unwrap();
133 append_event(&dir, 1_794_830_460_000, "srv_stall", json!({ "ms": 5_300 })).unwrap();
134 let text = std::fs::read_to_string(dir.join("events-2026-11.jsonl")).unwrap();
135 let lines: Vec<serde_json::Value> = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
136 assert_eq!(lines[0], json!({ "t": 1_794_830_400_000u64, "kind": "ui_stall", "ms": 55_000, "host_mb": 310 }));
137 assert_eq!(lines[1]["kind"], "srv_stall");
138 assert!(append_event(&dir, 1, "x", json!([1])).is_err());
140 assert!(append_event(&dir, 1, "x", json!({ "text": "x".repeat(3_000) })).is_err());
141 assert_eq!(std::fs::read_to_string(dir.join("events-2026-11.jsonl")).unwrap().lines().count(), 2);
142 }
143}