steid

@jamesgill /

1//! How much disk the instance is using — the adapter behind
2//! [`DiskUsage`](crate::application::port::DiskUsage).
3//!
4//! Two numbers come from one `statvfs` and are free; the third is a walk of the data
5//! directory, which is not. A forge's data directory is thousands of small files — one
6//! bare repository is a few hundred on its own — and the walk is the reason this caches.
7
8use std::{
9 path::{Path, PathBuf},
10 sync::{Arc, Mutex},
11 time::{Duration, Instant},
12};
13
14use crate::application::port::{DiskError, DiskReport, DiskUsage};
15
16/// How long a measurement is reused before the directory is walked again.
17///
18/// A minute. The consumer is a console polling for a number somebody reads in gigabytes,
19/// and a number a minute stale is indistinguishable from a fresh one at that resolution —
20/// while an uncached walk on every poll would make an operator's monitoring the most
21/// expensive thing the instance does.
22const FRESH_FOR: Duration = Duration::from_secs(60);
23
24/// Walks the data directory, asks the filesystem for the rest, and remembers for a
25/// minute.
26///
27/// **One per process**, in app context, or the cache remembers nothing — the same
28/// composition-root decision `CatFilePool` and the highlight cache needed.
29#[derive(Debug, Clone)]
30pub struct WalkingDiskUsage {
31 data_dir: PathBuf,
32 cached: Arc<Mutex<Option<(Instant, DiskReport)>>>,
33}
34
35impl 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
45impl 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 // Blocking, for the reason the archive work is: a walk of a repository directory
56 // is thousands of `stat` calls, which is real work on a filesystem rather than a
57 // wait, and doing it on the runtime's threads would stall requests.
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/// The three numbers, measured now.
69fn measure(data_dir: &Path) -> Result<DiskReport, DiskError> {
70 // The filesystem first, and against the data directory itself: `/var/lib/steid/repos`
71 // is routinely its own volume, and asking about `/` would answer about the root disk
72 // instead of the one that fills up.
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 // `f_frsize`, the fragment size, is what POSIX says the block counts are in —
81 // `f_bsize` is the preferred I/O size and is not the same number on every
82 // filesystem. `f_bavail`, not `f_bfree`: the difference is the reserve kept for
83 // root, and Steid does not run as root, so `f_bfree` would promise space it cannot
84 // have.
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/// What everything under `dir` occupies, in bytes.
95///
96/// **Apparent size, not blocks used.** `len()` is what the files say they are; a
97/// sparse file or a filesystem with compression or tail-packing will disagree, and git
98/// objects are neither. It is the number that matches what a backup of the directory
99/// would weigh, which is the comparison somebody sizing a volume actually makes.
100///
101/// **Never follows a symlink and never fails.** A directory that cannot be read
102/// contributes nothing and the walk carries on: this is a number on a monitoring poll,
103/// and half an answer is more useful than an error — the alternative is an operator
104/// surface that goes blind because one directory had the wrong mode.
105///
106/// Iterative rather than recursive, so a pathological tree cannot overflow the stack of
107/// a thread that is only counting bytes.
108fn 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 // `DirEntry::metadata` does not traverse a symlink, unlike `fs::metadata`:
119 // a link is counted as the link it is. Following one would count something
120 // outside the data directory, or count the same tree twice.
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/// The in-memory [`DiskUsage`], for use-case tests.
137///
138/// Touches no disk and answers whatever it was built with, so a test can pin what
139/// `/api/instance` says about a full volume without filling one.
140#[derive(Debug, Clone)]
141pub struct InMemoryDiskUsage(Option<DiskReport>);
142
143impl InMemoryDiskUsage {
144 #[must_use]
145 pub fn new(report: DiskReport) -> Self {
146 Self(Some(report))
147 }
148
149 /// One that cannot measure anything, which is the case a report has to survive.
150 #[must_use]
151 pub fn unmeasurable() -> Self {
152 Self(None)
153 }
154}
155
156impl 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)]
163mod 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 // An empty directory contributes nothing but must not stop the walk.
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 // A fresh instance has not created its data directory yet, and an operator poll
186 // must answer rather than fail because of it.
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 // Nothing can be asserted about the size of the disk a test runs on, so what is
210 // pinned is the relationship: free is part of total, and the data directory is
211 // what it was written to be.
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 // The cache is the whole reason the walk is affordable on a poll, so what is
240 // pinned is that a second call does not walk again — a file written in between
241 // must not show up.
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}