| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::{ |
| 9 | path::{Path, PathBuf}, |
| 10 | sync::{Arc, Mutex}, |
| 11 | time::{Duration, Instant}, |
| 12 | }; |
| 13 | |
| 14 | use crate::application::port::{DiskError, DiskReport, DiskUsage}; |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | const FRESH_FOR: Duration = Duration::from_secs(60); |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | #[derive(Debug, Clone)] |
| 30 | pub struct WalkingDiskUsage { |
| 31 | data_dir: PathBuf, |
| 32 | cached: Arc<Mutex<Option<(Instant, DiskReport)>>>, |
| 33 | } |
| 34 | |
| 35 | impl WalkingDiskUsage { |
| 36 | #[must_use] |
| 37 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 38 | Self { |
| 39 | data_dir: data_dir.into(), |
| 40 | cached: Arc::new(Mutex::new(None)), |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl DiskUsage for WalkingDiskUsage { |
| 46 | async fn measure(&self) -> Result<DiskReport, DiskError> { |
| 47 | if let Some((taken, report)) = *self.cached.lock().expect("lock poisoned") |
| 48 | && taken.elapsed() < FRESH_FOR |
| 49 | { |
| 50 | return Ok(report); |
| 51 | } |
| 52 | |
| 53 | let data_dir = self.data_dir.clone(); |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | let report = tokio::task::spawn_blocking(move || measure(&data_dir)) |
| 59 | .await |
| 60 | .map_err(DiskError::new)??; |
| 61 | |
| 62 | *self.cached.lock().expect("lock poisoned") = Some((Instant::now(), report)); |
| 63 | |
| 64 | Ok(report) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | |
| 69 | fn measure(data_dir: &Path) -> Result<DiskReport, DiskError> { |
| 70 | |
| 71 | |
| 72 | |
| 73 | let stat = rustix::fs::statvfs(data_dir).map_err(|error| { |
| 74 | DiskError::new(format!( |
| 75 | "{} could not be stat'd: {error}", |
| 76 | data_dir.display() |
| 77 | )) |
| 78 | })?; |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | let block = stat.f_frsize; |
| 86 | |
| 87 | Ok(DiskReport { |
| 88 | data_dir_bytes: walk(data_dir), |
| 89 | filesystem_total_bytes: stat.f_blocks.saturating_mul(block), |
| 90 | filesystem_free_bytes: stat.f_bavail.saturating_mul(block), |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | fn walk(dir: &Path) -> u64 { |
| 109 | let mut total = 0; |
| 110 | let mut pending = vec![dir.to_path_buf()]; |
| 111 | |
| 112 | while let Some(path) = pending.pop() { |
| 113 | let Ok(entries) = std::fs::read_dir(&path) else { |
| 114 | continue; |
| 115 | }; |
| 116 | |
| 117 | for entry in entries.flatten() { |
| 118 | |
| 119 | |
| 120 | |
| 121 | let Ok(metadata) = entry.metadata() else { |
| 122 | continue; |
| 123 | }; |
| 124 | |
| 125 | if metadata.is_dir() { |
| 126 | pending.push(entry.path()); |
| 127 | } else { |
| 128 | total += metadata.len(); |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | total |
| 134 | } |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | #[derive(Debug, Clone)] |
| 141 | pub struct InMemoryDiskUsage(Option<DiskReport>); |
| 142 | |
| 143 | impl InMemoryDiskUsage { |
| 144 | #[must_use] |
| 145 | pub fn new(report: DiskReport) -> Self { |
| 146 | Self(Some(report)) |
| 147 | } |
| 148 | |
| 149 | |
| 150 | #[must_use] |
| 151 | pub fn unmeasurable() -> Self { |
| 152 | Self(None) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | impl DiskUsage for InMemoryDiskUsage { |
| 157 | async fn measure(&self) -> Result<DiskReport, DiskError> { |
| 158 | self.0.ok_or_else(|| DiskError::new("no disk here")) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[cfg(test)] |
| 163 | mod tests { |
| 164 | use super::*; |
| 165 | |
| 166 | #[test] |
| 167 | fn a_walk_counts_every_file_at_every_depth() { |
| 168 | let root = tempfile::tempdir().expect("tempdir"); |
| 169 | let repo = root.path().join("james/steid.git/refs/heads"); |
| 170 | std::fs::create_dir_all(&repo).expect("mkdir"); |
| 171 | std::fs::write(repo.join("main"), b"abc123\n").expect("write"); |
| 172 | std::fs::write( |
| 173 | root.path().join("james/steid.git/HEAD"), |
| 174 | b"ref: refs/heads/main\n", |
| 175 | ) |
| 176 | .expect("write"); |
| 177 | |
| 178 | std::fs::create_dir_all(root.path().join("james/empty.git")).expect("mkdir"); |
| 179 | |
| 180 | assert_eq!(walk(root.path()), 7 + 21); |
| 181 | } |
| 182 | |
| 183 | #[test] |
| 184 | fn a_walk_of_a_directory_that_is_not_there_is_zero_rather_than_an_error() { |
| 185 | |
| 186 | |
| 187 | assert_eq!(walk(Path::new("/nowhere-at-all-steid")), 0); |
| 188 | } |
| 189 | |
| 190 | #[test] |
| 191 | fn a_symlink_is_counted_as_a_link_and_never_followed() { |
| 192 | let root = tempfile::tempdir().expect("tempdir"); |
| 193 | let outside = root.path().join("outside"); |
| 194 | std::fs::create_dir_all(&outside).expect("mkdir"); |
| 195 | std::fs::write(outside.join("big"), vec![0u8; 4096]).expect("write"); |
| 196 | |
| 197 | let data = root.path().join("data"); |
| 198 | std::fs::create_dir_all(&data).expect("mkdir"); |
| 199 | std::os::unix::fs::symlink(&outside, data.join("link")).expect("symlink"); |
| 200 | |
| 201 | assert!( |
| 202 | walk(&data) < 4096, |
| 203 | "the walk followed a symlink out of the data directory" |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | #[tokio::test] |
| 208 | async fn the_filesystem_numbers_are_real_and_consistent() { |
| 209 | |
| 210 | |
| 211 | |
| 212 | let root = tempfile::tempdir().expect("tempdir"); |
| 213 | std::fs::write(root.path().join("one"), vec![7u8; 1024]).expect("write"); |
| 214 | |
| 215 | let report = WalkingDiskUsage::new(root.path()) |
| 216 | .measure() |
| 217 | .await |
| 218 | .expect("the disk can be measured"); |
| 219 | |
| 220 | assert_eq!(report.data_dir_bytes, 1024); |
| 221 | assert!(report.filesystem_total_bytes > 0); |
| 222 | assert!(report.filesystem_free_bytes <= report.filesystem_total_bytes); |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | #[ignore = "a benchmark, not a test: run with --ignored and STEID_WALK_BENCH=<dir>"] |
| 227 | fn how_long_the_walk_takes() { |
| 228 | let Ok(dir) = std::env::var("STEID_WALK_BENCH") else { |
| 229 | return; |
| 230 | }; |
| 231 | |
| 232 | let started = Instant::now(); |
| 233 | let bytes = walk(Path::new(&dir)); |
| 234 | println!("walked {dir}: {bytes} bytes in {:?}", started.elapsed()); |
| 235 | } |
| 236 | |
| 237 | #[tokio::test] |
| 238 | async fn a_measurement_is_reused_for_a_minute() { |
| 239 | |
| 240 | |
| 241 | |
| 242 | let root = tempfile::tempdir().expect("tempdir"); |
| 243 | let usage = WalkingDiskUsage::new(root.path()); |
| 244 | |
| 245 | let first = usage.measure().await.expect("measured"); |
| 246 | assert_eq!(first.data_dir_bytes, 0); |
| 247 | |
| 248 | std::fs::write(root.path().join("new"), vec![0u8; 2048]).expect("write"); |
| 249 | |
| 250 | assert_eq!( |
| 251 | usage.measure().await.expect("measured").data_dir_bytes, |
| 252 | 0, |
| 253 | "the walk ran again inside the cache window" |
| 254 | ); |
| 255 | } |
| 256 | } |