agentmux_srv_core/backend/
build_cache.rs1use std::collections::HashMap;
26use std::path::{Path, PathBuf};
27use std::time::{Duration, SystemTime};
28
29pub const KEY_ENABLED: &str = "buildcache:enabled";
31pub const KEY_ORPHANS: &str = "buildcache:orphans";
32pub const KEY_ORPHAN_KEEP: &str = "buildcache:orphan_keep";
33pub const KEY_ORPHAN_IDLE_HOURS: &str = "buildcache:orphan_idle_hours";
34pub const KEY_STALE_DAYS: &str = "buildcache:stale_days";
35pub const KEY_WARN_FREE_GB: &str = "buildcache:warn_free_gb";
36pub const KEY_WARN_FREE_PCT: &str = "buildcache:warn_free_pct";
37
38#[derive(Debug, Clone, PartialEq)]
40pub struct Policy {
41 pub enabled: bool,
43 pub orphans: bool,
45 pub orphan_keep: usize,
47 pub orphan_idle: Duration,
49 pub stale: Duration,
51 pub warn_free_bytes: u64,
53 pub warn_free_pct: f64,
55}
56
57impl Default for Policy {
58 fn default() -> Self {
59 Self {
60 enabled: true,
61 orphans: true,
62 orphan_keep: 3,
63 orphan_idle: Duration::from_secs(24 * 3600),
64 stale: Duration::from_secs(3 * 24 * 3600),
65 warn_free_bytes: 20 * (1 << 30),
66 warn_free_pct: 10.0,
67 }
68 }
69}
70
71impl Policy {
72 pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
74 let d = Self::default();
75 let num = |key: &str| extra.get(key).and_then(|v| v.as_f64()).filter(|n| n.is_finite() && *n >= 0.0);
76 Self {
77 enabled: extra.get(KEY_ENABLED).and_then(|v| v.as_bool()).unwrap_or(d.enabled),
78 orphans: extra.get(KEY_ORPHANS).and_then(|v| v.as_bool()).unwrap_or(d.orphans),
79 orphan_keep: num(KEY_ORPHAN_KEEP).map_or(d.orphan_keep, |n| (n as usize).max(1)),
81 orphan_idle: num(KEY_ORPHAN_IDLE_HOURS).and_then(|h| Duration::try_from_secs_f64(h * 3600.0).ok()).unwrap_or(d.orphan_idle),
82 stale: num(KEY_STALE_DAYS).and_then(|days| Duration::try_from_secs_f64(days * 86_400.0).ok()).unwrap_or(d.stale),
83 warn_free_bytes: num(KEY_WARN_FREE_GB).map_or(d.warn_free_bytes, |g| (g * (1u64 << 30) as f64) as u64),
84 warn_free_pct: num(KEY_WARN_FREE_PCT).unwrap_or(d.warn_free_pct),
85 }
86 }
87
88 pub fn is_low(&self, free: u64, total: u64) -> bool {
90 total > 0 && (free < self.warn_free_bytes || (free as f64) * 100.0 < self.warn_free_pct * total as f64)
91 }
92}
93
94pub fn clones_in(workspace: &Path) -> Vec<PathBuf> {
97 let is_clone = |p: &Path| p.join("Cargo.toml").is_file() && p.join("target").is_dir();
98 let mut out = Vec::new();
99 if is_clone(workspace) {
100 out.push(workspace.to_path_buf());
101 }
102 if let Ok(entries) = std::fs::read_dir(workspace) {
103 for e in entries.flatten() {
104 let p = e.path();
105 let name = e.file_name();
106 let name = name.to_string_lossy();
107 if name.starts_with('.') || name == "node_modules" || name == "target" {
108 continue;
109 }
110 if e.file_type().is_ok_and(|t| t.is_dir()) && is_clone(&p) {
111 out.push(p);
112 }
113 }
114 }
115 out.sort();
116 out
117}
118
119pub fn incremental_roots(target: &Path) -> Vec<PathBuf> {
122 let mut out = Vec::new();
123 let subdirs = |p: &Path| -> Vec<PathBuf> {
124 std::fs::read_dir(p)
125 .into_iter()
126 .flatten()
127 .flatten()
128 .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
129 .map(|e| e.path())
130 .collect()
131 };
132 for a in subdirs(target) {
133 if a.join("incremental").is_dir() {
134 out.push(a.join("incremental"));
135 }
136 for b in subdirs(&a) {
137 if b.join("incremental").is_dir() {
138 out.push(b.join("incremental"));
139 }
140 }
141 }
142 out.sort();
143 out
144}
145
146fn mtime(p: &Path) -> Option<SystemTime> {
147 std::fs::metadata(p).and_then(|m| m.modified()).ok()
148}
149
150fn activity(dir: &Path) -> SystemTime {
153 let mut newest = mtime(dir).unwrap_or(SystemTime::UNIX_EPOCH);
154 let mut bump = |t: Option<SystemTime>| {
155 if let Some(t) = t {
156 newest = newest.max(t);
157 }
158 };
159 for sess in std::fs::read_dir(dir).into_iter().flatten().flatten() {
160 bump(sess.metadata().and_then(|m| m.modified()).ok());
161 if sess.file_type().is_ok_and(|t| t.is_dir()) {
162 for f in std::fs::read_dir(sess.path()).into_iter().flatten().flatten() {
163 bump(f.metadata().and_then(|m| m.modified()).ok());
164 }
165 }
166 }
167 newest
168}
169
170pub fn dir_size(p: &Path) -> u64 {
172 let mut total = 0u64;
173 let mut stack = vec![p.to_path_buf()];
174 while let Some(d) = stack.pop() {
175 let Ok(entries) = std::fs::read_dir(&d) else { continue };
176 for e in entries.flatten() {
177 match e.file_type() {
178 Ok(t) if t.is_dir() => stack.push(e.path()),
179 Ok(_) => total += e.metadata().map_or(0, |m| m.len()),
180 Err(_) => {}
181 }
182 }
183 }
184 total
185}
186
187fn crate_of(name: &str) -> &str {
190 name.rsplit_once('-').map_or(name, |(c, _)| c)
191}
192
193pub fn orphans_in(root: &Path, keep: usize, idle: Duration, now: SystemTime) -> Vec<PathBuf> {
196 let mut by_crate: HashMap<String, Vec<(SystemTime, PathBuf)>> = HashMap::new();
197 for e in std::fs::read_dir(root).into_iter().flatten().flatten() {
198 if !e.file_type().is_ok_and(|t| t.is_dir()) {
199 continue;
200 }
201 let name = e.file_name().to_string_lossy().into_owned();
202 by_crate.entry(crate_of(&name).to_string()).or_default().push((activity(&e.path()), e.path()));
203 }
204 let mut out = Vec::new();
205 for (_, mut dirs) in by_crate {
206 dirs.sort_by(|a, b| b.0.cmp(&a.0));
207 out.extend(
208 dirs.into_iter()
209 .skip(keep.max(1))
210 .filter(|(at, _)| now.duration_since(*at).unwrap_or_default() >= idle)
211 .map(|(_, p)| p),
212 );
213 }
214 out.sort();
215 out
216}
217
218pub fn last_build(target: &Path) -> SystemTime {
221 let mut newest = mtime(target).unwrap_or(SystemTime::UNIX_EPOCH);
222 let subdirs = |p: &Path| -> Vec<PathBuf> {
223 std::fs::read_dir(p)
224 .into_iter()
225 .flatten()
226 .flatten()
227 .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
228 .map(|e| e.path())
229 .collect()
230 };
231 let mut look = |p: &Path| {
232 for p in [p.to_path_buf(), p.join(".fingerprint"), p.join("deps"), p.join("incremental")] {
233 if let Some(t) = mtime(&p) {
234 newest = newest.max(t);
235 }
236 }
237 };
238 for a in subdirs(target) {
240 look(&a);
241 for b in subdirs(&a) {
242 look(&b);
243 }
244 }
245 newest
246}
247
248pub fn build_running_in(clone: &Path, procs: &sysinfo::System) -> bool {
252 let needle = normal(clone);
253 procs.processes().values().any(|p| {
254 let name = p.name().to_string_lossy().to_ascii_lowercase();
255 let stem = name.strip_suffix(".exe").unwrap_or(&name);
256 let tool = matches!(stem, "cargo" | "rustc" | "link" | "lld-link" | "ld" | "cc" | "cl" | "clang" | "gcc" | "cmake" | "ninja" | "clippy-driver" | "rustdoc");
257 let in_clone = p.cwd().is_some_and(|c| normal(c).starts_with(&needle))
258 || p.exe().is_some_and(|e| normal(e).starts_with(&needle))
259 || p.cmd().iter().any(|a| normal(Path::new(a)).contains(&needle));
260 in_clone && (tool || p.exe().is_some_and(|e| normal(e).starts_with(&needle)))
261 })
262}
263
264fn normal(p: &Path) -> String {
265 let s = p.to_string_lossy().replace('\\', "/").to_ascii_lowercase();
266 s.strip_prefix("//?/").map_or_else(|| s.clone(), str::to_string)
268}
269
270pub fn snapshot_processes() -> sysinfo::System {
272 let mut sys = sysinfo::System::new();
273 sys.refresh_processes_specifics(
274 sysinfo::ProcessesToUpdate::All,
275 true,
276 sysinfo::ProcessRefreshKind::nothing()
277 .with_cwd(sysinfo::UpdateKind::Always)
278 .with_exe(sysinfo::UpdateKind::Always)
279 .with_cmd(sysinfo::UpdateKind::Always),
280 );
281 sys
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum Why {
287 TaskDone,
289 Hourly,
291 LowDisk,
293 Asked,
295}
296
297impl Why {
298 fn as_str(self) -> &'static str {
299 match self {
300 Why::TaskDone => "task-done",
301 Why::Hourly => "hourly",
302 Why::LowDisk => "low-disk",
303 Why::Asked => "asked",
304 }
305 }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct Removed {
311 pub path: PathBuf,
312 pub bytes: u64,
313 pub what: &'static str,
314}
315
316#[derive(Debug, Default, Clone, PartialEq, Eq)]
318pub struct Report {
319 pub removed: Vec<Removed>,
320 pub busy: Vec<PathBuf>,
322}
323
324impl Report {
325 pub fn bytes(&self) -> u64 {
326 self.removed.iter().map(|r| r.bytes).sum()
327 }
328}
329
330pub fn log_path() -> Option<PathBuf> {
332 if let Some(p) = std::env::var_os("AGENTMUX_BUILD_CACHE_LOG").filter(|p| !p.is_empty()) {
333 return Some(PathBuf::from(p));
334 }
335 Some(dirs::home_dir()?.join(".agentmux").join("logs").join("build-cache-cleanup.log"))
336}
337
338fn log_removal(log: Option<&Path>, why: Why, workspace: &Path, r: &Removed) {
339 tracing::info!(why = why.as_str(), workspace = %workspace.display(), path = %r.path.display(), bytes = r.bytes, what = r.what, "build cache: removed");
340 let Some(log) = log else { return };
341 if let Some(dir) = log.parent() {
342 let _ = std::fs::create_dir_all(dir);
343 }
344 use std::io::Write;
345 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(log) {
346 let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
347 let _ = writeln!(f, "{now}\t{}\t{}\t{}\t{}\t{}", why.as_str(), workspace.display(), r.what, r.bytes, r.path.display());
348 }
349}
350
351fn remove(log: Option<&Path>, why: Why, workspace: &Path, path: PathBuf, what: &'static str, report: &mut Report) {
352 let bytes = dir_size(&path);
353 match std::fs::remove_dir_all(&path) {
354 Ok(()) => {
355 let r = Removed { path, bytes, what };
356 log_removal(log, why, workspace, &r);
357 report.removed.push(r);
358 }
359 Err(e) => tracing::warn!(path = %path.display(), error = %e, "build cache: could not remove"),
360 }
361}
362
363pub fn run_pass(workspace: &Path, why: Why, policy: &Policy, is_busy: &dyn Fn(&Path) -> bool, now: SystemTime, log: Option<&Path>) -> Report {
370 let mut report = Report::default();
371 if !policy.enabled {
372 return report;
373 }
374 for clone in clones_in(workspace) {
375 if is_busy(&clone) {
376 report.busy.push(clone);
377 continue;
378 }
379 let target = clone.join("target");
380 let stale_applies = matches!(why, Why::TaskDone | Why::LowDisk | Why::Asked);
381 let mut todo: Vec<(PathBuf, &'static str)> = Vec::new();
385 if stale_applies && !policy.stale.is_zero() && now.duration_since(last_build(&target)).unwrap_or_default() >= policy.stale {
386 todo.push((target, "stale target"));
387 } else {
388 for root in incremental_roots(&target) {
389 if why == Why::TaskDone {
390 for e in std::fs::read_dir(&root).into_iter().flatten().flatten() {
391 if e.file_type().is_ok_and(|t| t.is_dir()) {
392 todo.push((e.path(), "incremental"));
393 }
394 }
395 } else if policy.orphans {
396 todo.extend(orphans_in(&root, policy.orphan_keep, policy.orphan_idle, now).into_iter().map(|d| (d, "orphan incremental")));
397 }
398 }
399 }
400 for (path, what) in todo {
401 if is_busy(&clone) {
402 report.busy.push(clone);
403 break;
404 }
405 remove(log, why, workspace, path, what, &mut report);
406 }
407 }
408 report
409}
410
411pub fn disk_of(path: &Path) -> Option<(u64, u64)> {
413 let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
414 let want = normal(&path);
415 let disks = sysinfo::Disks::new_with_refreshed_list();
416 disks
417 .list()
418 .iter()
419 .filter(|d| want.starts_with(&normal(d.mount_point())))
420 .max_by_key(|d| d.mount_point().as_os_str().len())
421 .map(|d| (d.available_space(), d.total_space()))
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
426pub struct TargetSize {
427 pub clone: PathBuf,
428 pub target_bytes: u64,
429 pub incremental_bytes: u64,
430}
431
432pub fn target_sizes(workspace: &Path) -> Vec<TargetSize> {
434 let mut out: Vec<TargetSize> = clones_in(workspace)
435 .into_iter()
436 .map(|clone| {
437 let target = clone.join("target");
438 let incremental_bytes = incremental_roots(&target).iter().map(|r| dir_size(r)).sum();
439 TargetSize { target_bytes: dir_size(&target), incremental_bytes, clone }
440 })
441 .collect();
442 out.sort_by(|a, b| b.target_bytes.cmp(&a.target_bytes));
443 out
444}
445
446pub fn human(bytes: u64) -> String {
448 const GB: f64 = (1u64 << 30) as f64;
449 let b = bytes as f64;
450 if b >= 100.0 * GB {
451 format!("{:.0} GB", b / GB)
452 } else if b >= GB {
453 format!("{:.1} GB", b / GB)
454 } else {
455 format!("{:.0} MB", b / (1u64 << 20) as f64)
456 }
457}
458
459#[cfg(test)]
460#[path = "build_cache_tests.rs"]
461mod tests;