agentmux_srv_core/backend/
bundle_use.rs1use std::collections::BTreeMap;
13use std::io::Write;
14use std::path::Path;
15
16const FILE_NAME: &str = "bundle-transport-use.jsonl";
17
18pub fn note(op: &str) {
20 #[cfg(any(test, feature = "test-support"))]
22 let _ = op;
23 #[cfg(not(any(test, feature = "test-support")))]
24 if let Some(paths) = agentmux_common::DataPaths::from_env() {
25 if let Some(total) = note_at(&paths.instance_dir.join(FILE_NAME), op, agentmux_common::time::now_ms()) {
26 tracing::info!(op, total, "bundle transport used");
27 }
28 }
29}
30
31fn note_at(path: &Path, op: &str, at_ms: i64) -> Option<u64> {
33 let line = serde_json::json!({ "at_ms": at_ms, "op": op }).to_string();
34 let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?;
35 writeln!(file, "{line}").ok()?;
36 Some(counts(path).values().sum())
37}
38
39pub fn counts(path: &Path) -> BTreeMap<String, u64> {
41 let mut counts = BTreeMap::new();
42 let Ok(text) = std::fs::read_to_string(path) else { return counts };
43 for line in text.lines() {
44 if let Some(op) = serde_json::from_str::<serde_json::Value>(line).ok().and_then(|v| v.get("op")?.as_str().map(str::to_string)) {
45 *counts.entry(op).or_insert(0) += 1;
46 }
47 }
48 counts
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn counts_each_call_and_gives_the_running_total() {
57 let dir = tempfile::tempdir().unwrap();
58 let path = dir.path().join(FILE_NAME);
59 assert_eq!(note_at(&path, "export", 1), Some(1));
60 assert_eq!(note_at(&path, "import_commit", 2), Some(2));
61 assert_eq!(note_at(&path, "export", 3), Some(3));
62 let by_op = counts(&path);
63 assert_eq!(by_op.get("export"), Some(&2));
64 assert_eq!(by_op.get("import_commit"), Some(&1));
65 assert_eq!(counts(&dir.path().join("none.jsonl")).len(), 0);
66 }
67
68 #[test]
69 fn a_line_that_is_not_json_is_skipped() {
70 let dir = tempfile::tempdir().unwrap();
71 let path = dir.path().join(FILE_NAME);
72 std::fs::write(&path, "not json\n{\"at_ms\":1,\"op\":\"export\"}\n").unwrap();
73 assert_eq!(counts(&path).get("export"), Some(&1));
74 }
75
76 #[test]
77 fn an_unwritable_place_is_dropped() {
78 let dir = tempfile::tempdir().unwrap();
79 assert_eq!(note_at(&dir.path().join("no-such-dir").join(FILE_NAME), "export", 1), None);
80 }
81}