Skip to main content

stratum_node_core/
schedule.rs

1//! Installation schedules: interval arithmetic for periods.
2//!
3//! A schedule is an interval `i` of 0 (manual only) or 300 to 604 800
4//! seconds. The anchor is the activation time rounded down to a multiple of
5//! `i`, in seconds since the Unix epoch. Period `n` covers
6//! `[anchor + n·i, anchor + (n+1)·i)`, and its job becomes eligible when it
7//! ends. When several ended periods have no job, only the latest runs and
8//! the others are recorded `skipped`, so a controller that was down does not
9//! cause a burst.
10//!
11//! Nothing here reads a clock: the controller owns it and passes `now`.
12
13use std::ops::Range;
14
15use crate::id::UnixTime;
16
17/// The shortest interval a scheduled installation may have, in seconds.
18pub const MIN_SCHEDULE_SECS: u64 = 300;
19
20/// The longest interval, in seconds: one week.
21pub const MAX_SCHEDULE_SECS: u64 = 604_800;
22
23/// An installation's schedule.
24///
25/// # Examples
26///
27/// ```
28/// use stratum_node_core::{Schedule, UnixTime};
29///
30/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
31/// // Activated at 1000 s with a 300 s interval: the anchor is 900.
32/// let s = Schedule::new(300, UnixTime::from_secs(1_000))?;
33/// assert_eq!(s.anchor().map(UnixTime::as_secs), Some(900));
34/// assert_eq!(
35///     s.period_bounds(0).map(|(a, b)| (a.as_secs(), b.as_secs())),
36///     Some((900, 1_200)),
37/// );
38/// assert_eq!(s.latest_ended(UnixTime::from_secs(1_199)), None);
39/// assert_eq!(s.latest_ended(UnixTime::from_secs(1_200)), Some(0));
40/// assert_eq!(s.latest_ended(UnixTime::from_secs(2_100)), Some(3));
41///
42/// // Nothing ran yet: run period 3, skip 0..3.
43/// let due = s.ended_periods(None, UnixTime::from_secs(2_100)).ok_or("due")?;
44/// assert_eq!((due.run, due.skip), (3, 0..3));
45///
46/// // Manual only: no period ever ends by itself.
47/// let manual = Schedule::new(0, UnixTime::from_secs(1_000))?;
48/// assert!(manual.is_manual());
49/// assert_eq!(manual.latest_ended(UnixTime::from_secs(u64::MAX)), None);
50/// assert!(Schedule::new(299, UnixTime::from_secs(0)).is_err());
51/// # Ok(())
52/// # }
53/// ```
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub struct Schedule {
56    /// The interval and the anchor; `None` for a manual-only schedule.
57    interval: Option<(u64, u64)>,
58}
59
60impl Schedule {
61    /// Builds the schedule of an installation activated at `activated_at`.
62    ///
63    /// # Errors
64    ///
65    /// [`ScheduleError`] when `schedule_secs` is neither 0 nor in
66    /// `300..=604800`.
67    pub fn new(schedule_secs: u64, activated_at: UnixTime) -> Result<Self, ScheduleError> {
68        check_schedule_secs(schedule_secs)?;
69        if schedule_secs == 0 {
70            return Ok(Self { interval: None });
71        }
72        let at = activated_at.as_secs();
73        let anchor = at - at % schedule_secs;
74        Ok(Self {
75            interval: Some((schedule_secs, anchor)),
76        })
77    }
78
79    /// Returns `true` for a manual-only schedule (`schedule_secs` 0).
80    pub fn is_manual(&self) -> bool {
81        self.interval.is_none()
82    }
83
84    /// Returns the interval in seconds, or `None` when manual.
85    pub fn interval_secs(&self) -> Option<u64> {
86        self.interval.map(|(i, _)| i)
87    }
88
89    /// Returns the anchor, or `None` when manual.
90    pub fn anchor(&self) -> Option<UnixTime> {
91        self.interval.map(|(_, a)| UnixTime::from_secs(a))
92    }
93
94    /// Returns the start and end of period `n`, `[start, end)`, or `None`
95    /// when manual or when the end would not fit in a `u64`.
96    pub fn period_bounds(&self, n: u64) -> Option<(UnixTime, UnixTime)> {
97        let (i, anchor) = self.interval?;
98        let start = n.checked_mul(i)?.checked_add(anchor)?;
99        let end = start.checked_add(i)?;
100        Some((UnixTime::from_secs(start), UnixTime::from_secs(end)))
101    }
102
103    /// Returns the latest period that has ended at `now`, or `None` when
104    /// manual or when no period has ended yet.
105    pub fn latest_ended(&self, now: UnixTime) -> Option<u64> {
106        let (i, anchor) = self.interval?;
107        let elapsed = now.as_secs().checked_sub(anchor)?;
108        (elapsed / i).checked_sub(1)
109    }
110
111    /// Returns what the scheduler does at `now`, given the latest period
112    /// that already has a job (`last_seen`, `None` if none has): the period
113    /// to run and the earlier ended periods to record `skipped`. `None` when
114    /// no period after `last_seen` has ended.
115    pub fn ended_periods(&self, last_seen: Option<u64>, now: UnixTime) -> Option<EndedPeriods> {
116        let latest = self.latest_ended(now)?;
117        let first = match last_seen {
118            Some(seen) => seen.checked_add(1)?,
119            None => 0,
120        };
121        (latest >= first).then_some(EndedPeriods {
122            run: latest,
123            skip: first..latest,
124        })
125    }
126}
127
128/// The scheduler's work at one tick: one period to run, the others skipped.
129#[derive(Debug, Clone, PartialEq, Eq, Hash)]
130pub struct EndedPeriods {
131    /// The latest ended period: create its job.
132    pub run: u64,
133    /// The ended periods before it without a job: record them `skipped`.
134    pub skip: Range<u64>,
135}
136
137/// Checks a `schedule_secs` value: 0, or `300..=604800`.
138///
139/// # Errors
140///
141/// [`ScheduleError`] for any other value.
142///
143/// # Examples
144///
145/// ```
146/// use stratum_node_core::check_schedule_secs;
147///
148/// assert!(check_schedule_secs(0).is_ok());
149/// assert!(check_schedule_secs(300).is_ok());
150/// assert!(check_schedule_secs(604_801).is_err());
151/// ```
152pub fn check_schedule_secs(schedule_secs: u64) -> Result<(), ScheduleError> {
153    if schedule_secs == 0 || (MIN_SCHEDULE_SECS..=MAX_SCHEDULE_SECS).contains(&schedule_secs) {
154        Ok(())
155    } else {
156        Err(ScheduleError)
157    }
158}
159
160/// `schedule_secs` is neither 0 nor between 300 and 604 800.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
162#[error("schedule_secs must be 0 or between 300 and 604800")]
163pub struct ScheduleError;