agentmux_srv_core/backend/audit_activity/
store.rs1use std::io::Write;
8use std::path::{Path, PathBuf};
9use std::sync::mpsc::{channel, Sender};
10use std::sync::OnceLock;
11
12use super::{ActivityRow, KEEP_DAYS};
13
14static SINK: OnceLock<Sender<ActivityRow>> = OnceLock::new();
15
16const PREFIX: &str = "activity-";
17const SUFFIX: &str = ".jsonl";
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct DayFile {
22 pub day: String,
23 pub path: PathBuf,
24}
25
26pub(super) fn day_of(ms: u64) -> String {
28 chrono::DateTime::from_timestamp_millis(ms as i64).unwrap_or_default().format("%Y-%m-%d").to_string()
29}
30
31pub fn day_files(dir: &Path) -> Vec<DayFile> {
33 let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };
34 let mut files: Vec<DayFile> = read
35 .filter_map(Result::ok)
36 .filter_map(|e| {
37 let name = e.file_name().into_string().ok()?;
38 let day = name.strip_prefix(PREFIX)?.strip_suffix(SUFFIX)?.to_string();
39 chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok()?;
40 Some(DayFile { day, path: e.path() })
41 })
42 .collect();
43 files.sort_by(|a, b| b.day.cmp(&a.day));
44 files
45}
46
47fn file_in(dir: &Path, day: &str) -> PathBuf {
48 dir.join(format!("{PREFIX}{day}{SUFFIX}"))
49}
50
51pub(super) fn prune(dir: &Path, today: &str) -> usize {
53 let Ok(today) = chrono::NaiveDate::parse_from_str(today, "%Y-%m-%d") else { return 0 };
54 let mut gone = 0;
55 for file in day_files(dir) {
56 let Ok(day) = chrono::NaiveDate::parse_from_str(&file.day, "%Y-%m-%d") else { continue };
57 if (today - day).num_days() > KEEP_DAYS as i64 && std::fs::remove_file(&file.path).is_ok() {
58 gone += 1;
59 }
60 }
61 gone
62}
63
64pub fn install(dir: PathBuf, channel_name: String) -> std::io::Result<()> {
66 let (tx, _writer) = spawn_writer(dir, channel_name)?;
67 let _ = SINK.set(tx);
68 Ok(())
69}
70
71pub(super) fn spawn_writer(dir: PathBuf, channel_name: String) -> std::io::Result<(Sender<ActivityRow>, std::thread::JoinHandle<()>)> {
73 std::fs::create_dir_all(&dir)?;
74 let (tx, rx) = channel::<ActivityRow>();
75 let writer = std::thread::Builder::new().name("audit-activity-writer".into()).spawn(move || {
76 let mut open: Option<(String, std::fs::File)> = None;
77 for mut row in rx {
78 let day = day_of(row.ts);
80 if open.as_ref().is_none_or(|(d, _)| *d != day) {
81 let path = file_in(&dir, &day);
82 match std::fs::OpenOptions::new().create(true).append(true).open(&path) {
83 Ok(file) => open = Some((day.clone(), file)),
84 Err(e) => {
85 tracing::warn!(path = %path.display(), error = %e, "audit activity: could not open the day file");
86 continue;
87 }
88 }
89 prune(&dir, &day_of(agentmux_common::time::now_ms_u64()));
90 }
91 row.channel = Some(channel_name.clone());
92 let Ok(mut line) = serde_json::to_vec(&row) else { continue };
93 line.push(b'\n');
94 if let Some((_, file)) = open.as_mut() {
95 match file.write_all(&line).and_then(|_| file.flush()) {
97 Ok(()) => crate::backend::audit_live::poke(),
98 Err(e) => tracing::warn!(error = %e, "audit activity: could not append a row"),
99 }
100 }
101 }
102 })?;
103 Ok((tx, writer))
104}
105
106pub fn record(row: ActivityRow) {
108 if let Some(tx) = SINK.get() {
109 let _ = tx.send(row);
110 }
111}
112
113pub fn install_for_this_srv() {
115 let Some(dir) = crate::backend::reactive::audit_store::write_path().and_then(|p| p.parent().map(Path::to_path_buf)) else { return };
116 let channel_name = std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default();
117 if let Err(e) = install(dir.clone(), channel_name) {
118 tracing::warn!(dir = %dir.display(), error = %e, "audit activity: not kept");
119 }
120}