stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
//! Installation schedules: interval arithmetic for periods.
//!
//! A schedule is an interval `i` of 0 (manual only) or 300 to 604 800
//! seconds. The anchor is the activation time rounded down to a multiple of
//! `i`, in seconds since the Unix epoch. Period `n` covers
//! `[anchor + n·i, anchor + (n+1)·i)`, and its job becomes eligible when it
//! ends. When several ended periods have no job, only the latest runs and
//! the others are recorded `skipped`, so a controller that was down does not
//! cause a burst.
//!
//! Nothing here reads a clock: the controller owns it and passes `now`.

use std::ops::Range;

use crate::id::UnixTime;

/// The shortest interval a scheduled installation may have, in seconds.
pub const MIN_SCHEDULE_SECS: u64 = 300;

/// The longest interval, in seconds: one week.
pub const MAX_SCHEDULE_SECS: u64 = 604_800;

/// An installation's schedule.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{Schedule, UnixTime};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Activated at 1000 s with a 300 s interval: the anchor is 900.
/// let s = Schedule::new(300, UnixTime::from_secs(1_000))?;
/// assert_eq!(s.anchor().map(UnixTime::as_secs), Some(900));
/// assert_eq!(
///     s.period_bounds(0).map(|(a, b)| (a.as_secs(), b.as_secs())),
///     Some((900, 1_200)),
/// );
/// assert_eq!(s.latest_ended(UnixTime::from_secs(1_199)), None);
/// assert_eq!(s.latest_ended(UnixTime::from_secs(1_200)), Some(0));
/// assert_eq!(s.latest_ended(UnixTime::from_secs(2_100)), Some(3));
///
/// // Nothing ran yet: run period 3, skip 0..3.
/// let due = s.ended_periods(None, UnixTime::from_secs(2_100)).ok_or("due")?;
/// assert_eq!((due.run, due.skip), (3, 0..3));
///
/// // Manual only: no period ever ends by itself.
/// let manual = Schedule::new(0, UnixTime::from_secs(1_000))?;
/// assert!(manual.is_manual());
/// assert_eq!(manual.latest_ended(UnixTime::from_secs(u64::MAX)), None);
/// assert!(Schedule::new(299, UnixTime::from_secs(0)).is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Schedule {
    /// The interval and the anchor; `None` for a manual-only schedule.
    interval: Option<(u64, u64)>,
}

impl Schedule {
    /// Builds the schedule of an installation activated at `activated_at`.
    ///
    /// # Errors
    ///
    /// [`ScheduleError`] when `schedule_secs` is neither 0 nor in
    /// `300..=604800`.
    pub fn new(schedule_secs: u64, activated_at: UnixTime) -> Result<Self, ScheduleError> {
        check_schedule_secs(schedule_secs)?;
        if schedule_secs == 0 {
            return Ok(Self { interval: None });
        }
        let at = activated_at.as_secs();
        let anchor = at - at % schedule_secs;
        Ok(Self {
            interval: Some((schedule_secs, anchor)),
        })
    }

    /// Returns `true` for a manual-only schedule (`schedule_secs` 0).
    pub fn is_manual(&self) -> bool {
        self.interval.is_none()
    }

    /// Returns the interval in seconds, or `None` when manual.
    pub fn interval_secs(&self) -> Option<u64> {
        self.interval.map(|(i, _)| i)
    }

    /// Returns the anchor, or `None` when manual.
    pub fn anchor(&self) -> Option<UnixTime> {
        self.interval.map(|(_, a)| UnixTime::from_secs(a))
    }

    /// Returns the start and end of period `n`, `[start, end)`, or `None`
    /// when manual or when the end would not fit in a `u64`.
    pub fn period_bounds(&self, n: u64) -> Option<(UnixTime, UnixTime)> {
        let (i, anchor) = self.interval?;
        let start = n.checked_mul(i)?.checked_add(anchor)?;
        let end = start.checked_add(i)?;
        Some((UnixTime::from_secs(start), UnixTime::from_secs(end)))
    }

    /// Returns the latest period that has ended at `now`, or `None` when
    /// manual or when no period has ended yet.
    pub fn latest_ended(&self, now: UnixTime) -> Option<u64> {
        let (i, anchor) = self.interval?;
        let elapsed = now.as_secs().checked_sub(anchor)?;
        (elapsed / i).checked_sub(1)
    }

    /// Returns what the scheduler does at `now`, given the latest period
    /// that already has a job (`last_seen`, `None` if none has): the period
    /// to run and the earlier ended periods to record `skipped`. `None` when
    /// no period after `last_seen` has ended.
    pub fn ended_periods(&self, last_seen: Option<u64>, now: UnixTime) -> Option<EndedPeriods> {
        let latest = self.latest_ended(now)?;
        let first = match last_seen {
            Some(seen) => seen.checked_add(1)?,
            None => 0,
        };
        (latest >= first).then_some(EndedPeriods {
            run: latest,
            skip: first..latest,
        })
    }
}

/// The scheduler's work at one tick: one period to run, the others skipped.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EndedPeriods {
    /// The latest ended period: create its job.
    pub run: u64,
    /// The ended periods before it without a job: record them `skipped`.
    pub skip: Range<u64>,
}

/// Checks a `schedule_secs` value: 0, or `300..=604800`.
///
/// # Errors
///
/// [`ScheduleError`] for any other value.
///
/// # Examples
///
/// ```
/// use stratum_node_core::check_schedule_secs;
///
/// assert!(check_schedule_secs(0).is_ok());
/// assert!(check_schedule_secs(300).is_ok());
/// assert!(check_schedule_secs(604_801).is_err());
/// ```
pub fn check_schedule_secs(schedule_secs: u64) -> Result<(), ScheduleError> {
    if schedule_secs == 0 || (MIN_SCHEDULE_SECS..=MAX_SCHEDULE_SECS).contains(&schedule_secs) {
        Ok(())
    } else {
        Err(ScheduleError)
    }
}

/// `schedule_secs` is neither 0 nor between 300 and 604 800.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("schedule_secs must be 0 or between 300 and 604800")]
pub struct ScheduleError;