OXYGENHUB

Coverage / crates/flow-core/src/cron.rs 100.0%

59 of 59 lines run, 6 of 11 functions · run #216 on main · run missed

1
//! Five-field cron lines for `on { schedule "…" }` (oxygenflow#24):
2
//! minute, hour, day of month, month, day of week (0 or 7 is Sunday), each
3
//! `*`, a number, a range `a-b`, a list `a,b`, or any of those `/step`.
4
//! The hub checks each minute which lines are due.
5
6
/// A parsed line: the values each field allows.
7
#[derive(Clone, Debug, PartialEq, Eq)]
8
pub struct Cron {
9
    minute: Vec<bool>,
10
    hour: Vec<bool>,
11
    day: Vec<bool>,
12
    month: Vec<bool>,
13
    weekday: Vec<bool>,
14
    /// Both day fields restricted: either may match, as cron has it.
15
    either_day: bool,
16
}
17
1864×
fn field(text: &str, lo: u32, hi: u32) -> Option<(Vec<bool>, bool)> {
1964×
    let mut allowed = vec![false; hi as usize + 1];
2064×
    let star = text == "*";
2164×
    for part in text.split(',') {
2264×
        let (range, step) = match part.split_once('/') {
232×
            Some((r, s)) => (r, s.parse::<u32>().ok().filter(|s| *s > 0)?),
2462×
            None => (part, 1),
25
        };
2663×
        let (a, b) = if range == "*" {
2733×
            (lo, hi)
2830×
        } else if let Some((a, b)) = range.split_once('-') {
293×
            (a.parse().ok()?, b.parse().ok()?)
30
        } else {
3127×
            let a: u32 = range.parse().ok()?;
32
            // `5/15` is from 5 to the end, every 15.
3326×
            (a, if part.contains('/') { hi } else { a })
34
        };
3562×
        if a < lo || b > hi || a > b {
364×
            return None;
3758×
        }
3858×
        let mut v = a;
39749×
        while v <= b {
40691×
            allowed[v as usize] = true;
41691×
            v += step;
42691×
        }
43
    }
4458×
    Some((allowed, star))
4564×
}
46
47
impl Cron {
4820×
    pub fn parse(line: &str) -> Option<Cron> {
4920×
        let f: Vec<&str> = line.split_whitespace().collect();
5020×
        let [m, h, d, mo, w] = f.as_slice() else { return None };
5117×
        let (minute, _) = field(m, 0, 59)?;
5213×
        let (hour, _) = field(h, 0, 23)?;
5312×
        let (day, day_star) = field(d, 1, 31)?;
5411×
        let (month, _) = field(mo, 1, 12)?;
5511×
        let (mut weekday, week_star) = field(w, 0, 7)?;
5611×
        if weekday[7] {
579×
            weekday[0] = true;
589×
        }
5911×
        Some(Cron { minute, hour, day, month, weekday, either_day: !day_star && !week_star })
6020×
    }
61
62
    /// Whether the line is due at this minute (UTC): `weekday` 0 is Sunday.
6310×
    pub fn matches(&self, minute: u32, hour: u32, day: u32, month: u32, weekday: u32) -> bool {
6444×
        let get = |v: &Vec<bool>, i: u32| v.get(i as usize).copied().unwrap_or(false);
6510×
        let (d, w) = (get(&self.day, day), get(&self.weekday, weekday % 7));
6610×
        let days = if self.either_day { d || w } else { d && w };
6710×
        get(&self.minute, minute) && get(&self.hour, hour) && get(&self.month, month) && days
6810×
    }
69
}
70
71
#[cfg(test)]
72
mod tests {
73
    use super::Cron;
74
75
    #[test]
761×
    fn lines_parse_and_match_as_cron_does() {
771×
        let nightly = Cron::parse("0 3 * * *").unwrap();
781×
        assert!(nightly.matches(0, 3, 15, 6, 2));
791×
        assert!(!nightly.matches(1, 3, 15, 6, 2));
801×
        let quarter = Cron::parse("*/15 9-17 * * 1-5").unwrap();
811×
        assert!(quarter.matches(45, 17, 2, 10, 5));
821×
        assert!(!quarter.matches(50, 17, 2, 10, 5));
831×
        assert!(!quarter.matches(0, 12, 3, 10, 6), "Saturday");
841×
        let sunday = Cron::parse("30 4 * * 7").unwrap();
851×
        assert!(sunday.matches(30, 4, 4, 10, 0));
861×
        let either = Cron::parse("0 0 1 * 1").unwrap();
871×
        assert!(either.matches(0, 0, 1, 10, 3) && either.matches(0, 0, 5, 10, 1), "the 1st or a Monday");
888×
        for bad in ["", "* * * *", "60 * * * *", "* 24 * * *", "* * 0 * *", "*/0 * * * *", "a * * * *", "5-1 * * * *"] {
898×
            assert!(Cron::parse(bad).is_none(), "{bad:?}");
90
        }
911×
    }
92
}