1use jiff::civil::DateTime;
17use jiff::tz::{AmbiguousOffset, TimeZone};
18use jiff::{SignedDuration, Timestamp};
19use schedr_model::Trigger;
20
21#[cfg(test)]
22mod tests;
23
24const MARGIN: SignedDuration = SignedDuration::from_hours(3);
27
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30pub enum FireTimesError {
31 #[error("cron expression `{expression}`: {reason}")]
33 Cron {
34 expression: String,
36 reason: String,
38 },
39 #[error("unknown time zone `{0}`")]
41 TimeZone(String),
42 #[error("the interval of an Every trigger must be positive")]
44 ZeroInterval,
45}
46
47#[derive(Debug, Clone)]
49pub enum FireTimes {
50 None,
52 Cron(Box<CronTimes>),
54 Every {
56 anchor: Timestamp,
58 interval_ns: i128,
60 },
61 Once(Timestamp),
63}
64
65#[derive(Debug, Clone)]
67pub struct CronTimes {
68 cron: croner::Cron,
69 tz: TimeZone,
70 hour_fixed: bool,
71}
72
73impl FireTimes {
74 pub fn new(trigger: &Trigger) -> Result<Self, FireTimesError> {
81 match trigger {
82 Trigger::None
84 | Trigger::Chained { .. }
85 | Trigger::Event { .. }
86 | Trigger::RunOf { .. }
87 | Trigger::EventNamed { .. } => Ok(Self::None),
88 Trigger::Once { at } => Ok(Self::Once(*at)),
89 Trigger::Every {
90 interval_ms, start, ..
91 } => {
92 if *interval_ms == 0 {
93 return Err(FireTimesError::ZeroInterval);
94 }
95 Ok(Self::Every {
96 anchor: start.unwrap_or(Timestamp::UNIX_EPOCH),
97 interval_ns: i128::from(*interval_ms) * 1_000_000,
98 })
99 }
100 Trigger::Cron {
101 expression,
102 timezone,
103 ..
104 } => Ok(Self::Cron(Box::new(CronTimes::new(expression, timezone)?))),
105 }
106 }
107
108 #[must_use]
110 pub fn next_after(&self, t: Timestamp) -> Option<Timestamp> {
111 match self {
112 Self::None => None,
113 Self::Once(at) => (*at > t).then_some(*at),
114 Self::Every {
115 anchor,
116 interval_ns,
117 } => {
118 let k = (t.as_nanosecond() - anchor.as_nanosecond()).div_euclid(*interval_ns) + 1;
119 Timestamp::from_nanosecond(anchor.as_nanosecond() + k * interval_ns).ok()
120 }
121 Self::Cron(cron) => cron.next_after(t),
122 }
123 }
124
125 #[must_use]
127 pub fn previous_before(&self, t: Timestamp) -> Option<Timestamp> {
128 match self {
129 Self::None => None,
130 Self::Once(at) => (*at < t).then_some(*at),
131 Self::Every {
132 anchor,
133 interval_ns,
134 } => {
135 let offset = t.as_nanosecond() - anchor.as_nanosecond();
136 let k = (offset - 1).div_euclid(*interval_ns);
137 Timestamp::from_nanosecond(anchor.as_nanosecond() + k * interval_ns).ok()
138 }
139 Self::Cron(cron) => cron.previous_before(t),
140 }
141 }
142
143 #[must_use]
145 pub fn next_at_or_after(&self, t: Timestamp) -> Option<Timestamp> {
146 if self.is_fire_time(t) {
147 Some(t)
148 } else {
149 self.next_after(t)
150 }
151 }
152
153 #[must_use]
155 pub fn last_at_or_before(&self, t: Timestamp) -> Option<Timestamp> {
156 if self.is_fire_time(t) {
157 Some(t)
158 } else {
159 self.previous_before(t)
160 }
161 }
162
163 #[must_use]
167 pub fn between(&self, from: Timestamp, to: Timestamp, max: usize) -> Option<Vec<Timestamp>> {
168 if let Self::Cron(cron) = self {
169 return cron.between(from, to, max);
170 }
171 let mut found = Vec::new();
172 let mut next = self.next_at_or_after(from);
173 while let Some(at) = next.filter(|at| *at <= to) {
174 if found.len() == max {
175 return None;
176 }
177 found.push(at);
178 next = self.next_after(at);
179 }
180 Some(found)
181 }
182
183 #[must_use]
185 pub fn is_fire_time(&self, t: Timestamp) -> bool {
186 t.checked_sub(SignedDuration::from_nanos(1))
187 .ok()
188 .and_then(|before| self.next_after(before))
189 == Some(t)
190 }
191}
192
193impl CronTimes {
194 pub fn new(expression: &str, timezone: &str) -> Result<Self, FireTimesError> {
200 let tz =
201 TimeZone::get(timezone).map_err(|_| FireTimesError::TimeZone(timezone.to_owned()))?;
202 let cron = croner::parser::CronParser::builder()
203 .seconds(croner::parser::Seconds::Optional)
204 .year(croner::parser::Year::Disallowed)
205 .build()
206 .parse(expression.trim())
207 .map_err(|e| FireTimesError::Cron {
208 expression: expression.to_owned(),
209 reason: e.to_string(),
210 })?;
211 Ok(Self {
212 cron,
213 tz,
214 hour_fixed: hour_field_is_fixed(expression),
215 })
216 }
217
218 fn next_after(&self, t: Timestamp) -> Option<Timestamp> {
219 self.quick_after(t).or_else(|| self.walk_after(t))
220 }
221
222 fn previous_before(&self, t: Timestamp) -> Option<Timestamp> {
223 self.quick_before(t).or_else(|| self.walk_before(t))
224 }
225
226 fn quick_after(&self, t: Timestamp) -> Option<Timestamp> {
230 let found = self.cron.find_next_occurrence(&self.civil(t), false).ok()?;
231 let at = self.unambiguous(found).filter(|at| *at > t)?;
232 let (from, until) = (t.checked_sub(MARGIN).ok()?, at.checked_add(MARGIN).ok()?);
233 match self.tz.following(from).next() {
234 Some(change) if change.timestamp() <= until => None,
235 _ => Some(at),
236 }
237 }
238
239 fn quick_before(&self, t: Timestamp) -> Option<Timestamp> {
241 let civil = self.civil(t);
244 let found = self
245 .cron
246 .find_previous_occurrence(&civil, civil.subsec_nanosecond() != 0)
247 .ok()?;
248 let at = self.unambiguous(found).filter(|at| *at < t)?;
249 let (from, until) = (at.checked_sub(MARGIN).ok()?, t.checked_add(MARGIN).ok()?);
250 match self.tz.preceding(until).next() {
251 Some(change) if change.timestamp() >= from => None,
252 _ => Some(at),
253 }
254 }
255
256 fn between(&self, from: Timestamp, to: Timestamp, max: usize) -> Option<Vec<Timestamp>> {
260 let change_near = from.checked_sub(MARGIN).ok().is_none_or(|start| {
261 self.tz.following(start).next().is_some_and(|change| {
262 to.checked_add(MARGIN)
263 .ok()
264 .is_none_or(|until| change.timestamp() <= until)
265 })
266 });
267 let margin = if change_near {
268 MARGIN
269 } else {
270 SignedDuration::ZERO
271 };
272 let first = self
273 .civil(from)
274 .checked_sub(margin)
275 .unwrap_or(DateTime::MIN);
276 let last = self.civil(to).checked_add(margin).unwrap_or(DateTime::MAX);
277 let mut found = std::collections::BTreeSet::new();
278 let mut matched = self.cron.find_next_occurrence(&first, true).ok();
279 while let Some(civil) = matched.filter(|civil| *civil <= last) {
280 found.extend(
281 self.moments(civil)
282 .into_iter()
283 .filter(|moment| (from..=to).contains(moment)),
284 );
285 if found.len() > max {
286 return None;
287 }
288 matched = self.cron.find_next_occurrence(&civil, false).ok();
289 }
290 Some(found.into_iter().collect())
291 }
292
293 fn unambiguous(&self, civil: DateTime) -> Option<Timestamp> {
295 match self.tz.to_ambiguous_timestamp(civil).offset() {
296 AmbiguousOffset::Unambiguous { offset } => offset.to_timestamp(civil).ok(),
297 AmbiguousOffset::Gap { .. } | AmbiguousOffset::Fold { .. } => None,
298 }
299 }
300
301 fn walk_after(&self, t: Timestamp) -> Option<Timestamp> {
305 let mut civil = self.civil(t).checked_sub(MARGIN).ok()?;
306 let mut best: Option<Timestamp> = None;
307 while let Ok(found) = self.cron.find_next_occurrence(&civil, false) {
308 if best.is_some_and(|b| {
309 self.civil(b)
310 .checked_add(MARGIN)
311 .is_ok_and(|limit| found > limit)
312 }) {
313 break;
314 }
315 for moment in self.moments(found) {
316 if moment > t && best.is_none_or(|b| moment < b) {
317 best = Some(moment);
318 }
319 }
320 civil = found;
321 }
322 best
323 }
324
325 fn walk_before(&self, t: Timestamp) -> Option<Timestamp> {
327 let mut civil = self.civil(t).checked_add(MARGIN).ok()?;
328 let mut best: Option<Timestamp> = None;
329 while let Ok(found) = self.cron.find_previous_occurrence(&civil, false) {
330 if best.is_some_and(|b| {
331 self.civil(b)
332 .checked_sub(MARGIN)
333 .is_ok_and(|limit| found < limit)
334 }) {
335 break;
336 }
337 for moment in self.moments(found) {
338 if moment < t && best.is_none_or(|b| moment > b) {
339 best = Some(moment);
340 }
341 }
342 civil = found;
343 }
344 best
345 }
346
347 fn civil(&self, t: Timestamp) -> DateTime {
348 t.to_zoned(self.tz.clone()).datetime()
349 }
350
351 fn moments(&self, civil: DateTime) -> Vec<Timestamp> {
353 match self.tz.to_ambiguous_timestamp(civil).offset() {
354 AmbiguousOffset::Unambiguous { offset } => {
355 offset.to_timestamp(civil).ok().into_iter().collect()
356 }
357 AmbiguousOffset::Gap { after, .. } => after
358 .to_timestamp(civil)
359 .ok()
360 .and_then(|before_gap| self.tz.following(before_gap).next())
361 .map(|transition| transition.timestamp())
362 .into_iter()
363 .collect(),
364 AmbiguousOffset::Fold { before, after } => {
365 let first = before.to_timestamp(civil).ok();
366 let second = after.to_timestamp(civil).ok().filter(|_| !self.hour_fixed);
367 first.into_iter().chain(second).collect()
368 }
369 }
370 }
371}
372
373fn hour_field_is_fixed(expression: &str) -> bool {
375 let text = expression.trim();
376 if text.starts_with('@') {
377 return text != "@hourly";
378 }
379 let fields: Vec<&str> = text.split_whitespace().collect();
380 let hour = if fields.len() == 6 {
381 fields[2]
382 } else {
383 fields.get(1).copied().unwrap_or("")
384 };
385 !hour.is_empty() && hour.bytes().all(|b| b.is_ascii_digit())
386}