engenho_controllers/cron.rs
1//! Minimal typed 5-field cron parser — the engenho-native cron surface.
2//!
3//! No external cron crate exists in the workspace (checked Cargo.lock),
4//! and the upstream `cron`/`saffron` crates are heavier than the surface
5//! the `CronJobController` needs. Per the Prime Directive (don't add a
6//! heavy dep for a small typed surface that we can author once), this is
7//! a lightweight typed parser for standard Vixie-style 5-field cron:
8//!
9//! ```text
10//! ┌───────────── minute (0-59)
11//! │ ┌─────────── hour (0-23)
12//! │ │ ┌───────── day-of-month (1-31)
13//! │ │ │ ┌─────── month (1-12)
14//! │ │ │ │ ┌───── day-of-week (0-6, Sunday=0)
15//! │ │ │ │ │
16//! * * * * *
17//! ```
18//!
19//! Each field supports `*`, a single number `N`, a comma list
20//! `a,b,c`, a range `a-b`, a step `*/k`, and a ranged step `a-b/k`.
21//! Day-of-week `7` is normalised to Sunday (`0`), matching cron(5).
22//!
23//! ## Day-of-month ∧ day-of-week semantics (cron(5) "OR" rule)
24//!
25//! When BOTH day-of-month and day-of-week are restricted (neither is
26//! `*`), a timestamp matches if it satisfies EITHER field — the classic
27//! cron-OR rule. When one is `*`, both must match (the `*` is vacuously
28//! satisfied). This mirrors Vixie cron + the Kubernetes `CronJob`
29//! controller's behaviour.
30//!
31//! ## Time decomposition
32//!
33//! A unix-seconds instant is decomposed to UTC calendar fields via
34//! chrono (the typed calendar surface engenho-types already depends on).
35//! Timezone-aware schedules (`spec.timeZone`) are a named follow-up —
36//! this parser evaluates against UTC.
37
38use chrono::{DateTime, Datelike, Timelike, Utc};
39
40/// A parse failure for one cron field or the whole expression. Typed so
41/// the controller surfaces a bad `spec.schedule` as a skip-with-reason,
42/// never a panic.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum CronParseError {
45 /// The expression did not have exactly 5 whitespace-separated fields.
46 FieldCount {
47 /// The number of fields actually found.
48 found: usize,
49 },
50 /// A field's token could not be parsed (bad number, empty range, …).
51 Field {
52 /// Which field (0=minute … 4=day-of-week).
53 index: usize,
54 /// The offending token.
55 token: String,
56 },
57}
58
59impl std::fmt::Display for CronParseError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 match self {
62 Self::FieldCount { found } => {
63 write!(f, "cron expression must have 5 fields, found {found}")
64 }
65 Self::Field { index, token } => {
66 write!(f, "invalid cron field {index}: {token:?}")
67 }
68 }
69 }
70}
71
72impl std::error::Error for CronParseError {}
73
74/// A single parsed cron field — the set of integer values it admits.
75///
76/// Stored as an explicit sorted value set (each field's domain is tiny —
77/// at most 60 values), plus a `wildcard` flag so the day-of-month ∧
78/// day-of-week OR-rule can ask "was this field restricted?".
79#[derive(Debug, Clone, PartialEq, Eq)]
80struct CronField {
81 values: Vec<u32>,
82 wildcard: bool,
83}
84
85impl CronField {
86 fn matches(&self, v: u32) -> bool {
87 self.values.binary_search(&v).is_ok()
88 }
89}
90
91/// A parsed 5-field cron schedule. Construct via [`CronSchedule::parse`];
92/// match an instant via [`CronSchedule::matches_unix`]; find the next due
93/// time via [`CronSchedule::next_after_unix`].
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CronSchedule {
96 minute: CronField,
97 hour: CronField,
98 dom: CronField,
99 month: CronField,
100 dow: CronField,
101}
102
103impl CronSchedule {
104 /// Parse a standard 5-field cron expression.
105 ///
106 /// # Errors
107 ///
108 /// [`CronParseError::FieldCount`] if not exactly 5 fields;
109 /// [`CronParseError::Field`] if any field's token is malformed or
110 /// out of range.
111 pub fn parse(expr: &str) -> Result<Self, CronParseError> {
112 let fields: Vec<&str> = expr.split_whitespace().collect();
113 if fields.len() != 5 {
114 return Err(CronParseError::FieldCount {
115 found: fields.len(),
116 });
117 }
118 Ok(Self {
119 minute: parse_field(fields[0], 0, 0, 59)?,
120 hour: parse_field(fields[1], 1, 0, 23)?,
121 dom: parse_field(fields[2], 2, 1, 31)?,
122 month: parse_field(fields[3], 3, 1, 12)?,
123 dow: parse_field(fields[4], 4, 0, 6)?,
124 })
125 }
126
127 /// Does the given UTC instant (unix seconds) match this schedule, to
128 /// minute precision (seconds are ignored, as in cron)?
129 #[must_use]
130 pub fn matches_unix(&self, unix_secs: u64) -> bool {
131 let Some(dt) = unix_to_utc(unix_secs) else {
132 return false;
133 };
134 self.matches_dt(&dt)
135 }
136
137 fn matches_dt(&self, dt: &DateTime<Utc>) -> bool {
138 if !self.minute.matches(dt.minute()) || !self.hour.matches(dt.hour()) {
139 return false;
140 }
141 if !self.month.matches(dt.month()) {
142 return false;
143 }
144 let day_of_month_ok = self.dom.matches(dt.day());
145 // chrono Weekday: Mon=0..Sun=6 via num_days_from_monday; cron wants
146 // Sun=0..Sat=6. num_days_from_sunday gives exactly that.
147 let weekday_ok = self.dow.matches(dt.weekday().num_days_from_sunday());
148 // cron(5) OR-rule: when BOTH dom and dow are restricted, match on
149 // either; otherwise both must hold (a `*` field is vacuously true).
150 if self.dom.wildcard || self.dow.wildcard {
151 day_of_month_ok && weekday_ok
152 } else {
153 day_of_month_ok || weekday_ok
154 }
155 }
156
157 /// The first scheduled minute STRICTLY AFTER `after_unix`, or `None`
158 /// if no match is found within a bounded search horizon (4 years —
159 /// covers Feb-29-only schedules). The returned value is aligned to the
160 /// top of the minute (seconds = 0).
161 #[must_use]
162 pub fn next_after_unix(&self, after_unix: u64) -> Option<u64> {
163 // 4-year horizon in minutes (catches Feb-29 leap-day schedules).
164 const HORIZON_MINUTES: u64 = 4 * 366 * 24 * 60;
165 // Start at the next whole minute strictly after `after_unix`.
166 let mut t = (after_unix / 60 + 1) * 60;
167 for _ in 0..HORIZON_MINUTES {
168 if self.matches_unix(t) {
169 return Some(t);
170 }
171 t += 60;
172 }
173 None
174 }
175}
176
177/// Decompose a unix-seconds instant to a UTC `DateTime`. `None` only for
178/// timestamps chrono cannot represent (far outside the supported range).
179fn unix_to_utc(unix_secs: u64) -> Option<DateTime<Utc>> {
180 let secs = i64::try_from(unix_secs).ok()?;
181 DateTime::<Utc>::from_timestamp(secs, 0)
182}
183
184/// Parse one cron field into its admissible value set.
185fn parse_field(field: &str, index: usize, min: u32, max: u32) -> Result<CronField, CronParseError> {
186 let err = || CronParseError::Field {
187 index,
188 token: field.to_string(),
189 };
190 let wildcard = field == "*" || field.starts_with("*/");
191 let mut values: std::collections::BTreeSet<u32> = std::collections::BTreeSet::new();
192 for part in field.split(',') {
193 parse_part(part, index, min, max, &mut values)?;
194 }
195 if values.is_empty() {
196 return Err(err());
197 }
198 Ok(CronField {
199 values: values.into_iter().collect(),
200 wildcard,
201 })
202}
203
204/// Parse one comma-separated component of a cron field: `*`, `N`, `a-b`,
205/// `*/k`, or `a-b/k`. Day-of-week `7` is folded to `0` (Sunday).
206fn parse_part(
207 part: &str,
208 index: usize,
209 min: u32,
210 max: u32,
211 out: &mut std::collections::BTreeSet<u32>,
212) -> Result<(), CronParseError> {
213 let err = || CronParseError::Field {
214 index,
215 token: part.to_string(),
216 };
217
218 // Split off an optional `/step` suffix.
219 let (range_spec, step) = match part.split_once('/') {
220 Some((r, s)) => {
221 let step: u32 = s.parse().map_err(|_| err())?;
222 if step == 0 {
223 return Err(err());
224 }
225 (r, step)
226 }
227 None => (part, 1),
228 };
229
230 // Resolve the range the step walks over.
231 let (lo, hi) = if range_spec == "*" {
232 (min, max)
233 } else if let Some((a, b)) = range_spec.split_once('-') {
234 let lo = fold_dow(a.parse().map_err(|_| err())?, index);
235 let hi = fold_dow(b.parse().map_err(|_| err())?, index);
236 if lo > hi {
237 return Err(err());
238 }
239 (lo, hi)
240 } else {
241 // A bare number. With a step (`N/k`) it means "from N, stepping".
242 let n = fold_dow(range_spec.parse().map_err(|_| err())?, index);
243 if step == 1 { (n, n) } else { (n, max) }
244 };
245
246 if lo < min || hi > max {
247 return Err(err());
248 }
249
250 let mut v = lo;
251 while v <= hi {
252 out.insert(v);
253 v += step;
254 }
255 Ok(())
256}
257
258/// Fold day-of-week `7` → `0` (both are Sunday in cron(5)). Only applies
259/// to the day-of-week field (index 4); a no-op for every other field.
260fn fold_dow(v: u32, index: usize) -> u32 {
261 if index == 4 && v == 7 { 0 } else { v }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn parse_rejects_wrong_field_count() {
270 assert_eq!(
271 CronSchedule::parse("* * * *"),
272 Err(CronParseError::FieldCount { found: 4 })
273 );
274 assert_eq!(
275 CronSchedule::parse("* * * * * *"),
276 Err(CronParseError::FieldCount { found: 6 })
277 );
278 }
279
280 #[test]
281 fn every_minute_matches_any_instant() {
282 let s = CronSchedule::parse("* * * * *").unwrap();
283 // 2026-06-15T12:34:00Z = 1781613240. Any minute matches.
284 assert!(s.matches_unix(1_781_613_240));
285 assert!(s.matches_unix(0));
286 }
287
288 #[test]
289 fn next_after_every_minute_is_next_whole_minute() {
290 let s = CronSchedule::parse("* * * * *").unwrap();
291 // After 100s (01:40) the next due minute is 120s (02:00).
292 assert_eq!(s.next_after_unix(100), Some(120));
293 // Exactly on a minute boundary → strictly-after gives the next one.
294 assert_eq!(s.next_after_unix(120), Some(180));
295 }
296
297 #[test]
298 fn specific_minute_hour() {
299 // "30 2 * * *" = 02:30 UTC daily.
300 let s = CronSchedule::parse("30 2 * * *").unwrap();
301 // 2026-01-01T00:00:00Z = 1767225600.
302 let next = s.next_after_unix(1_767_225_600).unwrap();
303 let dt = unix_to_utc(next).unwrap();
304 assert_eq!(dt.hour(), 2);
305 assert_eq!(dt.minute(), 30);
306 }
307
308 #[test]
309 fn step_field() {
310 // Every 15 minutes: matches :00 :15 :30 :45.
311 let s = CronSchedule::parse("*/15 * * * *").unwrap();
312 // 1767225600 = 2026-01-01T00:00:00Z (minute 0 → matches).
313 assert!(s.matches_unix(1_767_225_600));
314 // +15 min.
315 assert!(s.matches_unix(1_767_225_600 + 15 * 60));
316 // +7 min → minute 7, no match.
317 assert!(!s.matches_unix(1_767_225_600 + 7 * 60));
318 }
319
320 #[test]
321 fn range_and_list() {
322 let s = CronSchedule::parse("0 9-17 * * 1-5").unwrap();
323 // Hour 9-17, weekdays Mon-Fri, minute 0.
324 // 2026-01-05 is a Monday (1767571200 = 2026-01-05T00:00:00Z).
325 // 09:00 on that Monday:
326 let mon_9 = 1_767_603_600; // 2026-01-05T09:00:00Z
327 assert!(s.matches_unix(mon_9));
328 // 18:00 same day → hour 18 out of 9-17.
329 assert!(!s.matches_unix(mon_9 + 9 * 3600));
330 }
331
332 #[test]
333 fn dow_seven_is_sunday() {
334 let s7 = CronSchedule::parse("0 0 * * 7").unwrap();
335 let s0 = CronSchedule::parse("0 0 * * 0").unwrap();
336 // 2026-01-04 is a Sunday (1767484800 = 2026-01-04T00:00:00Z).
337 let sun = 1_767_484_800;
338 assert!(s7.matches_unix(sun));
339 assert!(s0.matches_unix(sun));
340 }
341
342 #[test]
343 fn dom_dow_or_rule() {
344 // "0 0 1 * 1" = midnight on the 1st OR on a Monday.
345 let s = CronSchedule::parse("0 0 1 * 1").unwrap();
346 // 2026-02-01 is a Sunday (the 1st, not a Monday).
347 // 1769904000 = 2026-02-01T00:00:00Z. Matches via day-of-month.
348 assert!(s.matches_unix(1_769_904_000));
349 // 2026-02-02 is a Monday (not the 1st). Matches via day-of-week.
350 assert!(s.matches_unix(1_769_904_000 + 86_400));
351 // 2026-02-03 is a Tuesday (not the 1st). No match.
352 assert!(!s.matches_unix(1_769_904_000 + 2 * 86_400));
353 }
354
355 #[test]
356 fn invalid_tokens_rejected() {
357 assert!(matches!(
358 CronSchedule::parse("60 * * * *"),
359 Err(CronParseError::Field { index: 0, .. })
360 ));
361 assert!(matches!(
362 CronSchedule::parse("* 24 * * *"),
363 Err(CronParseError::Field { index: 1, .. })
364 ));
365 assert!(matches!(
366 CronSchedule::parse("* * * * abc"),
367 Err(CronParseError::Field { index: 4, .. })
368 ));
369 // Zero step is invalid.
370 assert!(matches!(
371 CronSchedule::parse("*/0 * * * *"),
372 Err(CronParseError::Field { index: 0, .. })
373 ));
374 }
375}