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