use std::collections::HashSet; use std::fs; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; const INTERVAL: Duration = Duration::from_secs(2); pub fn usage(roots: &[PathBuf]) -> u64 { let mut seen = HashSet::new(); let mut total = 0u64; let mut stack: Vec = roots.to_vec(); while let Some(path) = stack.pop() { let Ok(meta) = fs::symlink_metadata(&path) else { continue; }; if meta.nlink() > 1 && !meta.is_dir() && !seen.insert((meta.dev(), meta.ino())) { continue; } total = total.saturating_add(meta.blocks().saturating_mul(512)); if meta.is_dir() && let Ok(entries) = fs::read_dir(&path) { stack.extend(entries.flatten().map(|entry| entry.path())); } } total } pub async fn watch(roots: Vec, cap: u64, job: CancellationToken, over: Arc) { let roots = Arc::new(roots); let mut pause = INTERVAL; loop { tokio::time::sleep(pause).await; let measured = Arc::clone(&roots); let started = Instant::now(); let Ok(used) = tokio::task::spawn_blocking(move || usage(&measured)).await else { return; }; pause = INTERVAL.max(started.elapsed() * 4); if used > cap { over.store(true, Ordering::SeqCst); job.cancel(); return; } } }