forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli2 hours ago363 commits

disk.rs51 lines, 1.5 KiBHistoryRawDownload
1use std::collections::HashSet;
2use std::fs;
3use std::os::unix::fs::MetadataExt;
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::time::{Duration, Instant};
8
9use tokio_util::sync::CancellationToken;
10
11const INTERVAL: Duration = Duration::from_secs(2);
12
13pub fn usage(roots: &[PathBuf]) -> u64 {
14 let mut seen = HashSet::new();
15 let mut total = 0u64;
16 let mut stack: Vec<PathBuf> = roots.to_vec();
17 while let Some(path) = stack.pop() {
18 let Ok(meta) = fs::symlink_metadata(&path) else {
19 continue;
20 };
21 if meta.nlink() > 1 && !meta.is_dir() && !seen.insert((meta.dev(), meta.ino())) {
22 continue;
23 }
24 total = total.saturating_add(meta.blocks().saturating_mul(512));
25 if meta.is_dir()
26 && let Ok(entries) = fs::read_dir(&path)
27 {
28 stack.extend(entries.flatten().map(|entry| entry.path()));
29 }
30 }
31 total
32}
33
34pub async fn watch(roots: Vec<PathBuf>, cap: u64, job: CancellationToken, over: Arc<AtomicBool>) {
35 let roots = Arc::new(roots);
36 let mut pause = INTERVAL;
37 loop {
38 tokio::time::sleep(pause).await;
39 let measured = Arc::clone(&roots);
40 let started = Instant::now();
41 let Ok(used) = tokio::task::spawn_blocking(move || usage(&measured)).await else {
42 return;
43 };
44 pause = INTERVAL.max(started.elapsed() * 4);
45 if used > cap {
46 over.store(true, Ordering::SeqCst);
47 job.cancel();
48 return;
49 }
50 }
51}