zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! A cancellable wall-clock budget shared by the probes.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

#[derive(Clone, Debug)]
pub struct Budget {
    deadline: Instant,
    cancel: Arc<AtomicBool>,
}

impl Budget {
    pub fn new(total: Duration, cancel: Arc<AtomicBool>) -> Self {
        Budget {
            deadline: Instant::now() + total,
            cancel,
        }
    }

    /// A child budget that gets `frac` of the time left, sharing the cancel flag.
    pub fn slice(&self, frac: f64) -> Budget {
        let remaining = self.deadline.saturating_duration_since(Instant::now());
        let frac = if frac.is_finite() {
            frac.clamp(0.0, 1.0)
        } else {
            0.0
        };
        Budget {
            deadline: Instant::now() + remaining.mul_f64(frac),
            cancel: self.cancel.clone(),
        }
    }

    /// True once the deadline has passed or the budget was cancelled.
    pub fn expired(&self) -> bool {
        self.cancelled() || Instant::now() >= self.deadline
    }

    pub fn cancelled(&self) -> bool {
        self.cancel.load(Ordering::SeqCst)
    }

    /// The shared cancel flag, for building a sibling budget.
    pub(crate) fn cancel_flag(&self) -> Arc<AtomicBool> {
        self.cancel.clone()
    }

    pub(crate) fn remaining(&self) -> Duration {
        self.deadline.saturating_duration_since(Instant::now())
    }
}

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

    #[test]
    fn a_cancelled_budget_reads_expired() {
        let c = Arc::new(AtomicBool::new(false));
        let b = Budget::new(Duration::from_secs(60), c.clone());
        assert!(!b.expired());
        c.store(true, Ordering::SeqCst);
        assert!(b.expired() && b.cancelled());
    }

    #[test]
    fn a_slice_never_outlives_its_parent() {
        let b = Budget::new(Duration::from_millis(10), Arc::new(AtomicBool::new(false)));
        std::thread::sleep(Duration::from_millis(15));
        assert!(b.slice(0.5).expired());
    }
}