1use crate::error::{Result, RulesError};
3use crate::model::{RuleSpec, Schedule};
4use crate::syntax::parse_on;
5
6pub fn parse_every(s: &str) -> Result<Schedule> {
8 let t = s.trim().to_ascii_lowercase();
9 let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
10 let (n, u) = t.split_at(split);
11 let n: i64 = n.parse().map_err(|_| RulesError::invalid("--every", format!("`{s}`: like 30m, 6h, 1d")))?;
12 let unit = match u.trim() {
13 "s" | "sec" | "secs" => 1_000,
14 "m" | "min" | "mins" => 60_000,
15 "h" | "hr" | "hrs" | "" => 3_600_000,
16 "d" | "day" | "days" => 86_400_000,
17 "w" | "week" | "weeks" => 7 * 86_400_000,
18 _ => return Err(RulesError::invalid("--every", format!("`{s}`: use s, m, h, d or w"))),
19 };
20 let ms = n.saturating_mul(unit);
21 if ms < 60_000 {
22 return Err(RulesError::invalid("--every", "at least a minute"));
23 }
24 Ok(Schedule::Every(ms))
25}
26
27#[derive(Debug, Clone, PartialEq)]
31pub struct Cron {
32 min: Vec<bool>,
33 hour: Vec<bool>,
34 dom: Vec<bool>,
35 month: Vec<bool>,
36 dow: Vec<bool>,
37 dom_any: bool,
38 dow_any: bool,
39}
40
41fn cron_field(f: &str, lo: u32, hi: u32, what: &str) -> Result<Vec<bool>> {
42 let bad = || RulesError::invalid("--cron", format!("`{f}` is not a valid {what} ({lo}-{hi}, *, a-b, */n, lists)"));
43 let mut v = vec![false; hi as usize + 1];
44 for part in f.split(',') {
45 let (range, step) = match part.split_once('/') {
46 Some((r, s)) => (r, s.parse::<u32>().ok().filter(|s| *s > 0).ok_or_else(bad)?),
47 None => (part, 1),
48 };
49 let (a, b) = if range == "*" {
50 (lo, hi)
51 } else if let Some((a, b)) = range.split_once('-') {
52 (a.parse().map_err(|_| bad())?, b.parse().map_err(|_| bad())?)
53 } else {
54 let a: u32 = range.parse().map_err(|_| bad())?;
55 (a, if part.contains('/') { hi } else { a })
56 };
57 if a < lo || b > hi || a > b {
58 return Err(bad());
59 }
60 let mut i = a;
61 while i <= b {
62 v[i as usize] = true;
63 i += step;
64 }
65 }
66 Ok(v)
67}
68
69pub fn parse_cron(s: &str) -> Result<Cron> {
70 let f: Vec<&str> = s.split_whitespace().collect();
71 if f.len() != 5 {
72 return Err(RulesError::invalid("--cron", format!("`{s}`: five fields, minute hour day month weekday (like \"0 3 * * *\")")));
73 }
74 let mut dow = cron_field(f[4], 0, 7, "weekday")?;
75 if dow[7] {
76 dow[0] = true;
77 }
78 Ok(Cron {
79 min: cron_field(f[0], 0, 59, "minute")?,
80 hour: cron_field(f[1], 0, 23, "hour")?,
81 dom: cron_field(f[2], 1, 31, "day")?,
82 month: cron_field(f[3], 1, 12, "month")?,
83 dow,
84 dom_any: f[2] == "*",
85 dow_any: f[4] == "*",
86 })
87}
88
89impl Cron {
90 pub fn next_after(&self, after: i64) -> Option<i64> {
92 self.next_after_in(after, &chrono::Local)
93 }
94
95 pub fn next_after_in<Z: chrono::TimeZone>(&self, after: i64, z: &Z) -> Option<i64> {
102 use chrono::{Datelike, Duration, NaiveTime, Timelike};
103 let start = z.timestamp_millis_opt(after).earliest()?.naive_local();
104 let mut t = start.with_second(0)?.with_nanosecond(0)? + Duration::minutes(1);
105 let end = start + Duration::days(366 * 4);
106 let next_day = |t: chrono::NaiveDateTime| t.date().succ_opt().map(|d| d.and_time(NaiveTime::MIN));
107 while t < end {
108 if !self.month[t.month() as usize] {
109 t = next_day(t)?;
110 continue;
111 }
112 let dom = self.dom[t.day() as usize];
113 let dow = self.dow[t.weekday().num_days_from_sunday() as usize];
114 let day_ok = match (self.dom_any, self.dow_any) {
115 (true, true) => true,
116 (false, true) => dom,
117 (true, false) => dow,
118 (false, false) => dom || dow,
119 };
120 if !day_ok {
121 t = next_day(t)?;
122 continue;
123 }
124 if !self.hour[t.hour() as usize] {
125 t = t.with_minute(0)? + Duration::hours(1);
126 continue;
127 }
128 if self.min[t.minute() as usize] {
129 let at = z.from_local_datetime(&t);
130 if let Some(ms) = at.earliest().map(|d| d.timestamp_millis()).filter(|ms| *ms > after) {
132 return Some(ms);
133 }
134 }
135 t += Duration::minutes(1);
136 }
137 None
138 }
139}
140
141pub fn parse_schedule(every: Option<&str>, cron: Option<&str>) -> Result<Option<Schedule>> {
143 match (every, cron) {
144 (Some(_), Some(_)) => Err(RulesError::invalid("schedule", "give --every or --cron, not both")),
145 (Some(e), None) => parse_every(e).map(Some),
146 (None, Some(c)) => {
147 parse_cron(c)?;
148 Ok(Some(Schedule::Cron(c.split_whitespace().collect::<Vec<_>>().join(" "))))
149 }
150 (None, None) => Ok(None),
151 }
152}
153
154pub fn schedule_text(s: &Schedule) -> String {
156 match s {
157 Schedule::Every(ms) => {
158 let ms = *ms;
159 let (n, u) = [(7 * 86_400_000, "w"), (86_400_000, "d"), (3_600_000, "h"), (60_000, "m"), (1_000, "s")]
160 .iter()
161 .find(|(u, _)| ms % u == 0)
162 .map(|(u, n)| (ms / u, *n))
163 .unwrap_or((ms, "ms"));
164 format!("every {n}{u}")
165 }
166 Schedule::Cron(c) => format!("cron \"{c}\""),
167 }
168}
169
170pub fn next_run(s: &Schedule, created_at: i64, last_run_at: Option<i64>) -> Option<i64> {
174 next_run_in(s, created_at, last_run_at, &chrono::Local)
175}
176
177pub fn next_run_in<Z: chrono::TimeZone>(s: &Schedule, created_at: i64, last_run_at: Option<i64>, z: &Z) -> Option<i64> {
179 match s {
180 Schedule::Every(ms) => Some(last_run_at.map_or(created_at, |l| l + ms)),
181 Schedule::Cron(c) => parse_cron(c).ok()?.next_after_in(last_run_at.unwrap_or(created_at), z),
182 }
183}
184
185pub fn parse_on_text(s: &str, kinds: &[&str], hint: &str) -> Result<(Vec<String>, Option<Schedule>)> {
188 let t = s.trim();
189 let low = t.to_ascii_lowercase();
190 if !(low.starts_with("every ") || low.starts_with("cron ")) {
191 return Ok((parse_on(&[t.to_string()], kinds, hint)?, None));
192 }
193 let (sched, rest) = t.split_once(';').unwrap_or((t, ""));
194 let (word, arg) = sched.trim().split_once(' ').unwrap_or((sched, ""));
195 let arg = arg.trim().trim_matches('"');
196 let schedule = if word.eq_ignore_ascii_case("every") { parse_schedule(Some(arg), None)? } else { parse_schedule(None, Some(arg))? };
197 let on = if rest.trim().is_empty() { vec![] } else { parse_on(&[rest.to_string()], kinds, hint)? };
198 Ok((on, schedule))
199}
200
201pub fn on_text<T>(spec: &RuleSpec<T>) -> String {
203 match &spec.schedule {
204 Some(s) if spec.on.is_empty() => schedule_text(s),
205 Some(s) => format!("{}; {}", schedule_text(s), spec.on.join(", ")),
206 None => spec.on.join(", "),
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use chrono::{FixedOffset, TimeZone, Timelike, Utc};
214
215 const H: i64 = 3_600_000;
216
217 fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> i64 {
218 Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap().timestamp_millis()
219 }
220
221 #[test]
222 fn every_parse_and_print() {
223 assert_eq!(parse_every("6h").unwrap(), Schedule::Every(6 * H));
224 assert_eq!(parse_every("30m").unwrap(), Schedule::Every(1_800_000));
225 assert_eq!(parse_every(" 2 ").unwrap(), Schedule::Every(2 * H), "no unit: hours");
226 assert_eq!(parse_every("60s").unwrap(), Schedule::Every(60_000));
227 assert_eq!(schedule_text(&parse_every("1d").unwrap()), "every 1d");
228 assert_eq!(schedule_text(&parse_every("90m").unwrap()), "every 90m");
229 assert_eq!(schedule_text(&parse_every("2w").unwrap()), "every 2w");
230 assert_eq!(schedule_text(&Schedule::Every(61_500)), "every 61500ms");
231 assert_eq!(parse_every("10s").unwrap_err().to_string(), "invalid --every: at least a minute");
232 assert_eq!(parse_every("6x").unwrap_err().to_string(), "invalid --every: `6x`: use s, m, h, d or w");
233 assert_eq!(parse_every("h").unwrap_err().to_string(), "invalid --every: `h`: like 30m, 6h, 1d");
234 assert!(parse_every("99999999999999999999h").is_err());
235 assert_eq!(parse_every("9999999999999w").unwrap(), Schedule::Every(i64::MAX), "saturates");
236 }
237
238 #[test]
239 fn cron_parse_and_errors() {
240 assert!(parse_cron("0 3 * * *").is_ok() && parse_cron("*/15 9-17 * * 1-5").is_ok() && parse_cron("0,30 * 1 1 0").is_ok());
241 assert!(parse_cron("0 3 * *").is_err() && parse_cron("60 * * * *").is_err() && parse_cron("* 25 * * *").is_err());
242 assert!(parse_cron("* * 0 * *").is_err() && parse_cron("* * * 13 *").is_err() && parse_cron("* * * * 8").is_err());
243 assert!(parse_cron("*/0 * * * *").is_err() && parse_cron("5-1 * * * *").is_err());
244 assert_eq!(parse_cron("x * * * *").unwrap_err().to_string(), "invalid --cron: `x` is not a valid minute (0-59, *, a-b, */n, lists)");
245 assert_eq!(parse_schedule(Some("1h"), Some("0 3 * * *")).unwrap_err().to_string(), "invalid schedule: give --every or --cron, not both");
246 assert_eq!(parse_schedule(None, Some(" 0 3 * * * ")).unwrap(), Some(Schedule::Cron("0 3 * * *".into())));
247 assert_eq!(parse_schedule(None, None).unwrap(), None);
248 }
249
250 #[test]
251 fn cron_steps_in_fixed_zones() {
252 let at = utc(2026, 11, 1, 10, 7);
254 let c = parse_cron("0 3 * * *").unwrap();
255 assert_eq!(c.next_after_in(at, &Utc), Some(utc(2026, 11, 2, 3, 0)));
256 let est = FixedOffset::west_opt(5 * 3600).unwrap();
258 assert_eq!(c.next_after_in(at, &est), Some(utc(2026, 11, 2, 8, 0)));
259 let kiri = FixedOffset::east_opt(14 * 3600).unwrap();
261 assert_eq!(c.next_after_in(at, &kiri), Some(utc(2026, 11, 1, 13, 0)));
262 assert_eq!(parse_cron("*/15 * * * *").unwrap().next_after_in(at, &Utc), Some(utc(2026, 11, 1, 10, 15)));
263 assert_eq!(parse_cron("15 10 * * *").unwrap().next_after_in(utc(2026, 11, 1, 10, 15), &Utc), Some(utc(2026, 11, 2, 10, 15)));
265 assert_eq!(parse_cron("0 9 * * 1").unwrap().next_after_in(at, &Utc), Some(utc(2026, 11, 2, 9, 0)));
267 assert_eq!(parse_cron("0 12 * * 7").unwrap().next_after_in(at, &Utc), Some(utc(2026, 11, 1, 12, 0)));
268 assert_eq!(parse_cron("0 0 15 * 5").unwrap().next_after_in(at, &Utc), Some(utc(2026, 11, 6, 0, 0)));
270 assert_eq!(parse_cron("0 0 1 1 *").unwrap().next_after_in(at, &Utc), Some(utc(2027, 1, 1, 0, 0)));
272 assert_eq!(parse_cron("0 0 29 2 *").unwrap().next_after_in(at, &Utc), Some(utc(2028, 2, 29, 0, 0)));
273 assert_eq!(parse_cron("0 0 31 2 *").unwrap().next_after_in(at, &Utc), None);
275 let n = c.next_after(at).unwrap();
277 let t = chrono::Local.timestamp_millis_opt(n).unwrap();
278 assert_eq!((t.hour(), t.minute()), (3, 0));
279 assert!(n > at && n - at <= 25 * H);
280 }
281
282 #[test]
286 fn cron_across_daylight_saving() {
287 let ny = chrono_tz::America::New_York;
288 let at = utc(2026, 10, 25, 12, 0); assert_eq!(parse_cron("0 0 1 1 *").unwrap().next_after_in(at, &ny), Some(utc(2027, 1, 1, 5, 0)));
291 assert_eq!(parse_cron("0 9 * * 1").unwrap().next_after_in(at, &ny), Some(utc(2026, 10, 26, 13, 0)));
292 assert_eq!(parse_cron("0 9 * * 1").unwrap().next_after_in(utc(2026, 10, 27, 0, 0), &ny), Some(utc(2026, 11, 2, 14, 0)), "09:00 EST");
293 assert_eq!(parse_cron("0 0 29 2 *").unwrap().next_after_in(at, &ny), Some(utc(2028, 2, 29, 5, 0)));
294 assert_eq!(parse_cron("0 0 31 2 *").unwrap().next_after_in(at, &ny), None);
295 let c = parse_cron("30 1 * * *").unwrap();
297 let first = c.next_after_in(utc(2026, 11, 1, 4, 0), &ny).unwrap();
298 assert_eq!(first, utc(2026, 11, 1, 5, 30));
299 assert_eq!(c.next_after_in(first, &ny), Some(utc(2026, 11, 2, 6, 30)));
300 assert_eq!(c.next_after_in(utc(2026, 11, 1, 6, 0), &ny), Some(utc(2026, 11, 2, 6, 30)), "inside the repeat: not again");
301 let h = parse_cron("0 * * * *").unwrap();
303 assert_eq!(h.next_after_in(utc(2026, 11, 1, 4, 30), &ny), Some(utc(2026, 11, 1, 5, 0)));
304 assert_eq!(h.next_after_in(utc(2026, 11, 1, 5, 0), &ny), Some(utc(2026, 11, 1, 7, 0)));
305 let q = parse_cron("*/15 * * * *").unwrap();
307 assert_eq!(q.next_after_in(utc(2026, 11, 1, 6, 20), &ny), Some(utc(2026, 11, 1, 7, 0)), "no run in the repeat after its first pass");
308 let s = parse_cron("30 2 * * *").unwrap();
310 assert_eq!(s.next_after_in(utc(2027, 3, 13, 12, 0), &ny), Some(utc(2027, 3, 15, 6, 30)));
311 assert_eq!(parse_cron("0 3 * * *").unwrap().next_after_in(utc(2027, 3, 14, 6, 0), &ny), Some(utc(2027, 3, 14, 7, 0)), "03:00 EDT");
312 }
313
314 #[test]
315 fn next_run_with_a_fake_clock() {
316 let created = utc(2026, 11, 1, 10, 7);
317 let every = Schedule::Every(6 * H);
318 assert_eq!(next_run(&every, created, None), Some(created), "never ran: due at once");
319 assert_eq!(next_run(&every, created, Some(created + H)), Some(created + 7 * H));
320 let cron = Schedule::Cron("30 * * * *".into());
321 assert_eq!(next_run_in(&cron, created, None, &Utc), Some(utc(2026, 11, 1, 10, 30)));
322 assert_eq!(next_run_in(&cron, created, Some(utc(2026, 11, 1, 10, 30)), &Utc), Some(utc(2026, 11, 1, 11, 30)));
323 assert_eq!(next_run_in(&Schedule::Cron("bad".into()), created, None, &Utc), None);
324 }
325
326 #[test]
327 fn on_text_round_trips() {
328 let kinds = &["import", "schedule"];
329 let (on, s) = parse_on_text("every 6h; import", kinds, "").unwrap();
330 assert_eq!((on, s), (vec!["import".to_string()], Some(Schedule::Every(6 * H))));
331 let spec: RuleSpec<()> = RuleSpec { schedule: Some(Schedule::Cron("0 3 * * *".into())), ..Default::default() };
332 assert_eq!(on_text(&spec), "cron \"0 3 * * *\"");
333 assert_eq!(parse_on_text(&on_text(&spec), kinds, "").unwrap().1, spec.schedule);
334 let spec: RuleSpec<()> = RuleSpec { on: vec!["import".into()], schedule: Some(Schedule::Every(H)), ..Default::default() };
335 assert_eq!(on_text(&spec), "every 1h; import");
336 assert_eq!(parse_on_text(&on_text(&spec), kinds, "").unwrap(), (spec.on.clone(), spec.schedule.clone()));
337 assert_eq!(parse_on_text("import", kinds, "").unwrap(), (vec!["import".to_string()], None));
338 assert!(parse_on_text("every 6h; nope", kinds, "").is_err());
339 }
340}