Skip to main content

agentmux_srv_core/backend/cron/
schedule.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! When a job runs: its trigger as a sequence of slots, ms epoch
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.1 "Triggers").
6//!
7//! A cron trigger is read in its IANA time zone. The `cron` crate evaluates
8//! in one zone only and skips a local time that doesn't exist or exists
9//! twice, so the expression is evaluated here against local wall-clock time
10//! (carried as a UTC value with no offset), and each local time is turned
11//! into an instant with the zone's rules:
12//! - in a daylight-saving gap (02:30 on a spring-forward night) the slot
13//!   fires once, at the first valid time after the gap; several slots in one
14//!   gap are that one fire;
15//! - in an overlap (01:30 on a fall-back night) it fires once, at the first
16//!   of the two.
17//!
18//! Every slot is strictly later than the one before, so a scheduler that
19//! asks for the slot after the last one never fires a time twice.
20
21use chrono::{DateTime, Duration, LocalResult, NaiveDateTime, TimeZone, Timelike, Utc};
22use chrono_tz::Tz;
23
24use crate::backend::storage::cron::CronJob;
25
26/// The zone a cron trigger names when it names none.
27pub const DEFAULT_TZ: &str = "UTC";
28
29/// The longest fixed offset a job's fires are spread by (§5.1).
30pub const JITTER_MAX_MS: i64 = 120_000;
31
32/// How far a daylight-saving change can move the local clock, at most, for
33/// the backward search; and how many candidate local times one search
34/// looks at.
35const SHIFT_MAX_HOURS: i64 = 3;
36const SEARCH_CAP: usize = 100_000;
37
38/// A job's trigger, ready to answer "when next".
39#[derive(Debug, Clone)]
40pub enum JobSchedule {
41    Cron { schedule: Box<cron::Schedule>, tz: Tz },
42    /// Every `period_ms` from `anchor_ms` (its creation): the first slot is
43    /// one period after it.
44    Every { anchor_ms: i64, period_ms: i64 },
45    Once { at_ms: i64 },
46    /// Run now only: no slots.
47    Manual,
48}
49
50/// An IANA zone name (`America/New_York`, `UTC`). Empty is UTC.
51pub fn parse_tz(name: &str) -> Result<Tz, String> {
52    let name = name.trim();
53    if name.is_empty() {
54        return Ok(Tz::UTC);
55    }
56    name.parse::<Tz>().map_err(|_| format!("unknown time zone '{name}' (use an IANA name such as Europe/Berlin or UTC)"))
57}
58
59/// The job's fixed jitter, 0 up to [`JITTER_MAX_MS`], derived from its id
60/// (FNV-1a), so jobs due at the same minute don't all start at once and a
61/// job's offset is the same on every instance and after a restart.
62pub fn jitter_ms(job_id: &str) -> i64 {
63    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
64    for b in job_id.bytes() {
65        hash ^= u64::from(b);
66        hash = hash.wrapping_mul(0x0100_0000_01b3);
67    }
68    (hash % (JITTER_MAX_MS as u64 + 1)) as i64
69}
70
71/// A local wall-clock time as the `cron` crate's UTC value.
72fn carrier(naive: NaiveDateTime) -> DateTime<Utc> {
73    Utc.from_utc_datetime(&naive)
74}
75
76/// The instant a cron slot at local time `naive` fires (see the module doc).
77fn instant(tz: &Tz, naive: NaiveDateTime) -> Option<i64> {
78    match tz.from_local_datetime(&naive) {
79        LocalResult::Single(t) | LocalResult::Ambiguous(t, _) => Some(t.timestamp_millis()),
80        LocalResult::None => gap_end(tz, naive),
81    }
82}
83
84/// The first valid local minute after the gap `naive` falls in, as an
85/// instant. Gaps are at most a day (a zone that skipped a date).
86fn gap_end(tz: &Tz, naive: NaiveDateTime) -> Option<i64> {
87    let start = naive.with_second(0)?.with_nanosecond(0)?;
88    (1..=48 * 60).find_map(|m| match tz.from_local_datetime(&(start + Duration::minutes(m))) {
89        LocalResult::Single(t) | LocalResult::Ambiguous(t, _) => Some(t.timestamp_millis()),
90        LocalResult::None => None,
91    })
92}
93
94impl JobSchedule {
95    /// A standard 5-field cron expression read in `tz` (empty: UTC).
96    pub fn cron(expression: &str, tz: &str) -> Result<Self, String> {
97        Ok(JobSchedule::Cron { schedule: Box::new(super::expr::parse(expression)?), tz: parse_tz(tz)? })
98    }
99
100    /// `job`'s trigger. A job from before triggers had kinds is cron.
101    pub fn of(job: &CronJob) -> Result<Self, String> {
102        use crate::backend::jobs::definition::trigger_kind;
103        match job.trigger_kind.as_str() {
104            "" | trigger_kind::CRON => Self::cron(&job.expression, &job.tz),
105            trigger_kind::EVERY => {
106                let secs = job.every_secs.filter(|&s| s > 0).ok_or("an every trigger needs seconds")?;
107                Ok(JobSchedule::Every { anchor_ms: job.created_at.saturating_mul(1000), period_ms: secs.saturating_mul(1000) })
108            }
109            trigger_kind::ONCE => Ok(JobSchedule::Once { at_ms: job.once_at_ms.ok_or("a once trigger needs at")? }),
110            // An event job fires when a source says so (`CronScheduler::fire_event`), never at a time.
111            trigger_kind::MANUAL | trigger_kind::EVENT => Ok(JobSchedule::Manual),
112            other => Err(format!("trigger kind {other} can't be scheduled")),
113        }
114    }
115
116    /// The slots strictly after `after_ms`, in order.
117    pub fn after(&self, after_ms: i64) -> Box<dyn Iterator<Item = i64> + '_> {
118        match self {
119            JobSchedule::Cron { schedule, tz } => {
120                let Some(after) = DateTime::from_timestamp_millis(after_ms) else { return Box::new(std::iter::empty()) };
121                let local = after.with_timezone(tz).naive_local();
122                let mut last = after_ms;
123                Box::new(schedule.after(&carrier(local)).take(SEARCH_CAP).filter_map(move |c| {
124                    let ms = instant(tz, c.naive_utc())?;
125                    (ms > last).then(|| {
126                        last = ms;
127                        ms
128                    })
129                }))
130            }
131            &JobSchedule::Every { anchor_ms, period_ms } => {
132                let k = if after_ms < anchor_ms { 1 } else { (after_ms - anchor_ms) / period_ms + 1 };
133                Box::new((k.max(1)..).map(move |k| anchor_ms.saturating_add(k.saturating_mul(period_ms))))
134            }
135            &JobSchedule::Once { at_ms } => Box::new((at_ms > after_ms).then_some(at_ms).into_iter()),
136            JobSchedule::Manual => Box::new(std::iter::empty()),
137        }
138    }
139
140    /// The first slot strictly after `after_ms`.
141    pub fn next_after(&self, after_ms: i64) -> Option<i64> {
142        self.after(after_ms).next()
143    }
144
145    /// The last slot strictly before `before_ms`.
146    pub fn prev_before(&self, before_ms: i64) -> Option<i64> {
147        match self {
148            JobSchedule::Cron { schedule, tz } => {
149                // Local times aren't in instant order around an overlap, so
150                // look a few hours either side and keep the latest instant.
151                let local = DateTime::from_timestamp_millis(before_ms)?.with_timezone(tz).naive_local();
152                let window = Duration::hours(SHIFT_MAX_HOURS);
153                let mut best: Option<i64> = None;
154                for c in schedule.after(&carrier(local + window)).rev().take(SEARCH_CAP) {
155                    let naive = c.naive_utc();
156                    if let Some(ms) = instant(tz, naive).filter(|&ms| ms < before_ms) {
157                        best = Some(best.map_or(ms, |b| b.max(ms)));
158                    }
159                    if naive < local - window && best.is_some() {
160                        break;
161                    }
162                }
163                best
164            }
165            &JobSchedule::Every { anchor_ms, period_ms } => {
166                let k = (before_ms - anchor_ms - 1).div_euclid(period_ms);
167                (k >= 1).then(|| anchor_ms + k * period_ms)
168            }
169            &JobSchedule::Once { at_ms } => (at_ms < before_ms).then_some(at_ms),
170            JobSchedule::Manual => None,
171        }
172    }
173
174    /// The shortest time between two consecutive slots among the next
175    /// `count` after `from_ms`, in seconds. `None` with fewer than two.
176    pub fn min_gap_secs(&self, from_ms: i64, count: usize) -> Option<i64> {
177        let slots: Vec<i64> = self.after(from_ms).take(count).collect();
178        slots.windows(2).map(|w| (w[1] - w[0]) / 1000).min()
179    }
180}
181
182#[cfg(test)]
183#[path = "schedule_tests.rs"]
184mod tests;