Skip to main content

schedr_master/
fire_times.rs

1//! Fire times of a DAG's time trigger, with schedr's daylight-saving rules.
2//!
3//! A cron expression is matched against **wall-clock times** in its time zone (croner parses and
4//! matches it); each match becomes real moments by these rules (see archive/PROJECT.md, Native API:
5//! daylight-saving changes):
6//!
7//! - **Gap** (spring forward, the time doesn't exist): the fire time moves to the first moment
8//!   after the gap; several matches in one gap collapse into that one fire time.
9//! - **Overlap** (fall back, the time happens twice): with a **fixed hour field** (`30 2 * * *`)
10//!   it fires once, at the first occurrence; with a wildcard, step, range or list in the hour
11//!   field (`*/15 * * * *`) it fires at each occurrence.
12//!
13//! `Every` is measured in real time from its anchor (`start`, or the Unix epoch without one);
14//! `Once` has one fire time; no trigger has none.
15
16use jiff::civil::DateTime;
17use jiff::tz::{AmbiguousOffset, TimeZone};
18use jiff::{SignedDuration, Timestamp};
19use schedr_model::Trigger;
20
21#[cfg(test)]
22mod tests;
23
24/// How far around a moment wall-clock matches are looked at: more than any daylight-saving
25/// shift, so the matches of both sides of an overlap are compared.
26const MARGIN: SignedDuration = SignedDuration::from_hours(3);
27
28/// A time trigger that can't be evaluated.
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30pub enum FireTimesError {
31    /// The cron expression doesn't parse.
32    #[error("cron expression `{expression}`: {reason}")]
33    Cron {
34        /// The expression.
35        expression: String,
36        /// Why it doesn't parse.
37        reason: String,
38    },
39    /// The time zone isn't known.
40    #[error("unknown time zone `{0}`")]
41    TimeZone(String),
42    /// An `Every` interval of zero.
43    #[error("the interval of an Every trigger must be positive")]
44    ZeroInterval,
45}
46
47/// The fire times of a time trigger.
48#[derive(Debug, Clone)]
49pub enum FireTimes {
50    /// No trigger: no fire times.
51    None,
52    /// A cron expression in a time zone.
53    Cron(Box<CronTimes>),
54    /// A fixed interval from an anchor.
55    Every {
56        /// A fire time the others are whole intervals from.
57        anchor: Timestamp,
58        /// The interval in nanoseconds (positive).
59        interval_ns: i128,
60    },
61    /// One fire time.
62    Once(Timestamp),
63}
64
65/// A parsed cron trigger.
66#[derive(Debug, Clone)]
67pub struct CronTimes {
68    cron: croner::Cron,
69    tz: TimeZone,
70    hour_fixed: bool,
71}
72
73impl FireTimes {
74    /// The fire times of `trigger`; an `Every` trigger counts from its `start` when given.
75    ///
76    /// # Errors
77    ///
78    /// [`FireTimesError`] for a cron expression that doesn't parse, an unknown time zone or a
79    /// zero interval.
80    pub fn new(trigger: &Trigger) -> Result<Self, FireTimesError> {
81        match trigger {
82            // Events start its runs: it has no fire times.
83            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    /// The first fire time strictly after `t`.
109    #[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    /// The last fire time strictly before `t`.
126    #[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    /// The first fire time at or after `t`.
144    #[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    /// The last fire time at or before `t`.
154    #[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    /// The fire times from `from` to `to`, both included, in order; `None` when there are
164    /// more than `max`. A cron's are found in one walk over the range's matches (B199), not a
165    /// lookup per fire time, which near a daylight-saving change walks hours of matches each.
166    #[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    /// Whether `t` is a fire time.
184    #[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    /// Parses a cron expression (5 fields, 6 with seconds first, or a preset) in a time zone.
195    ///
196    /// # Errors
197    ///
198    /// [`FireTimesError::Cron`] or [`FireTimesError::TimeZone`].
199    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    /// The first match after `t` when the zone doesn't change its offset from [`MARGIN`]
227    /// before `t` to [`MARGIN`] after it (B98): there wall-clock times and moments map one to
228    /// one, so no match on either side of a change needs comparing. `None`: walk.
229    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    /// The last match before `t`, as [`Self::quick_after`] does it.
240    fn quick_before(&self, t: Timestamp) -> Option<Timestamp> {
241        // Cron's search drops the fraction of a second: past a whole second, a match at it is
242        // before `t`, so it is included.
243        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    /// [`FireTimes::between`]: the moments of every match from `from` to `to`, sorted and
257    /// deduplicated (a gap's matches collapse into one). Near a time zone change the matches
258    /// [`MARGIN`] either side are looked at too, whose moments can fall inside the range.
259    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    /// The moment of a wall-clock time that has exactly one.
294    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    /// The first fire time after `t`, comparing every match from [`MARGIN`] before `t` to
302    /// [`MARGIN`] after the best one (a daylight-saving change can put a later wall-clock
303    /// time first).
304    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    /// The last fire time before `t`, as [`Self::walk_after`] does it.
326    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    /// The real moments of a matching wall-clock time, by the daylight-saving rules.
352    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
373/// Whether the hour field is one fixed hour (presets other than `@hourly` are).
374fn 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}