agentmux_srv_core/backend/cron/
schedule.rs1use chrono::{DateTime, Duration, LocalResult, NaiveDateTime, TimeZone, Timelike, Utc};
22use chrono_tz::Tz;
23
24use crate::backend::storage::cron::CronJob;
25
26pub const DEFAULT_TZ: &str = "UTC";
28
29pub const JITTER_MAX_MS: i64 = 120_000;
31
32const SHIFT_MAX_HOURS: i64 = 3;
36const SEARCH_CAP: usize = 100_000;
37
38#[derive(Debug, Clone)]
40pub enum JobSchedule {
41 Cron { schedule: Box<cron::Schedule>, tz: Tz },
42 Every { anchor_ms: i64, period_ms: i64 },
45 Once { at_ms: i64 },
46 Manual,
48}
49
50pub 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
59pub 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
71fn carrier(naive: NaiveDateTime) -> DateTime<Utc> {
73 Utc.from_utc_datetime(&naive)
74}
75
76fn 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
84fn 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 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 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 trigger_kind::MANUAL | trigger_kind::EVENT => Ok(JobSchedule::Manual),
112 other => Err(format!("trigger kind {other} can't be scheduled")),
113 }
114 }
115
116 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 pub fn next_after(&self, after_ms: i64) -> Option<i64> {
142 self.after(after_ms).next()
143 }
144
145 pub fn prev_before(&self, before_ms: i64) -> Option<i64> {
147 match self {
148 JobSchedule::Cron { schedule, tz } => {
149 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 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;