| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Cron trigger schedules, reified sans-IO. |
| 4 | //! |
| 5 | //! A `triggers.crons` entry in the Wrangler config becomes one reserved cell |
| 6 | //! whose alarm is armed at the next occurrence. Everything about *when* that |
| 7 | //! is — parsing the expression, walking to the next minute, choosing between |
| 8 | //! a retry and the next occurrence — is a pure function of the expression and |
| 9 | //! a timestamp. The cell and its alarm row are the executor. |
| 10 | //! |
| 11 | //! Resolution is one minute and the zone is UTC, matching both Cloudflare's |
| 12 | //! cron triggers and the minute buckets the wake index already uses |
| 13 | //! (`wake::entry_key`). The schedule is therefore never more precise than the |
| 14 | //! alarm that carries it. |
| 15 | //! |
| 16 | //! The dialect is Cloudflare's, read out of `saffron` (the parser behind Cron |
| 17 | //! Triggers) rather than out of a POSIX cron manual, because the two disagree |
| 18 | //! on the day-of-week numbers and silence is the worst way to find that out. |
| 19 | //! Cloudflare numbers the weekdays 1 to 7 from Sunday and rejects 0, so `1-5` |
| 20 | //! is Sunday to Thursday there and Monday to Friday in Vixie cron. Two places |
| 21 | //! where `saffron` contradicts its own comments are called out at the code that |
| 22 | //! declines to copy them. |
| 23 | |
| 24 | use crate::wake::civil_from_days; |
| 25 | use crate::Ms; |
| 26 | |
| 27 | /// The class name of the reserved cell that carries a script's schedule. |
| 28 | /// |
| 29 | /// A leading `.` is inside `cell::valid_cell_scope`'s charset but is not a |
| 30 | /// legal start for a JavaScript identifier, so no exported class can collide |
| 31 | /// with the reserved namespace. That is the whole reason the name is punctuated |
| 32 | /// rather than pretty. |
| 33 | pub const RESERVED_CLASS: &str = ".cron"; |
| 34 | |
| 35 | /// The one cell that owns a script's cron schedule. |
| 36 | /// |
| 37 | /// Keyed on the script and nothing else — not the expressions, not a hash of |
| 38 | /// them. Ownership CAS on this one name is what makes a cron fire once per |
| 39 | /// fleet rather than once per node, and a stable name is what lets a deploy |
| 40 | /// change the schedule without stranding the alarm the old schedule armed. |
| 41 | pub fn reserved_cell(script_name: &str) -> String { |
| 42 | format!("{RESERVED_CLASS}:{script_name}") |
| 43 | } |
| 44 | |
| 45 | /// How far ahead `next_after` walks before it calls an expression |
| 46 | /// unsatisfiable. |
| 47 | /// |
| 48 | /// One Gregorian cycle. The calendar repeats exactly every 400 years, so a walk |
| 49 | /// of 146097 consecutive days sees every (month, day-of-month, day-of-week) |
| 50 | /// combination that can ever occur: an expression with no match in that window |
| 51 | /// has none at all, and the bound is a proof rather than an estimate. Estimates |
| 52 | /// were tried and were wrong twice over — `0 0 29 2 *` waits eight years, not |
| 53 | /// four, when a century skips its leap year (2096-02-29 to 2104-02-29 is 2921 |
| 54 | /// days), and `0 0 * 2 SUN#5` needs a 29-day February that starts on a Sunday, |
| 55 | /// which is 28 years apart. Undershooting is not a late fire but a silent |
| 56 | /// retirement: `next_across` returns `None`, so the cell deletes its alarm. The |
| 57 | /// full walk costs about a hundred thousand cheap iterations and only an |
| 58 | /// unsatisfiable expression ever pays it, once, at arm time. |
| 59 | const MAX_LOOKAHEAD_DAYS: usize = 146_097; |
| 60 | |
| 61 | const MINUTE: Field = Field { |
| 62 | name: "minute", |
| 63 | min: 0, |
| 64 | max: 59, |
| 65 | names: &[], |
| 66 | }; |
| 67 | const HOUR: Field = Field { |
| 68 | name: "hour", |
| 69 | min: 0, |
| 70 | max: 23, |
| 71 | names: &[], |
| 72 | }; |
| 73 | const DAY_OF_MONTH: Field = Field { |
| 74 | name: "day of month", |
| 75 | min: 1, |
| 76 | max: 31, |
| 77 | names: &[], |
| 78 | }; |
| 79 | const MONTH: Field = Field { |
| 80 | name: "month", |
| 81 | min: 1, |
| 82 | max: 12, |
| 83 | names: &[ |
| 84 | "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", |
| 85 | ], |
| 86 | }; |
| 87 | /// Cloudflare numbers the weekdays 1 to 7 from Sunday, so 1 is Sunday and 7 is |
| 88 | /// Saturday, and 0 is out of range. Vixie cron numbers them 0 to 6 from Sunday |
| 89 | /// and accepts 7 as Sunday again, which makes the same expression name a |
| 90 | /// different day on the two platforms. Cloudflare documents its choice, and a |
| 91 | /// value here is therefore the Cloudflare number minus one: the bit sets below |
| 92 | /// are indexed by weekday with Sunday at 0. |
| 93 | const DAY_OF_WEEK: Field = Field { |
| 94 | name: "day of week", |
| 95 | min: 1, |
| 96 | max: 7, |
| 97 | names: &["sun", "mon", "tue", "wed", "thu", "fri", "sat"], |
| 98 | }; |
| 99 | |
| 100 | /// One field's shape: its bounds and the three-letter aliases it accepts. |
| 101 | struct Field { |
| 102 | name: &'static str, |
| 103 | min: u32, |
| 104 | max: u32, |
| 105 | /// Aliases in ascending order starting at `min`. |
| 106 | names: &'static [&'static str], |
| 107 | } |
| 108 | |
| 109 | /// A parsed five-field cron expression, as bit sets. |
| 110 | /// |
| 111 | /// The original text is kept because the `scheduled` handler's controller |
| 112 | /// reports which expression fired, and it must be the string the developer |
| 113 | /// wrote rather than a re-rendering of these bits. |
| 114 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 115 | pub struct Cron { |
| 116 | text: String, |
| 117 | minute: u64, |
| 118 | hour: u32, |
| 119 | month: u16, |
| 120 | day_of_month: DayOfMonth, |
| 121 | day_of_week: DayOfWeek, |
| 122 | } |
| 123 | |
| 124 | /// The day-of-month field. `All` is its own variant because the day rule turns |
| 125 | /// on whether the field was written `*`, which a bit set cannot say: a field |
| 126 | /// listing every day is indistinguishable from `*` once expanded. The `L` and |
| 127 | /// `W` variants cannot be expressed as a bit set at all, because which day they |
| 128 | /// name depends on the month. |
| 129 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 130 | enum DayOfMonth { |
| 131 | /// `*` |
| 132 | All, |
| 133 | /// A list, range, or step: bit `d` set for day `d`. |
| 134 | Days(u32), |
| 135 | /// `L` — the last day of the month. |
| 136 | Last, |
| 137 | /// `L-<n>` — `n` days before the last day. |
| 138 | LastOffset(u32), |
| 139 | /// `LW` — the last weekday of the month. |
| 140 | LastWeekday, |
| 141 | /// `L-<n>W` — the weekday closest to `n` days before the last day. |
| 142 | LastOffsetWeekday(u32), |
| 143 | /// `<d>W` — the weekday closest to day `d`, inside the same month. |
| 144 | ClosestWeekday(u32), |
| 145 | } |
| 146 | |
| 147 | /// The day-of-week field, with Sunday at bit 0 whatever number named it. |
| 148 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 149 | enum DayOfWeek { |
| 150 | /// `*` |
| 151 | All, |
| 152 | /// A list, range, or step: bit `w` set for weekday `w`, Sunday at 0. |
| 153 | Days(u8), |
| 154 | /// `<dow>L` — the last such weekday of the month. |
| 155 | Last(u32), |
| 156 | /// `<dow>#<n>` — the nth such weekday of the month. |
| 157 | Nth(u32, u32), |
| 158 | } |
| 159 | |
| 160 | impl Cron { |
| 161 | /// The expression as the developer wrote it. |
| 162 | pub fn text(&self) -> &str { |
| 163 | &self.text |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// Why an expression was refused, naming the field at fault so a deploy can |
| 168 | /// report which of several crons is wrong. |
| 169 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 170 | pub struct CronError { |
| 171 | pub expression: String, |
| 172 | pub message: String, |
| 173 | } |
| 174 | |
| 175 | impl std::fmt::Display for CronError { |
| 176 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 177 | write!(f, "cron expression {:?}: {}", self.expression, self.message) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | impl std::error::Error for CronError {} |
| 182 | |
| 183 | /// Parse a five-field cron expression: minute, hour, day of month, month, day |
| 184 | /// of week. Each field takes `*`, a value, an `a-b` range, an `a,b` list, and a |
| 185 | /// `/n` step on any of those. Month and day-of-week also take the usual |
| 186 | /// three-letter names, case-insensitively. The day fields take Cloudflare's |
| 187 | /// `L`, `W`, and `#` on top of that. |
| 188 | /// |
| 189 | /// `?` is refused, as Cloudflare refuses it: its parser has no case for the |
| 190 | /// character, so an expression that uses it fails there too. |
| 191 | pub fn parse(expression: &str) -> Result<Cron, CronError> { |
| 192 | let fail = |message: String| CronError { |
| 193 | expression: expression.to_string(), |
| 194 | message, |
| 195 | }; |
| 196 | let fields: Vec<&str> = expression.split_whitespace().collect(); |
| 197 | if fields.len() != 5 { |
| 198 | return Err(fail(format!( |
| 199 | "expected 5 fields (minute hour day-of-month month day-of-week), found {}", |
| 200 | fields.len() |
| 201 | ))); |
| 202 | } |
| 203 | let minute = parse_field(fields[0], &MINUTE).map_err(&fail)?; |
| 204 | let hour = parse_field(fields[1], &HOUR).map_err(&fail)?; |
| 205 | let day_of_month = parse_day_of_month(fields[2]).map_err(&fail)?; |
| 206 | let month = parse_field(fields[3], &MONTH).map_err(&fail)?; |
| 207 | let day_of_week = parse_day_of_week(fields[4]).map_err(&fail)?; |
| 208 | Ok(Cron { |
| 209 | text: expression.trim().to_string(), |
| 210 | minute, |
| 211 | hour: hour as u32, |
| 212 | month: month as u16, |
| 213 | day_of_month, |
| 214 | day_of_week, |
| 215 | }) |
| 216 | } |
| 217 | |
| 218 | /// The day-of-month field, including the `L` and `W` forms. |
| 219 | /// |
| 220 | /// An `L` or `W` form stands alone. Cloudflare's parser stops after reading one |
| 221 | /// and never looks for a comma, so `1W,15` fails there; refusing it here keeps |
| 222 | /// the two answers the same instead of inventing a union it cannot express. |
| 223 | fn parse_day_of_month(text: &str) -> Result<DayOfMonth, String> { |
| 224 | if text == "*" { |
| 225 | return Ok(DayOfMonth::All); |
| 226 | } |
| 227 | if let Some(rest) = text.strip_prefix('L') { |
| 228 | return match rest { |
| 229 | "" => Ok(DayOfMonth::Last), |
| 230 | "W" => Ok(DayOfMonth::LastWeekday), |
| 231 | _ => { |
| 232 | let (digits, weekday) = match rest.strip_suffix('W') { |
| 233 | Some(digits) => (digits, true), |
| 234 | None => (rest, false), |
| 235 | }; |
| 236 | let offset = digits.strip_prefix('-').ok_or_else(|| { |
| 237 | format!("day of month field has an unreadable `L` form in {text:?}") |
| 238 | })?; |
| 239 | // Cloudflare allows 1 to 30: 30 is one short of the longest |
| 240 | // month, so `L-30` is the 1st of a 31-day month, and 0 is out |
| 241 | // of range rather than a spelling of `L`. Accepting 0 would |
| 242 | // also make `L-0W` a different rule from `LW`, because the |
| 243 | // offset arms cannot move to the Friday before a month that |
| 244 | // ends on a weekend. |
| 245 | let offset = parse_digits(offset).ok_or_else(|| { |
| 246 | format!("day of month field has a non-numeric `L` offset in {text:?}") |
| 247 | })?; |
| 248 | if !(1..=30).contains(&offset) { |
| 249 | return Err(format!( |
| 250 | "day of month field has an `L` offset {offset} outside 1-30" |
| 251 | )); |
| 252 | } |
| 253 | if weekday { |
| 254 | Ok(DayOfMonth::LastOffsetWeekday(offset)) |
| 255 | } else { |
| 256 | Ok(DayOfMonth::LastOffset(offset)) |
| 257 | } |
| 258 | } |
| 259 | }; |
| 260 | } |
| 261 | if let Some(day) = text.strip_suffix('W') { |
| 262 | return Ok(DayOfMonth::ClosestWeekday(parse_value(day, &DAY_OF_MONTH)?)); |
| 263 | } |
| 264 | Ok(DayOfMonth::Days(parse_field(text, &DAY_OF_MONTH)? as u32)) |
| 265 | } |
| 266 | |
| 267 | /// The day-of-week field, including the `L` and `#` forms. |
| 268 | /// |
| 269 | /// `L` on its own is Saturday, which reads like a typo and is not: Cloudflare's |
| 270 | /// parser maps a bare `L` in this field to day 7, and 7 is Saturday under its |
| 271 | /// numbering. |
| 272 | fn parse_day_of_week(text: &str) -> Result<DayOfWeek, String> { |
| 273 | if text == "*" { |
| 274 | return Ok(DayOfWeek::All); |
| 275 | } |
| 276 | if text == "L" { |
| 277 | return Ok(DayOfWeek::Days(1 << 6)); |
| 278 | } |
| 279 | if let Some(day) = text.strip_suffix('L') { |
| 280 | return Ok(DayOfWeek::Last(parse_value(day, &DAY_OF_WEEK)? - 1)); |
| 281 | } |
| 282 | if let Some((day, nth)) = text.split_once('#') { |
| 283 | let day = parse_value(day, &DAY_OF_WEEK)? - 1; |
| 284 | let nth = parse_digits(nth) |
| 285 | .ok_or_else(|| format!("day of week field has a non-numeric `#` count in {text:?}"))?; |
| 286 | if !(1..=5).contains(&nth) { |
| 287 | return Err(format!( |
| 288 | "day of week field has a `#` count {nth} outside 1-5" |
| 289 | )); |
| 290 | } |
| 291 | return Ok(DayOfWeek::Nth(day, nth)); |
| 292 | } |
| 293 | // Parsed in Cloudflare's 1-7 numbering and shifted down, so a range keeps |
| 294 | // its meaning: `2-6` is bits 2 to 6 before the shift and Monday to Friday |
| 295 | // after it. |
| 296 | Ok(DayOfWeek::Days( |
| 297 | (parse_field(text, &DAY_OF_WEEK)? >> 1) as u8, |
| 298 | )) |
| 299 | } |
| 300 | |
| 301 | /// One field to a bit set, bit `v` set when value `v` matches. |
| 302 | fn parse_field(text: &str, field: &Field) -> Result<u64, String> { |
| 303 | if text.is_empty() { |
| 304 | return Err(format!("{} field is empty", field.name)); |
| 305 | } |
| 306 | let mut bits = 0_u64; |
| 307 | let items: Vec<&str> = text.split(',').collect(); |
| 308 | for item in &items { |
| 309 | // A bare `*` inside a list is refused, wherever in the list it sits. |
| 310 | // Cloudflare rejects `*,5` outright — its parser returns on the first |
| 311 | // `*` and then fails on the unread remainder — and accepts `1,*` while |
| 312 | // reading that `*` as the field's minimum, so `1,*` is minute 0 and |
| 313 | // minute 1 there. Both follow from one parsing routine being reused and |
| 314 | // not from any intent, and reading either as "every value" would fire a |
| 315 | // handler sixty times where Cloudflare fires it twice. Neither answer |
| 316 | // can be defended, so the deploy stops where the developer can read it. |
| 317 | if items.len() > 1 && item.trim() == "*" { |
| 318 | return Err(format!( |
| 319 | "{} field has a `*` inside a list in {text:?}; write `*` alone, or list the values", |
| 320 | field.name |
| 321 | )); |
| 322 | } |
| 323 | bits |= parse_item(item, field)?; |
| 324 | } |
| 325 | Ok(bits) |
| 326 | } |
| 327 | |
| 328 | fn parse_item(item: &str, field: &Field) -> Result<u64, String> { |
| 329 | let (spec, step) = match item.split_once('/') { |
| 330 | None => (item, 1_u32), |
| 331 | Some((spec, step)) => { |
| 332 | let step = parse_digits(step).ok_or_else(|| { |
| 333 | format!("{} field has a non-numeric step in {item:?}", field.name) |
| 334 | })?; |
| 335 | // Cloudflare bounds a step by the width of its field, so `*/60` is |
| 336 | // refused for minutes rather than read as "every hour". A step at |
| 337 | // or past the width can only ever set the value it starts from, |
| 338 | // which is what the developer did not write. |
| 339 | if step == 0 || step > field.max - field.min { |
| 340 | return Err(format!( |
| 341 | "{} field has a step {step} outside 1-{} in {item:?}", |
| 342 | field.name, |
| 343 | field.max - field.min |
| 344 | )); |
| 345 | } |
| 346 | (spec, step) |
| 347 | } |
| 348 | }; |
| 349 | // A step with no explicit end runs to the field's maximum, so `*/15` and |
| 350 | // `30/15` differ only in where they start. |
| 351 | let (first, last) = match spec { |
| 352 | "*" => (field.min, field.max), |
| 353 | _ => match spec.split_once('-') { |
| 354 | Some((from, to)) => (parse_value(from, field)?, parse_value(to, field)?), |
| 355 | None => { |
| 356 | let value = parse_value(spec, field)?; |
| 357 | if step == 1 { |
| 358 | (value, value) |
| 359 | } else { |
| 360 | (value, field.max) |
| 361 | } |
| 362 | } |
| 363 | }, |
| 364 | }; |
| 365 | // A descending range is refused, and this is the one place celld declines |
| 366 | // to follow Cloudflare. Cloudflare accepts it and wraps around the end of |
| 367 | // the field for Quartz's sake, but takes one value too many at the low end: |
| 368 | // `SAT-SUN` matches Friday there and `NOV-FEB` matches October, which |
| 369 | // contradicts the worked example in saffron's own comment. Copying that |
| 370 | // ships a schedule known to fire on a day nobody asked for, and correcting |
| 371 | // it silently means the same expression means two things. Refusing stops |
| 372 | // the deploy where the developer is watching instead. |
| 373 | if first > last { |
| 374 | return Err(format!( |
| 375 | "{} field has a descending range in {item:?}; celld does not wrap a range around the end of a field", |
| 376 | field.name |
| 377 | )); |
| 378 | } |
| 379 | let mut bits = 0_u64; |
| 380 | let mut value = first; |
| 381 | while value <= last { |
| 382 | bits |= 1 << value; |
| 383 | value += step; |
| 384 | } |
| 385 | Ok(bits) |
| 386 | } |
| 387 | |
| 388 | /// A run of ASCII digits and nothing else. |
| 389 | /// |
| 390 | /// `str::parse` accepts a leading `+`, and Cloudflare's parser reads digits |
| 391 | /// only, so `0 0 * * +2` deploys here and fails there. Every number in an |
| 392 | /// expression goes through this. |
| 393 | fn parse_digits(text: &str) -> Option<u32> { |
| 394 | if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { |
| 395 | return None; |
| 396 | } |
| 397 | text.parse().ok() |
| 398 | } |
| 399 | |
| 400 | fn parse_value(text: &str, field: &Field) -> Result<u32, String> { |
| 401 | let text = text.trim(); |
| 402 | let lower = text.to_ascii_lowercase(); |
| 403 | if let Some(index) = field.names.iter().position(|name| *name == lower) { |
| 404 | return Ok(field.min + index as u32); |
| 405 | } |
| 406 | let value = parse_digits(text).ok_or_else(|| { |
| 407 | if field.names.is_empty() { |
| 408 | format!("{} field has a non-numeric value {text:?}", field.name) |
| 409 | } else { |
| 410 | format!( |
| 411 | "{} field has a value {text:?} that is neither a number nor a name", |
| 412 | field.name |
| 413 | ) |
| 414 | } |
| 415 | })?; |
| 416 | if value < field.min || value > field.max { |
| 417 | return Err(format!( |
| 418 | "{} field has {value} outside {}-{}", |
| 419 | field.name, field.min, field.max |
| 420 | )); |
| 421 | } |
| 422 | Ok(value) |
| 423 | } |
| 424 | |
| 425 | /// Does this expression match the minute containing `at_ms`? |
| 426 | pub fn matches(cron: &Cron, at_ms: Ms) -> bool { |
| 427 | let minutes = at_ms.div_euclid(60_000); |
| 428 | let day = minutes.div_euclid(1440); |
| 429 | let time = minutes.rem_euclid(1440); |
| 430 | day_matches(cron, day) |
| 431 | && cron.hour & (1 << (time / 60)) != 0 |
| 432 | && cron.minute & (1 << (time % 60)) != 0 |
| 433 | } |
| 434 | |
| 435 | /// The day rule: with both day fields restricted a day matches when *either* |
| 436 | /// does, so `0 0 1 * MON` is the first of the month and every Monday. With one |
| 437 | /// field restricted, only that one decides. A field counts as restricted unless |
| 438 | /// it is literally `*`, so `*/2` is restricted and joins the union — the rule |
| 439 | /// Cloudflare applies, and not Vixie's, which reads the field's first character |
| 440 | /// and would call `*/2` unrestricted. |
| 441 | fn day_matches(cron: &Cron, day: i64) -> bool { |
| 442 | let (year, month, day_of_month) = civil_from_days(day); |
| 443 | if cron.month & (1 << month) == 0 { |
| 444 | return false; |
| 445 | } |
| 446 | // 1970-01-01 was a Thursday, and Sunday is 0. |
| 447 | let day_of_week = (day + 4).rem_euclid(7) as u32; |
| 448 | let last = days_in_month(year, month); |
| 449 | let by_dom = day_of_month_matches(&cron.day_of_month, day_of_month, day_of_week, last); |
| 450 | let by_dow = day_of_week_matches(&cron.day_of_week, day_of_month, day_of_week, last); |
| 451 | match ( |
| 452 | cron.day_of_month == DayOfMonth::All, |
| 453 | cron.day_of_week == DayOfWeek::All, |
| 454 | ) { |
| 455 | (true, true) => true, |
| 456 | (false, true) => by_dom, |
| 457 | (true, false) => by_dow, |
| 458 | (false, false) => by_dom || by_dow, |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /// Saturday and Sunday. `W` moves off these two and onto the nearest of the |
| 463 | /// other five, which is the whole content of the character. |
| 464 | fn is_weekend(day_of_week: u32) -> bool { |
| 465 | day_of_week == 0 || day_of_week == 6 |
| 466 | } |
| 467 | |
| 468 | fn days_in_month(year: i64, month: u32) -> u32 { |
| 469 | match month { |
| 470 | 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, |
| 471 | 4 | 6 | 9 | 11 => 30, |
| 472 | _ => { |
| 473 | let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); |
| 474 | if leap { |
| 475 | 29 |
| 476 | } else { |
| 477 | 28 |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// Each `W` arm below is Cloudflare's, condition for condition. `W` never |
| 484 | /// leaves the month: the day it names moves back to Friday or forward to |
| 485 | /// Monday, and the arms that look redundant are the ones that catch a month |
| 486 | /// which begins or ends on a weekend. |
| 487 | fn day_of_month_matches(field: &DayOfMonth, day: u32, weekday: u32, last: u32) -> bool { |
| 488 | match *field { |
| 489 | DayOfMonth::All => true, |
| 490 | DayOfMonth::Days(days) => days & (1 << day) != 0, |
| 491 | DayOfMonth::Last => day == last, |
| 492 | DayOfMonth::LastOffset(offset) => day + offset == last, |
| 493 | DayOfMonth::LastWeekday => { |
| 494 | (!is_weekend(weekday) && day == last) || (weekday == 5 && last - day < 3) |
| 495 | } |
| 496 | DayOfMonth::LastOffsetWeekday(offset) => { |
| 497 | let target = day + offset; |
| 498 | (!is_weekend(weekday) && target == last) |
| 499 | || (weekday == 1 && target > last && target - last < 3) |
| 500 | || (weekday == 5 && target + 1 == last) |
| 501 | } |
| 502 | DayOfMonth::ClosestWeekday(target) => { |
| 503 | (!is_weekend(weekday) && day == target) |
| 504 | || (weekday == 1 && day > 1 && day - 1 == target) |
| 505 | // The 1st falls on a Saturday and the 2nd on a Sunday, so the |
| 506 | // nearest weekday inside the month is Monday the 3rd. |
| 507 | || (weekday == 1 && day == 3 && target == 1) |
| 508 | || (weekday == 5 && day + 1 == target) |
| 509 | // The target is the last day of the month and falls on a |
| 510 | // Sunday, so the move back is two days rather than one. |
| 511 | || (weekday == 5 && day + 2 == target && target == last) |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | fn day_of_week_matches(field: &DayOfWeek, day: u32, weekday: u32, last: u32) -> bool { |
| 517 | match *field { |
| 518 | DayOfWeek::All => true, |
| 519 | DayOfWeek::Days(days) => days & (1 << weekday) != 0, |
| 520 | DayOfWeek::Last(wanted) => weekday == wanted && day + 7 > last, |
| 521 | DayOfWeek::Nth(wanted, nth) => weekday == wanted && (day - 1) / 7 + 1 == nth, |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | /// The first occurrence strictly after `after_ms`, or `None` when the |
| 526 | /// expression cannot match within [`MAX_LOOKAHEAD_DAYS`]. |
| 527 | /// |
| 528 | /// Strictly after is what makes a re-arm from inside the handler terminate: an |
| 529 | /// occurrence that returned itself would arm an alarm already due and spin. |
| 530 | pub fn next_after(cron: &Cron, after_ms: Ms) -> Option<Ms> { |
| 531 | let start = after_ms.div_euclid(60_000) + 1; |
| 532 | let mut time = start.rem_euclid(1440); |
| 533 | for day in (start.div_euclid(1440)..).take(MAX_LOOKAHEAD_DAYS) { |
| 534 | if day_matches(cron, day) { |
| 535 | if let Some(found) = next_time_of_day(cron, time) { |
| 536 | return Some((day * 1440 + found) * 60_000); |
| 537 | } |
| 538 | } |
| 539 | time = 0; |
| 540 | } |
| 541 | None |
| 542 | } |
| 543 | |
| 544 | /// The first minute-of-day at or after `from` whose hour and minute both |
| 545 | /// match, walking hours so an unmatched hour costs one step rather than sixty. |
| 546 | fn next_time_of_day(cron: &Cron, from: i64) -> Option<i64> { |
| 547 | let (mut hour, mut minute) = (from / 60, from % 60); |
| 548 | while hour < 24 { |
| 549 | if cron.hour & (1 << hour) != 0 { |
| 550 | while minute < 60 { |
| 551 | if cron.minute & (1 << minute) != 0 { |
| 552 | return Some(hour * 60 + minute); |
| 553 | } |
| 554 | minute += 1; |
| 555 | } |
| 556 | } |
| 557 | hour += 1; |
| 558 | minute = 0; |
| 559 | } |
| 560 | None |
| 561 | } |
| 562 | |
| 563 | /// The earliest next occurrence across every expression on a script. This is |
| 564 | /// what the reserved cron cell arms, because one alarm row holds one deadline |
| 565 | /// however many expressions the script declares. |
| 566 | pub fn next_across(crons: &[Cron], after_ms: Ms) -> Option<Ms> { |
| 567 | crons |
| 568 | .iter() |
| 569 | .filter_map(|cron| next_after(cron, after_ms)) |
| 570 | .min() |
| 571 | } |
| 572 | |
| 573 | /// Which expressions match a fired occurrence, by index. A single deadline can |
| 574 | /// belong to several expressions, and Cloudflare invokes `scheduled` once per |
| 575 | /// matching cron, so the fan-out happens here rather than at arm time. |
| 576 | pub fn matching(crons: &[Cron], at_ms: Ms) -> Vec<usize> { |
| 577 | crons |
| 578 | .iter() |
| 579 | .enumerate() |
| 580 | .filter(|(_, cron)| matches(cron, at_ms)) |
| 581 | .map(|(index, _)| index) |
| 582 | .collect() |
| 583 | } |
| 584 | |
| 585 | /// When to re-arm after a `scheduled` handler failed. |
| 586 | /// |
| 587 | /// A cell has one alarm row, so a retry and the next occurrence compete for |
| 588 | /// the same deadline. The next occurrence wins whenever it is sooner: a |
| 589 | /// failing cron then retries with the usual backoff — `alarm::alarm_retry` |
| 590 | /// computes `retry_ms`, this does not fork it — but can never delay or skip a |
| 591 | /// scheduled run. A cron faster than the backoff simply never retries, which |
| 592 | /// is the right trade when the next attempt is seconds away anyway. |
| 593 | /// |
| 594 | /// `retry_ms` is `None` when the retry ceiling is reached and `next_ms` is |
| 595 | /// `None` when no expression matches again; with both absent there is nothing |
| 596 | /// left to arm and the cell retires. |
| 597 | pub fn cron_rearm(next_ms: Option<Ms>, retry_ms: Option<Ms>) -> Option<Ms> { |
| 598 | match (next_ms, retry_ms) { |
| 599 | (Some(next), Some(retry)) => Some(next.min(retry)), |
| 600 | (next, None) => next, |
| 601 | (None, retry) => retry, |
| 602 | } |
| 603 | } |