Skip to main content

areev_trigger/
schedule.rs

1//! When is this trigger next due?
2//!
3//! Interval, cron and one-shot are three declarations of one primitive: a
4//! function from "when did it last fire" to "when should it fire next". They
5//! are kept apart in the vocabulary because they read differently to a person,
6//! not because the evaluator treats them differently.
7//!
8//! Two behaviours here are worth stating because they are the ones people get
9//! wrong:
10//!
11//! **Rate drifts; cron does not.** `interval_secs` anchors to the *last firing*,
12//! so a 3-minute job on a 5-minute interval leaves a 2-minute gap and the
13//! effective period depends on runtime. `*/5 * * * *` anchors to wall-clock
14//! boundaries and does not. Both are correct; users need to know which they
15//! chose, so the two are separate kinds rather than one field with a flag.
16//!
17//! **Catch-up collapses by default.** A laptop closed over a weekend has missed
18//! hundreds of occurrences. `Catchup::Last` fires once on resume, which is what
19//! anacron does and what systemd's `Persistent=true` means. `All` replays them
20//! and `None` drops them; the three-way is Quartz's misfire vocabulary — fire
21//! once now / skip / replay all.
22
23use areev_core::types::{Catchup, Trigger, TriggerKind};
24use croner::Cron;
25
26use crate::error::{Result, TriggerError};
27
28/// This release evaluates cron in UTC only.
29///
30/// IANA timezone support means `chrono-tz` (~794 KB, and it pulls `phf`) or a
31/// second time library, and it means picking a side in a disagreement that real
32/// implementations have not settled: AWS EventBridge and robfig/cron *skip* an
33/// occurrence that falls in a spring-forward gap, while Vixie cron fires it
34/// immediately. They agree on the fall-back fold — fire once, do not repeat —
35/// so only the gap is contested, but that is enough to make a silent guess the
36/// wrong move. Refusing a timezone we would only mishandle is better than
37/// firing at the wrong hour and being believed.
38const SUPPORTED_TIMEZONE: &str = "UTC";
39
40/// Parse and validate a declaration's schedule without evaluating it.
41///
42/// Called at authoring time so a bad expression is refused when it is written
43/// rather than discovered as silence.
44pub fn validate(trigger: &Trigger) -> Result<()> {
45    if let Some(why) = trigger.incoherence() {
46        return Err(TriggerError::Malformed { what: why });
47    }
48    if trigger.kind == TriggerKind::Schedule {
49        let expr = trigger.cron.as_deref().unwrap_or_default();
50        parse_cron(expr)?;
51        if let Some(tz) = trigger.config_str(areev_core::types::config_keys::TIMEZONE) {
52            if !tz.eq_ignore_ascii_case(SUPPORTED_TIMEZONE) {
53                return Err(TriggerError::BadSchedule {
54                    expr: expr.to_string(),
55                    why: format!(
56                        "timezone {tz:?} is not supported in this release — cron is evaluated \
57                         in UTC. Declare the expression in UTC rather than having it fire at \
58                         the wrong local hour across a DST boundary"
59                    ),
60                });
61            }
62        }
63    }
64    if trigger.kind == TriggerKind::Composite {
65        // Refuse at authoring time exactly what firing refuses later. A gate
66        // naming a member the declaration does not carry can never be
67        // satisfied, so the trigger is dead on arrival -- and a dead trigger's
68        // only symptom is nothing happening, which is the whole category this
69        // validation exists to catch. Same TRG-E008 either way: the code names
70        // the defect, not the moment it was noticed.
71        //
72        // `incoherence()` has already established the predicate is present.
73        if let Some(raw) = trigger.predicate.as_ref() {
74            let predicate = crate::predicate::from_value(raw)?;
75            for referenced in crate::predicate::referenced_members(&predicate) {
76                if !trigger.members.contains_key(&referenced) {
77                    return Err(TriggerError::UnknownMember {
78                        trigger: "being declared".into(),
79                        member: referenced,
80                    });
81                }
82            }
83        }
84    }
85    Ok(())
86}
87
88fn parse_cron(expr: &str) -> Result<Cron> {
89    Cron::new(expr)
90        .with_seconds_optional()
91        .parse()
92        .map_err(|e| TriggerError::BadSchedule { expr: expr.to_string(), why: e.to_string() })
93}
94
95/// The next instant at or after `after_ms` at which `trigger` should fire.
96///
97/// `None` means "never again", which only a one-shot past its instant can be.
98pub fn next_due_after(trigger: &Trigger, after_ms: i64) -> Result<Option<i64>> {
99    match trigger.kind {
100        TriggerKind::Once => {
101            let at = trigger.at_ms.ok_or_else(|| TriggerError::Malformed {
102                what: "a once trigger needs at_ms".into(),
103            })?;
104            Ok(if at > after_ms { Some(at) } else { None })
105        }
106        TriggerKind::Interval | TriggerKind::Polling => {
107            let secs = trigger.interval_secs.ok_or_else(|| TriggerError::Malformed {
108                what: format!("a {} trigger needs interval_secs", trigger.kind.as_str()),
109            })?;
110            Ok(Some(after_ms.saturating_add(i64::from(secs) * 1000)))
111        }
112        TriggerKind::Schedule => {
113            let expr = trigger.cron.as_deref().unwrap_or_default();
114            let cron = parse_cron(expr)?;
115            let after = chrono::DateTime::from_timestamp_millis(after_ms).ok_or_else(|| {
116                TriggerError::BadSchedule {
117                    expr: expr.to_string(),
118                    why: format!("{after_ms} is not a representable instant"),
119                }
120            })?;
121            let next = cron.find_next_occurrence(&after, false).map_err(|e| {
122                TriggerError::BadSchedule { expr: expr.to_string(), why: e.to_string() }
123            })?;
124            Ok(Some(next.timestamp_millis()))
125        }
126        // Push and gate kinds are not clocked: they fire when something arrives.
127        TriggerKind::Memory | TriggerKind::Webhook | TriggerKind::Manual | TriggerKind::Composite => {
128            Ok(None)
129        }
130    }
131}
132
133/// Where to set `next_due_at` after a firing that happened at `fired_at_ms`,
134/// given that it is now `now_ms`.
135///
136/// This is where catch-up policy lands. If evaluation stalled — the host was
137/// asleep, the process was down — the naive next instant can be far in the
138/// past, and the question is whether to replay the gap.
139pub fn advance_after_firing(trigger: &Trigger, fired_at_ms: i64, now_ms: i64) -> Result<Option<i64>> {
140    let Some(mut next) = next_due_after(trigger, fired_at_ms)? else {
141        return Ok(None);
142    };
143    if next > now_ms {
144        return Ok(Some(next));
145    }
146    match trigger.catchup {
147        // Replay: leave the schedule where it is and let each stale occurrence
148        // fire in turn.
149        Catchup::All => Ok(Some(next)),
150        // Collapse the backlog into a single firing. Walk forward to the first
151        // occurrence still ahead of us; one firing already happened, and the
152        // others are missed rather than owed.
153        Catchup::Last | Catchup::None => {
154            // Bounded so a long-dormant memory with a fast interval cannot spin:
155            // a year of one-second occurrences would otherwise be 31 million
156            // steps. Past the bound we jump straight off `now`.
157            const MAX_STEPS: u32 = 10_000;
158            let mut steps = 0;
159            while next <= now_ms && steps < MAX_STEPS {
160                match next_due_after(trigger, next)? {
161                    Some(n) if n > next => next = n,
162                    // A schedule that does not advance would loop forever.
163                    _ => break,
164                }
165                steps += 1;
166            }
167            if next <= now_ms {
168                next = next_due_after(trigger, now_ms)?.unwrap_or(next);
169            }
170            Ok(Some(next))
171        }
172    }
173}
174
175/// When a never-evaluated trigger first becomes due.
176///
177/// `None` means "now". `Some(t)` means "not yet — at `t`", and the evaluator
178/// records it so the trigger wakes at the right moment instead of being asked
179/// this question again on every pass.
180///
181/// The split is between two kinds of cadence:
182///
183/// - **Relative** (`Interval`, `Polling`) has no baseline to wait out, so it
184///   fires at once — the loop gate's rule, and what makes a polling trigger
185///   seed its cursor promptly instead of an interval later.
186/// - **Absolute** (`Schedule`, `Once`) waits for the instant it names. A cron of
187///   `0 9 * * *` must not fire at midnight merely because it was just declared.
188/// - **Unclocked** kinds are eligible immediately; what gates them is whether
189///   anything arrived, which the evaluator decides.
190pub fn initial_due(trigger: &Trigger, now_ms: i64) -> Result<Option<i64>> {
191    Ok(match trigger.kind {
192        TriggerKind::Schedule => next_due_after(trigger, now_ms)?,
193        // A one-shot whose instant has already passed fires once, now.
194        TriggerKind::Once => trigger.at_ms.filter(|at| *at > now_ms),
195        TriggerKind::Interval
196        | TriggerKind::Polling
197        | TriggerKind::Memory
198        | TriggerKind::Webhook
199        | TriggerKind::Manual
200        | TriggerKind::Composite => None,
201    })
202}
203
204/// Is this trigger due at `now_ms`?
205///
206/// The complete check: state alone cannot answer it, because an absent
207/// `next_due_at` means "never evaluated" and what that implies depends on the
208/// declaration. See [`initial_due`].
209pub fn is_due(trigger: &Trigger, state: &areev_store::TriggerState, now_ms: i64) -> Result<bool> {
210    if !state.permits_firing(now_ms) {
211        return Ok(false);
212    }
213    if state.next_due_at.is_some() {
214        return Ok(true); // already compared against `now` above
215    }
216    Ok(initial_due(trigger, now_ms)?.is_none())
217}
218
219/// Whether this trigger can never fire again after a firing at `fired_at_ms`.
220///
221/// Only a one-shot exhausts. The other kinds that return no next instant
222/// (`Memory`, `Webhook`, `Manual`, `Composite`) are not clocked at all — they
223/// are eligible on every pass and gated by whether anything arrived — so
224/// treating "no next instant" as exhaustion would silence them permanently.
225pub fn exhausts_after(trigger: &Trigger, fired_at_ms: i64) -> bool {
226    trigger.kind == TriggerKind::Once
227        && next_due_after(trigger, fired_at_ms).ok().flatten().is_none()
228}
229
230/// Back off `next_due_at` after a failure, so a broken connector does not
231/// hot-loop against a source that is down.
232///
233/// Exponential on consecutive failures, capped, and never shorter than the
234/// declared interval — a trigger that fails fast should not end up polling
235/// *more* often than a healthy one.
236pub fn backoff_until(trigger: &Trigger, consecutive_failures: u32, now_ms: i64) -> i64 {
237    const BASE_MS: i64 = 30_000;
238    const CAP_MS: i64 = 3_600_000;
239    let shift = consecutive_failures.saturating_sub(1).min(7);
240    let penalty = (BASE_MS << shift).min(CAP_MS);
241    let floor = trigger.interval_secs.map(|s| i64::from(s) * 1000).unwrap_or(0);
242    now_ms.saturating_add(penalty.max(floor))
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    const WF: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
250    /// 2026-01-01T00:00:00Z
251    const T0: i64 = 1_767_225_600_000;
252
253    fn interval(secs: u32) -> Trigger {
254        Trigger::new(TriggerKind::Interval, WF).interval_secs(secs)
255    }
256    fn schedule(expr: &str) -> Trigger {
257        Trigger::new(TriggerKind::Schedule, WF).cron(expr)
258    }
259
260    #[test]
261    fn interval_anchors_to_the_last_firing() {
262        let t = interval(120);
263        assert_eq!(next_due_after(&t, T0).unwrap(), Some(T0 + 120_000));
264        // …and therefore drifts: firing late pushes the next one out.
265        assert_eq!(next_due_after(&t, T0 + 5_000).unwrap(), Some(T0 + 125_000));
266    }
267
268    #[test]
269    fn cron_anchors_to_wall_clock_boundaries() {
270        let t = schedule("*/5 * * * *");
271        let first = next_due_after(&t, T0).unwrap().unwrap();
272        assert_eq!(first, T0 + 300_000, "next boundary from midnight");
273        // Firing late still lands on the boundary — no drift.
274        let after_late = next_due_after(&t, T0 + 301_000).unwrap().unwrap();
275        assert_eq!(after_late, T0 + 600_000);
276    }
277
278    #[test]
279    fn a_five_field_weekday_expression_parses_with_posix_numbering() {
280        // The trap this guards: the most-downloaded Rust cron crate requires 7
281        // fields with mandatory seconds and Quartz day numbering where 1=Sun and
282        // 0 is rejected, so it reads this expression as the wrong days.
283        let t = schedule("0 9 * * 1-5");
284        let next = next_due_after(&t, T0).unwrap().unwrap();
285        let dt = chrono::DateTime::from_timestamp_millis(next).unwrap();
286        use chrono::{Datelike, Timelike};
287        assert_eq!(dt.hour(), 9);
288        assert_eq!(dt.minute(), 0);
289        let wd = dt.weekday().num_days_from_monday();
290        assert!(wd < 5, "must land Mon-Fri, got {:?}", dt.weekday());
291    }
292
293    #[test]
294    fn a_one_shot_fires_once_and_then_never() {
295        let t = Trigger::new(TriggerKind::Once, WF).at_ms(T0 + 1_000);
296        assert_eq!(next_due_after(&t, T0).unwrap(), Some(T0 + 1_000));
297        assert_eq!(next_due_after(&t, T0 + 1_000).unwrap(), None, "not due at its own instant again");
298        assert_eq!(next_due_after(&t, T0 + 9_999).unwrap(), None);
299    }
300
301    #[test]
302    fn push_and_gate_kinds_are_not_clocked() {
303        for kind in [TriggerKind::Webhook, TriggerKind::Manual, TriggerKind::Memory] {
304            let t = Trigger::new(kind, WF);
305            assert_eq!(next_due_after(&t, T0).unwrap(), None, "{kind:?} should not be clocked");
306        }
307    }
308
309    #[test]
310    fn catchup_last_collapses_a_weekend_of_missed_occurrences() {
311        // Fired Friday, evaluated Monday: a 5-minute schedule missed ~800
312        // occurrences. Exactly one firing is owed, not eight hundred.
313        let t = schedule("*/5 * * * *").catchup(Catchup::Last);
314        let three_days = 3 * 86_400_000;
315        let next = advance_after_firing(&t, T0, T0 + three_days).unwrap().unwrap();
316        assert!(next > T0 + three_days, "must be scheduled ahead of now, not in the backlog");
317        assert!(next <= T0 + three_days + 300_000, "and at the very next boundary");
318    }
319
320    #[test]
321    fn catchup_all_leaves_the_backlog_in_place() {
322        let t = schedule("*/5 * * * *").catchup(Catchup::All);
323        let three_days = 3 * 86_400_000;
324        let next = advance_after_firing(&t, T0, T0 + three_days).unwrap().unwrap();
325        assert_eq!(next, T0 + 300_000, "the stale occurrence stays due, to be replayed");
326    }
327
328    #[test]
329    fn collapsing_is_bounded_for_a_fast_interval_over_a_long_gap() {
330        // A one-second interval dormant for a year is ~31M occurrences. The walk
331        // must not attempt them.
332        let t = interval(1).catchup(Catchup::Last);
333        let a_year = 365 * 86_400_000i64;
334        let started = std::time::Instant::now();
335        let next = advance_after_firing(&t, T0, T0 + a_year).unwrap().unwrap();
336        assert!(next > T0 + a_year);
337        assert!(started.elapsed().as_millis() < 500, "the collapse walk must be bounded");
338    }
339
340    #[test]
341    fn a_firing_that_is_still_ahead_of_now_is_left_alone() {
342        let t = interval(300);
343        let next = advance_after_firing(&t, T0, T0 + 1_000).unwrap().unwrap();
344        assert_eq!(next, T0 + 300_000);
345    }
346
347    #[test]
348    fn backoff_grows_then_caps_and_never_polls_faster_than_the_interval() {
349        let t = interval(600); // 10 minutes
350        let first = backoff_until(&t, 1, T0) - T0;
351        let second = backoff_until(&t, 2, T0) - T0;
352        assert!(second >= first, "backoff must not shrink as failures accumulate");
353
354        // Never more often than the declared interval: a failing trigger must
355        // not end up hammering a source harder than a healthy one.
356        assert!(first >= 600_000, "floor is the declared interval");
357
358        let far = backoff_until(&t, 99, T0) - T0;
359        assert!(far <= 3_600_000, "and it caps rather than growing without bound");
360    }
361
362    #[test]
363    fn an_unparseable_expression_is_refused_with_its_code() {
364        let t = schedule("not a cron expression");
365        let e = validate(&t).unwrap_err();
366        assert_eq!(e.code(), "TRG-E006");
367        assert!(e.to_string().starts_with("TRG-E006"));
368    }
369
370    #[test]
371    fn a_non_utc_timezone_is_refused_rather_than_mishandled() {
372        // Firing at the wrong local hour and being believed is worse than
373        // refusing, because nobody notices a schedule that is quietly an hour
374        // off for half the year.
375        let t = schedule("0 9 * * *").config(serde_json::json!({
376            "int:timezone": "America/New_York"
377        }));
378        let e = validate(&t).unwrap_err();
379        assert_eq!(e.code(), "TRG-E006");
380        assert!(e.to_string().contains("UTC"), "the message should say what IS supported");
381
382        // UTC spelled either way is fine.
383        let ok = schedule("0 9 * * *").config(serde_json::json!({ "int:timezone": "utc" }));
384        assert!(validate(&ok).is_ok());
385    }
386
387    #[test]
388    fn validate_rejects_an_incoherent_declaration_before_the_schedule() {
389        let t = Trigger::new(TriggerKind::Interval, WF); // no interval_secs
390        let e = validate(&t).unwrap_err();
391        assert_eq!(e.code(), "TRG-E001");
392    }
393}