Skip to main content

subc_control/
disk.rs

1//! Data-volume status reported by the daemon and the shared low-space rule.
2
3use serde::{Deserialize, Serialize};
4
5const GIB: u64 = 1024 * 1024 * 1024;
6const LOW_BYTES: u64 = 2 * GIB;
7const RECOVER_BYTES: u64 = 5 * GIB / 2;
8const LOW_RATIO_DIVISOR: u128 = 100; // 1%
9const RECOVER_RATIO_DIVISOR: u128 = 80; // 1.25%
10
11/// The last measurement of the volume holding the daemon's data directory.
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13pub struct DiskStatus {
14    /// The daemon's data directory, even if an ancestor had to be measured.
15    pub path: String,
16    /// Bytes available to the daemon's user, not including reserved space.
17    pub available_bytes: u64,
18    pub total_bytes: u64,
19    /// The daemon's low-space state, including the margin for recovery.
20    pub low: bool,
21    /// Unix time in milliseconds when the measurement was taken.
22    pub checked_at_ms: u64,
23}
24
25/// Enters low space below either limit and clears it only once both recovery
26/// limits are met. Pass `false` for a standalone measurement without history.
27pub fn is_low(available_bytes: u64, total_bytes: u64, was_low: bool) -> bool {
28    // Compare ratios in bytes without rounding the limit down or overflowing
29    // even on volumes whose size is close to the largest representable value.
30    let (limit, divisor) = if was_low {
31        (RECOVER_BYTES, RECOVER_RATIO_DIVISOR)
32    } else {
33        (LOW_BYTES, LOW_RATIO_DIVISOR)
34    };
35    available_bytes < limit || u128::from(available_bytes) * divisor < u128::from(total_bytes)
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn enters_below_either_limit_but_not_at_it() {
44        assert!(is_low(2 * GIB - 1, 100 * GIB, false));
45        assert!(!is_low(2 * GIB, 100 * GIB, false));
46        assert!(is_low(4 * GIB - 1, 400 * GIB, false));
47        assert!(!is_low(4 * GIB, 400 * GIB, false));
48        assert!(is_low(4 * GIB, 400 * GIB + 1, false));
49    }
50
51    #[test]
52    fn stays_low_until_both_recovery_limits_are_met() {
53        let near_byte_limit = 5 * GIB / 2 - 1;
54        assert!(!is_low(near_byte_limit, 100 * GIB, false));
55        assert!(is_low(near_byte_limit, 100 * GIB, true));
56        assert!(!is_low(near_byte_limit + 1, 100 * GIB, true));
57
58        let near_ratio_limit = 5 * GIB - 1;
59        assert!(!is_low(near_ratio_limit, 400 * GIB, false));
60        assert!(is_low(near_ratio_limit, 400 * GIB, true));
61        assert!(!is_low(near_ratio_limit + 1, 400 * GIB, true));
62        assert!(is_low(near_ratio_limit + 1, 400 * GIB + 1, true));
63    }
64
65    #[test]
66    fn ratio_comparison_handles_large_volumes() {
67        assert!(!is_low(u64::MAX / 2, u64::MAX, true));
68    }
69}