Skip to main content

agentmux_srv_core/backend/cron/
expr.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Standard 5-field cron ("min hour dom mon dow", as the Schedule tool
5//! documents it) read with the `cron` crate, which wants a seconds field
6//! first and numbers the days of the week 1 = Sunday … 7 = Saturday. In
7//! standard cron 0 and 7 are Sunday and 1 is Monday, so the expression is
8//! translated here, at parse time only: a job's stored expression stays the
9//! standard one it was written in. Every parse of a job's expression goes
10//! through [`parse`].
11
12use std::collections::BTreeSet;
13use std::str::FromStr;
14
15use cron::Schedule;
16
17/// `five_field`, a standard 5-field cron expression, as the `cron` crate's
18/// expression: a `0` seconds field first, and a numeric day-of-week field in
19/// the crate's numbering. Names (`MON-FRI`, `SUN`), `*` and `?` are kept as
20/// they are. Ranges may wrap (`5-1` is Friday to Monday).
21pub fn to_crate_expr(five_field: &str) -> Result<String, String> {
22    let fields: Vec<&str> = five_field.split_whitespace().collect();
23    let [min, hour, dom, mon, dow] = fields[..] else {
24        return Err(format!("expected 5 fields (min hour dom mon dow), got {}", fields.len()));
25    };
26    Ok(format!("0 {min} {hour} {dom} {mon} {}", crate_dow(dow)?))
27}
28
29/// [`to_crate_expr`], parsed.
30pub fn parse(five_field: &str) -> Result<Schedule, String> {
31    let expr = to_crate_expr(five_field)?;
32    Schedule::from_str(&expr).map_err(|e| e.to_string())
33}
34
35/// A standard day-of-week field in the crate's numbering.
36fn crate_dow(field: &str) -> Result<String, String> {
37    if field == "*" || field == "?" {
38        return Ok(field.to_string());
39    }
40    let mut days: BTreeSet<u32> = BTreeSet::new();
41    let mut named: Vec<&str> = Vec::new();
42    for item in field.split(',') {
43        if item.chars().any(|c| c.is_ascii_alphabetic()) {
44            named.push(item);
45        } else {
46            days.extend(standard_days(item)?);
47        }
48    }
49    // Standard Sunday (0) is the crate's 1; Monday (1) its 2, and so on.
50    let mut out: Vec<String> = days.into_iter().map(|d| (d + 1).to_string()).collect();
51    out.extend(named.into_iter().map(str::to_string));
52    Ok(out.join(","))
53}
54
55/// The days (0 = Sunday … 6 = Saturday) one numeric item of a standard
56/// day-of-week list names: `n`, `a-b`, `a-b/s`, `a/s` or `*/s`. 7 is
57/// Sunday too. A range whose start is after its end wraps through Sunday.
58fn standard_days(item: &str) -> Result<Vec<u32>, String> {
59    let bad = || format!("invalid day of week '{item}' (use 0-7, where 0 and 7 are Sunday, or MON-SUN)");
60    let num = |s: &str| s.parse::<u32>().ok().filter(|&n| n <= 7).ok_or_else(bad);
61    let (range, step) = match item.split_once('/') {
62        Some((r, s)) => (r, Some(s.parse::<usize>().ok().filter(|&s| s > 0).ok_or_else(bad)?)),
63        None => (item, None),
64    };
65    let seq: Vec<u32> = if range == "*" {
66        (0..=6).collect()
67    } else if let Some((a, b)) = range.split_once('-') {
68        let (a, b) = (num(a)?, num(b)?);
69        if a <= b {
70            (a..=b).map(|d| d % 7).collect()
71        } else {
72            // Wraps through Sunday: 5-1 is Fri, Sat, Sun, Mon.
73            let (from, to) = (a % 7, b % 7);
74            let len = (to + 7 - from) % 7 + 1;
75            (0..len).map(|i| (from + i) % 7).collect()
76        }
77    } else if step.is_some() {
78        // `a/s`, any step: from a through the end of the week (7, Sunday).
79        (num(range)?..=7).map(|d| d % 7).collect()
80    } else {
81        vec![num(range)? % 7]
82    };
83    Ok(seq.into_iter().step_by(step.unwrap_or(1)).collect())
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use chrono::{Datelike, TimeZone, Utc, Weekday};
90
91    /// The weekdays `five_field` fires on, from a week of its fires.
92    fn fires_on(five_field: &str) -> BTreeSet<u32> {
93        let schedule = parse(five_field).unwrap_or_else(|e| panic!("{five_field}: {e}"));
94        // 2026-01-04 is a Sunday.
95        let start = Utc.with_ymd_and_hms(2026, 1, 3, 23, 0, 0).unwrap();
96        schedule
97            .after(&start)
98            .take_while(|t| *t < start + chrono::Duration::days(7))
99            .map(|t| t.weekday().num_days_from_sunday())
100            .collect()
101    }
102
103    fn set(days: &[u32]) -> BTreeSet<u32> {
104        days.iter().copied().collect()
105    }
106
107    #[test]
108    fn each_day_number_is_the_standard_day_and_0_and_7_are_both_sunday() {
109        for d in 0..=6 {
110            assert_eq!(fires_on(&format!("0 6 * * {d}")), set(&[d]), "day {d}");
111        }
112        assert_eq!(fires_on("0 6 * * 7"), set(&[0]), "7 is Sunday too");
113    }
114
115    #[test]
116    fn lists_ranges_and_steps_mean_what_standard_cron_means() {
117        assert_eq!(fires_on("0 6 * * 1-5"), set(&[1, 2, 3, 4, 5]), "Monday to Friday");
118        assert_eq!(fires_on("0 6 * * 1,3,5"), set(&[1, 3, 5]));
119        assert_eq!(fires_on("0 6 * * */2"), set(&[0, 2, 4, 6]));
120        assert_eq!(fires_on("0 6 * * 1-5/2"), set(&[1, 3, 5]));
121        assert_eq!(fires_on("0 6 * * 1/2"), set(&[1, 3, 5, 0]), "from Monday through Sunday, every 2");
122        assert_eq!(fires_on("0 6 * * 1/1"), set(&[1, 2, 3, 4, 5, 6, 0]), "a step of 1 is still a range");
123        assert_eq!(fires_on("0 6 * * 3/2"), set(&[3, 5, 0]), "Wednesday, Friday, Sunday");
124        assert_eq!(fires_on("0 6 * * 0/3"), set(&[0, 3, 6]));
125        assert_eq!(fires_on("0 6 * * */1"), set(&[0, 1, 2, 3, 4, 5, 6]));
126        assert_eq!(fires_on("0 6 * * 0-7"), set(&[0, 1, 2, 3, 4, 5, 6]));
127        assert_eq!(fires_on("0 6 * * 5-7"), set(&[5, 6, 0]), "Friday to Sunday");
128        assert_eq!(fires_on("0 6 * * 5-1"), set(&[5, 6, 0, 1]), "wraps: Friday to Monday");
129        assert_eq!(fires_on("0 6 * * 6-0"), set(&[6, 0]));
130        assert_eq!(fires_on("0 6 * * 0,6"), set(&[0, 6]));
131        assert_eq!(fires_on("0 6 * * *"), set(&[0, 1, 2, 3, 4, 5, 6]));
132    }
133
134    #[test]
135    fn names_are_kept_and_mean_their_day() {
136        assert_eq!(to_crate_expr("0 6 * * MON-FRI").unwrap(), "0 0 6 * * MON-FRI");
137        assert_eq!(fires_on("0 6 * * MON-FRI"), set(&[1, 2, 3, 4, 5]));
138        assert_eq!(fires_on("0 6 * * SUN"), set(&[0]));
139    }
140
141    #[test]
142    fn the_other_fields_pass_through_with_a_seconds_field_first() {
143        assert_eq!(to_crate_expr("*/15 * * * *").unwrap(), "0 */15 * * * *");
144        assert_eq!(to_crate_expr("0 6 1 * 1").unwrap(), "0 0 6 1 * 2");
145        assert_eq!(to_crate_expr("0 6 * * 5-1").unwrap(), "0 0 6 * * 1,2,6,7");
146    }
147
148    #[test]
149    fn bad_expressions_are_refused() {
150        for bad in ["0 6 * *", "0 6 * * 1 2", "0 6 * * 8", "0 6 * * 1-9", "0 6 * * x-", "0 6 * * */0", "61 6 * * 1"] {
151            assert!(parse(bad).is_err(), "{bad}");
152        }
153    }
154
155    /// `0 6 * * 1` is Monday 06:00. A job saved with it before this fix
156    /// fired on Sunday (the crate's 1); its stored expression is unchanged
157    /// and its next fire is now the documented Monday.
158    #[test]
159    fn a_saved_numeric_weekday_job_fires_on_the_documented_day() {
160        let saturday = Utc.with_ymd_and_hms(2026, 1, 3, 12, 0, 0).unwrap().timestamp_millis();
161        let schedule = crate::backend::cron::schedule::JobSchedule::cron("0 6 * * 1", "UTC").unwrap();
162        let next = schedule.next_after(saturday).unwrap();
163        let next = Utc.timestamp_millis_opt(next).unwrap();
164        assert_eq!((next.weekday(), next.format("%H:%M").to_string()), (Weekday::Mon, "06:00".to_string()));
165        // What the old reading did: the crate's own 1, a Sunday.
166        let old = Schedule::from_str("0 0 6 * * 1").unwrap();
167        let before = old.after(&Utc.timestamp_millis_opt(saturday).unwrap()).next().unwrap();
168        assert_eq!(before.weekday(), Weekday::Sun);
169    }
170}