OXYGENHUB
# f4dfd742b30d oxygenflow / crates / flow-core / src / cron.rs
3.5 KiB · Rust · last changed pipeline.kdl: on { push; tag; manual; schedule } for the pipeline and each job 1 month ago source blame history raw
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
18
fn field(text: &str, lo: u32, hi: u32) -> Option<(Vec<bool>, bool)> {
19
    let mut allowed = vec![false; hi as usize + 1];
20
    let star = text == "*";
21
    for part in text.split(',') {
22
        let (range, step) = match part.split_once('/') {
23
            Some((r, s)) => (r, s.parse::<u32>().ok().filter(|s| *s > 0)?),
24
            None => (part, 1),
25
        };
26
        let (a, b) = if range == "*" {
27
            (lo, hi)
28
        } else if let Some((a, b)) = range.split_once('-') {
29
            (a.parse().ok()?, b.parse().ok()?)
30
        } else {
31
            let a: u32 = range.parse().ok()?;
32
            // `5/15` is from 5 to the end, every 15.
33
            (a, if part.contains('/') { hi } else { a })
34
        };
35
        if a < lo || b > hi || a > b {
36
            return None;
37
        }
38
        let mut v = a;
39
        while v <= b {
40
            allowed[v as usize] = true;
41
            v += step;
42
        }
43
    }
44
    Some((allowed, star))
45
}
46
47
impl Cron {
48
    pub fn parse(line: &str) -> Option<Cron> {
49
        let f: Vec<&str> = line.split_whitespace().collect();
50
        let [m, h, d, mo, w] = f.as_slice() else { return None };
51
        let (minute, _) = field(m, 0, 59)?;
52
        let (hour, _) = field(h, 0, 23)?;
53
        let (day, day_star) = field(d, 1, 31)?;
54
        let (month, _) = field(mo, 1, 12)?;
55
        let (mut weekday, week_star) = field(w, 0, 7)?;
56
        if weekday[7] {
57
            weekday[0] = true;
58
        }
59
        Some(Cron { minute, hour, day, month, weekday, either_day: !day_star && !week_star })
60
    }
61
62
    /// Whether the line is due at this minute (UTC): `weekday` 0 is Sunday.
63
    pub fn matches(&self, minute: u32, hour: u32, day: u32, month: u32, weekday: u32) -> bool {
64
        let get = |v: &Vec<bool>, i: u32| v.get(i as usize).copied().unwrap_or(false);
65
        let (d, w) = (get(&self.day, day), get(&self.weekday, weekday % 7));
66
        let days = if self.either_day { d || w } else { d && w };
67
        get(&self.minute, minute) && get(&self.hour, hour) && get(&self.month, month) && days
68
    }
69
}
70
71
#[cfg(test)]
72
mod tests {
73
    use super::Cron;
74
75
    #[test]
76
    fn lines_parse_and_match_as_cron_does() {
77
        let nightly = Cron::parse("0 3 * * *").unwrap();
78
        assert!(nightly.matches(0, 3, 15, 6, 2));
79
        assert!(!nightly.matches(1, 3, 15, 6, 2));
80
        let quarter = Cron::parse("*/15 9-17 * * 1-5").unwrap();
81
        assert!(quarter.matches(45, 17, 2, 10, 5));
82
        assert!(!quarter.matches(50, 17, 2, 10, 5));
83
        assert!(!quarter.matches(0, 12, 3, 10, 6), "Saturday");
84
        let sunday = Cron::parse("30 4 * * 7").unwrap();
85
        assert!(sunday.matches(30, 4, 4, 10, 0));
86
        let either = Cron::parse("0 0 1 * 1").unwrap();
87
        assert!(either.matches(0, 0, 1, 10, 3) && either.matches(0, 0, 5, 10, 1), "the 1st or a Monday");
88
        for bad in ["", "* * * *", "60 * * * *", "* 24 * * *", "* * 0 * *", "*/0 * * * *", "a * * * *", "5-1 * * * *"] {
89
            assert!(Cron::parse(bad).is_none(), "{bad:?}");
90
        }
91
    }
92
}