Skip to main content

feldera_storage/
disk.rs

1//! Usage of the disk backing a storage path.
2
3use std::path::Path;
4use std::sync::Once;
5
6use tracing::warn;
7
8/// Disk usage, as `statvfs` reports it.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct DiskUsage {
11    /// Capacity of the disk, in bytes.
12    pub total_bytes: u64,
13
14    /// Bytes this process can still write.
15    pub available_bytes: u64,
16}
17
18impl DiskUsage {
19    /// Returns the usage of the disk that holds `path`, or `None` when it
20    /// cannot be read.
21    // `fsblkcnt_t` is 32 bits on macOS, 64 on Linux, so the widening is only
22    // redundant on some targets.
23    #[allow(clippy::useless_conversion)]
24    pub fn from_path(path: &Path) -> Option<Self> {
25        match nix::sys::statvfs::statvfs(path) {
26            Ok(stat) => {
27                // Counts are in units of `f_frsize`; `f_bsize` is only an I/O hint.
28                // statvfs(3): https://man7.org/linux/man-pages/man3/statvfs.3.html
29                let block_bytes = u64::from(stat.fragment_size());
30                let total_bytes = block_bytes.checked_mul(u64::from(stat.blocks()))?;
31                let available_bytes =
32                    block_bytes.checked_mul(u64::from(stat.blocks_available()))?;
33                // No capacity means the disk cannot report, not that it is full.
34                (total_bytes > 0).then_some(Self {
35                    total_bytes,
36                    available_bytes,
37                })
38            }
39            Err(errno) => {
40                static ONCE: Once = Once::new();
41                ONCE.call_once(|| {
42                    warn!(
43                        "Failed to read disk usage for {}, reporting it as unknown: {errno}",
44                        path.display()
45                    )
46                });
47                None
48            }
49        }
50    }
51}
52
53#[cfg(test)]
54mod test {
55    use std::path::Path;
56
57    use super::DiskUsage;
58
59    #[test]
60    fn reports_disk_usage_for_an_existing_directory() {
61        let temp_dir = std::env::temp_dir();
62        let usage = DiskUsage::from_path(&temp_dir)
63            .unwrap_or_else(|| panic!("a disk must hold {}", temp_dir.display()));
64        assert!(usage.total_bytes > 0, "{usage:?}");
65        assert!(usage.available_bytes <= usage.total_bytes, "{usage:?}");
66    }
67
68    #[test]
69    fn reports_no_disk_usage_for_a_missing_path() {
70        // Unknown, not an empty or full disk.
71        assert_eq!(
72            DiskUsage::from_path(Path::new("/nonexistent-feldera-storage-path")),
73            None
74        );
75    }
76}