1#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct CronFault {
18 pub field: &'static str,
21 pub reason: String,
23}
24
25impl CronFault {
26 fn new(field: &'static str, reason: impl Into<String>) -> Self {
27 Self {
28 field,
29 reason: reason.into(),
30 }
31 }
32
33 pub fn message(&self) -> String {
35 if self.field == "schedule" {
36 self.reason.clone()
37 } else {
38 format!("{}: {}", self.field, self.reason)
39 }
40 }
41}
42
43#[derive(Clone, Copy, PartialEq, Eq)]
44enum Kind {
45 Minute,
46 Hour,
47 DayOfMonth,
48 Month,
49 DayOfWeek,
50}
51
52impl Kind {
53 const ALL: [Kind; 5] = [
54 Kind::Minute,
55 Kind::Hour,
56 Kind::DayOfMonth,
57 Kind::Month,
58 Kind::DayOfWeek,
59 ];
60
61 fn name(self) -> &'static str {
62 match self {
63 Kind::Minute => "minute",
64 Kind::Hour => "hour",
65 Kind::DayOfMonth => "day of month",
66 Kind::Month => "month",
67 Kind::DayOfWeek => "day of week",
68 }
69 }
70
71 fn range(self) -> (u32, u32) {
72 match self {
73 Kind::Minute => (0, 59),
74 Kind::Hour => (0, 23),
75 Kind::DayOfMonth => (1, 31),
76 Kind::Month => (1, 12),
77 Kind::DayOfWeek => (1, 7),
78 }
79 }
80
81 fn names(self) -> &'static [&'static str] {
82 match self {
83 Kind::Month => &[
84 "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
85 ],
86 Kind::DayOfWeek => &["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"],
87 _ => &[],
88 }
89 }
90}
91
92pub fn is_cron_expression(s: &str) -> Result<(), CronFault> {
95 if s.is_empty() {
96 return Err(CronFault::new("schedule", "a schedule must not be empty"));
97 }
98 if s.starts_with(' ') || s.ends_with(' ') || s.contains(" ") || s.contains(['\t', '\n', '\r'])
99 {
100 return Err(CronFault::new(
101 "schedule",
102 "fields must be separated by exactly one space, with no leading or trailing space",
103 ));
104 }
105 if s.starts_with('@') {
106 return Err(CronFault::new(
107 "schedule",
108 "macros such as `@daily` are not supported; write the five fields",
109 ));
110 }
111 let fields: Vec<&str> = s.split(' ').collect();
112 if fields.len() != 5 {
113 return Err(CronFault::new(
114 "schedule",
115 format!(
116 "a schedule has exactly five fields (minute hour day-of-month month day-of-week), got {}",
117 fields.len()
118 ),
119 ));
120 }
121 for (kind, field) in Kind::ALL.iter().zip(&fields) {
122 check_field(*kind, field)?;
123 }
124 Ok(())
125}
126
127fn check_field(kind: Kind, field: &str) -> Result<(), CronFault> {
128 let name = kind.name();
129 if field.is_empty() {
130 return Err(CronFault::new(name, "is empty"));
131 }
132 for item in field.split(',') {
133 check_item(kind, item)?;
134 }
135 Ok(())
136}
137
138fn check_item(kind: Kind, item: &str) -> Result<(), CronFault> {
140 let name = kind.name();
141 if item.is_empty() {
142 return Err(CronFault::new(name, "has an empty list item"));
143 }
144 if item.contains('?') {
145 return Err(CronFault::new(name, "`?` is not supported; use `*`"));
146 }
147 let (lo, hi) = kind.range();
148 let (body, step) = match item.split_once('/') {
149 Some((b, st)) => (b, Some(st)),
150 None => (item, None),
151 };
152 if let Some(st) = step {
153 let n: u32 = st
154 .parse()
155 .map_err(|_| CronFault::new(name, format!("step `{st}` is not a number")))?;
156 if n < 1 {
157 return Err(CronFault::new(name, "a step must be at least 1"));
158 }
159 if n > hi {
160 return Err(CronFault::new(
161 name,
162 format!("step {n} is larger than the field's maximum {hi}"),
163 ));
164 }
165 }
166 if body == "*" {
167 return Ok(());
168 }
169 if let Some((a, b)) = body.split_once('-') {
170 let a = value(kind, a)?;
171 let b = value(kind, b)?;
172 if a > b {
173 return Err(CronFault::new(
174 name,
175 format!("range runs high to low ({a}-{b}); a range must run low to high"),
176 ));
177 }
178 return Ok(());
179 }
180 if step.is_some() {
181 return Err(CronFault::new(
183 name,
184 "a step applies to `*` or a range (`*/5`, `0-30/5`)",
185 ));
186 }
187 special_or_value(kind, body, lo, hi)
188}
189
190fn special_or_value(kind: Kind, body: &str, lo: u32, hi: u32) -> Result<(), CronFault> {
192 let name = kind.name();
193 match kind {
194 Kind::DayOfMonth => {
195 if body == "L" || body == "LW" {
196 return Ok(());
197 }
198 if let Some(n) = body.strip_suffix('W') {
199 let v = number(kind, n)?;
200 return in_range(kind, v);
201 }
202 }
203 Kind::DayOfWeek => {
204 if let Some((d, nth)) = body.split_once('#') {
205 let v = value(kind, d)?;
206 let _ = v;
207 let nth: u32 = nth
208 .parse()
209 .map_err(|_| CronFault::new(name, format!("`#{nth}` is not a number")))?;
210 if !(1..=5).contains(&nth) {
211 return Err(CronFault::new(
212 name,
213 format!("`#{nth}` is outside 1-5 (the nth weekday of the month)"),
214 ));
215 }
216 return Ok(());
217 }
218 if let Some(d) = strip_suffix_ci(body, 'L') {
219 if d.is_empty() {
222 return Err(CronFault::new(
223 name,
224 "`L` needs a weekday before it (`6L`, `FRIL`)",
225 ));
226 }
227 value(kind, d)?;
228 return Ok(());
229 }
230 }
231 _ => {}
232 }
233 let _ = (lo, hi);
234 value(kind, body).map(|_| ())
235}
236
237fn strip_suffix_ci(s: &str, c: char) -> Option<&str> {
238 let last = s.chars().last()?;
239 if last.eq_ignore_ascii_case(&c) {
240 Some(&s[..s.len() - last.len_utf8()])
241 } else {
242 None
243 }
244}
245
246fn number(kind: Kind, text: &str) -> Result<u32, CronFault> {
247 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
248 return Err(CronFault::new(
249 kind.name(),
250 format!("`{text}` is not a valid value"),
251 ));
252 }
253 text.parse::<u32>()
254 .map_err(|_| CronFault::new(kind.name(), format!("`{text}` is out of range")))
255}
256
257fn in_range(kind: Kind, v: u32) -> Result<(), CronFault> {
258 let (lo, hi) = kind.range();
259 if (lo..=hi).contains(&v) {
260 Ok(())
261 } else {
262 Err(CronFault::new(
263 kind.name(),
264 format!("{v} is outside {lo}-{hi}"),
265 ))
266 }
267}
268
269fn value(kind: Kind, text: &str) -> Result<u32, CronFault> {
271 if let Some(i) = kind
272 .names()
273 .iter()
274 .position(|n| n.eq_ignore_ascii_case(text))
275 {
276 let (lo, _) = kind.range();
277 return Ok(lo + i as u32);
278 }
279 let v = number(kind, text)?;
280 in_range(kind, v)?;
281 Ok(v)
282}
283
284fn fields_of(s: &str) -> Option<Vec<&str>> {
287 let f: Vec<&str> = s.split(' ').collect();
288 (f.len() == 5).then_some(f)
289}
290
291pub fn numeric_weekday(s: &str) -> bool {
294 let Some(f) = fields_of(s) else { return false };
295 let dow = f[4];
296 dow.split(',').any(|item| {
299 let body = item.split('/').next().unwrap_or("");
300 body.split('-').any(|p| {
301 p.trim_end_matches(['L', 'l'])
302 .split('#')
303 .next()
304 .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
305 })
306 })
307}
308
309pub fn uneven_step(s: &str) -> Option<String> {
312 let f = fields_of(s)?;
313 for (field, kind, size) in [(f[0], Kind::Minute, 60u32), (f[1], Kind::Hour, 24u32)] {
314 for item in field.split(',') {
315 let Some(n) = item.strip_prefix("*/").and_then(|n| n.parse::<u32>().ok()) else {
316 continue;
317 };
318 if n >= 1 && size % n != 0 {
319 let fires: Vec<String> = (0..size)
320 .step_by(n as usize)
321 .map(|v| v.to_string())
322 .collect();
323 return Some(format!(
324 "`*/{n}` in the {} field fires at {} and then restarts at 0 at the next {}, so the last gap is shorter than {n}",
325 kind.name(),
326 fires.join(", "),
327 if kind == Kind::Minute { "hour" } else { "day" },
328 ));
329 }
330 }
331 }
332 None
333}
334
335pub fn describe_fields(s: &str) -> Option<Vec<(&'static str, String)>> {
339 is_cron_expression(s).ok()?;
340 Some(
341 Kind::ALL
342 .iter()
343 .zip(s.split(' '))
344 .map(|(k, f)| (k.name(), f.to_string()))
345 .collect(),
346 )
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 fn ok(s: &str) {
354 assert_eq!(is_cron_expression(s), Ok(()), "{s:?} should be admitted");
355 }
356 fn bad(s: &str, field: &str) {
357 let e = is_cron_expression(s).expect_err(s);
358 assert_eq!(e.field, field, "{s:?}: {e:?}");
359 }
360
361 #[test]
362 fn admits_every_example_on_cloudflares_page() {
363 for s in [
364 "* * * * *",
365 "0 18 * * 6L",
366 "0 18 * * friL",
367 "59 23 LW * *",
368 "*/45 * * * *",
369 "0 2 * * MON-FRI",
370 "0 2 * * mon-fri",
371 "0 0 1,15 JAN,jul *",
372 "0 */6 * * *",
373 "5-10/2 * * * *",
374 "0 0 15W * *",
375 "0 0 L * *",
376 "0 0 * * 6#2",
377 ] {
378 ok(s);
379 }
380 }
381
382 #[test]
383 fn refuses_each_malformed_schedule_naming_the_field() {
384 bad("61 * * * *", "minute");
385 bad("* * * * 0", "day of week");
386 bad("* * * * 8", "day of week");
387 bad("5-1 * * * *", "minute");
388 bad("*/0 * * * *", "minute");
389 bad("? * * * *", "minute");
390 bad("@daily", "schedule");
391 bad("0 0 * * * *", "schedule");
392 bad("* * * *", "schedule");
393 bad("* 24 * * *", "hour");
394 bad("* * 0 * *", "day of month");
395 bad("* * 32 * *", "day of month");
396 bad("* * * 13 *", "month");
397 bad("* * * FOO *", "month");
398 bad("* * * * L", "day of week");
399 bad("* * * * 1#6", "day of week");
400 }
401
402 #[test]
403 fn refuses_irregular_whitespace() {
404 for s in ["0 2 * * *", "0\t2 * * *", "0 2 * * * ", " 0 2 * * *"] {
405 bad(s, "schedule");
406 }
407 }
408
409 #[test]
410 fn the_warnings() {
411 assert!(numeric_weekday("* * * * 5"));
412 assert!(numeric_weekday("* * * * 1-5"));
413 assert!(!numeric_weekday("* * * * FRI"));
414 assert!(!numeric_weekday("* * * * *"));
415 assert!(!numeric_weekday("* * * * */2"));
416 assert!(uneven_step("*/45 * * * *").is_some());
417 assert!(uneven_step("*/15 * * * *").is_none());
418 assert!(uneven_step("0 */5 * * *").is_some());
419 assert!(uneven_step("0 */6 * * *").is_none());
420 }
421}
422
423#[cfg(test)]
430mod corpus {
431 use super::*;
432
433 const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/cron_corpus.tsv");
434
435 fn generate() -> String {
436 let mut seed: u64 = 3873;
437 let mut next = move || {
438 seed = seed
439 .wrapping_mul(6364136223846793005)
440 .wrapping_add(1442695040888963407);
441 (seed >> 33) as usize
442 };
443 let atoms = [
444 "*", "*/5", "*/0", "*/45", "*/60", "0", "1", "5", "7", "8", "12", "13", "23", "24",
445 "31", "32", "59", "60", "0-5", "5-1", "1-7", "MON", "mon", "FRI", "JAN", "dec", "FOO",
446 "MON-FRI", "FRI-MON", "6L", "friL", "L", "LW", "15W", "0W", "6#2", "1#6", "?", "5/10",
447 "1,2", "1,", ",1", "0-30/5", "1-7/2", "*/", "-", "1-", "",
448 ];
449 let per_field: [&[&str]; 5] = [
450 &[
451 "*", "*/5", "*/15", "*/45", "0", "30", "59", "0-30", "5,10", "0-30/5",
452 ],
453 &["*", "*/6", "*/5", "0", "12", "23", "9-17", "0,12"],
454 &[
455 "*", "1", "15", "31", "L", "LW", "15W", "1-15", "*/2", "1,15",
456 ],
457 &["*", "1", "12", "JAN", "dec", "Jun", "JAN-MAR", "*/3", "1,6"],
458 &[
459 "*", "1", "7", "MON", "fri", "MON-FRI", "6L", "friL", "2#3", "1-5", "SUN,SAT",
460 ],
461 ];
462 let mut out = String::new();
463 let mut seen = std::collections::BTreeSet::new();
464 let mut push = |s: String, out: &mut String| {
465 if seen.insert(s.clone()) {
466 let verdict = if is_cron_expression(&s).is_ok() {
467 "ok"
468 } else {
469 "bad"
470 };
471 out.push_str(verdict);
472 out.push('\t');
473 out.push_str(&serde_json_string(&s));
474 out.push('\n');
475 }
476 };
477 for s in [
478 "* * * * *",
479 "0 18 * * 6L",
480 "0 18 * * friL",
481 "59 23 LW * *",
482 "@daily",
483 "0 0 * * * *",
484 "* * * *",
485 "",
486 " ",
487 "0 2 * * *",
488 "0\t2 * * *",
489 "0 2 * * * ",
490 " 0 2 * * *",
491 ] {
492 push(s.to_string(), &mut out);
493 }
494 for _ in 0..6000 {
495 let n = if next() % 20 == 0 { 4 + next() % 3 } else { 5 };
496 let fields: Vec<&str> = (0..n)
499 .map(|i| {
500 if next() % 6 == 0 || i >= 5 {
501 atoms[next() % atoms.len()]
502 } else {
503 let own = per_field[i];
504 own[next() % own.len()]
505 }
506 })
507 .collect();
508 let sep = if next() % 40 == 0 { " " } else { " " };
509 push(fields.join(sep), &mut out);
510 }
511 out
512 }
513
514 fn serde_json_string(s: &str) -> String {
515 let mut o = String::from("\"");
516 for c in s.chars() {
517 match c {
518 '"' => o.push_str("\\\""),
519 '\\' => o.push_str("\\\\"),
520 '\t' => o.push_str("\\t"),
521 '\n' => o.push_str("\\n"),
522 '\r' => o.push_str("\\r"),
523 c => o.push(c),
524 }
525 }
526 o.push('"');
527 o
528 }
529
530 #[test]
531 fn corpus_is_current() {
532 let want = generate();
533 if std::env::var("BYNK_BLESS").is_ok() {
534 std::fs::write(PATH, &want).unwrap();
535 }
536 let have = std::fs::read_to_string(PATH).unwrap_or_default();
537 assert!(
538 have == want,
539 "bynk-syntax/tests/cron_corpus.tsv is stale; regenerate with BYNK_BLESS=1 cargo test -p bynk-syntax cron"
540 );
541 assert!(want.contains("ok\t") && want.contains("bad\t"));
542 }
543}