subc-control 0.46.0

Client-facing subc control-plane wire shapes.
Documentation
//! Data-volume status reported by the daemon and the shared low-space rule.

use serde::{Deserialize, Serialize};

const GIB: u64 = 1024 * 1024 * 1024;
const LOW_BYTES: u64 = 2 * GIB;
const RECOVER_BYTES: u64 = 5 * GIB / 2;
const LOW_RATIO_DIVISOR: u128 = 100; // 1%
const RECOVER_RATIO_DIVISOR: u128 = 80; // 1.25%

/// The last measurement of the volume holding the daemon's data directory.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiskStatus {
    /// The daemon's data directory, even if an ancestor had to be measured.
    pub path: String,
    /// Bytes available to the daemon's user, not including reserved space.
    pub available_bytes: u64,
    pub total_bytes: u64,
    /// The daemon's low-space state, including the margin for recovery.
    pub low: bool,
    /// Unix time in milliseconds when the measurement was taken.
    pub checked_at_ms: u64,
}

/// Enters low space below either limit and clears it only once both recovery
/// limits are met. Pass `false` for a standalone measurement without history.
pub fn is_low(available_bytes: u64, total_bytes: u64, was_low: bool) -> bool {
    // Compare ratios in bytes without rounding the limit down or overflowing
    // even on volumes whose size is close to the largest representable value.
    let (limit, divisor) = if was_low {
        (RECOVER_BYTES, RECOVER_RATIO_DIVISOR)
    } else {
        (LOW_BYTES, LOW_RATIO_DIVISOR)
    };
    available_bytes < limit || u128::from(available_bytes) * divisor < u128::from(total_bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn enters_below_either_limit_but_not_at_it() {
        assert!(is_low(2 * GIB - 1, 100 * GIB, false));
        assert!(!is_low(2 * GIB, 100 * GIB, false));
        assert!(is_low(4 * GIB - 1, 400 * GIB, false));
        assert!(!is_low(4 * GIB, 400 * GIB, false));
        assert!(is_low(4 * GIB, 400 * GIB + 1, false));
    }

    #[test]
    fn stays_low_until_both_recovery_limits_are_met() {
        let near_byte_limit = 5 * GIB / 2 - 1;
        assert!(!is_low(near_byte_limit, 100 * GIB, false));
        assert!(is_low(near_byte_limit, 100 * GIB, true));
        assert!(!is_low(near_byte_limit + 1, 100 * GIB, true));

        let near_ratio_limit = 5 * GIB - 1;
        assert!(!is_low(near_ratio_limit, 400 * GIB, false));
        assert!(is_low(near_ratio_limit, 400 * GIB, true));
        assert!(!is_low(near_ratio_limit + 1, 400 * GIB, true));
        assert!(is_low(near_ratio_limit + 1, 400 * GIB + 1, true));
    }

    #[test]
    fn ratio_comparison_handles_large_volumes() {
        assert!(!is_low(u64::MAX / 2, u64::MAX, true));
    }
}