glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Cron expressions for recurring jobs: the five fields of crontab(5),
//! `minute hour day-of-month month day-of-week`.
//!
//! Each field takes `*`, numbers, ranges (`1-5`), lists (`1,15`) and steps
//! (`*/15`, `0-30/10`); months and weekdays also take names (`jan`, `mon`),
//! and Sunday is `0` or `7`. As in cron, when both day fields are
//! restricted a day matching either one counts. Shortcuts: `@hourly`,
//! `@daily` (`@midnight`), `@weekly`, `@monthly`, `@yearly` (`@annually`).

use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, TimeDelta, TimeZone, Timelike, Utc};
use chrono_tz::Tz;

/// A parsed cron expression, read in a time zone (UTC unless given).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cron {
    minutes: u64,
    hours: u64,
    days: u64,
    months: u64,
    weekdays: u64,
    /// Whether each day field was `*`, for cron's either-day rule.
    any_day: bool,
    any_weekday: bool,
    zone: Tz,
    /// Read in the app's time zone (`time_zone` in the config) when it's
    /// due, rather than `zone`: `at "10:00"`.
    app_zone: bool,
    /// As written, for `glacier jobs schedules`.
    source: String,
}

const MONTHS: [&str; 12] = [
    "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
const WEEKDAYS: [&str; 7] = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

impl Cron {
    /// Parses `expression`, as `"0 3 * * *"` or `"@daily"`.
    ///
    /// # Errors
    ///
    /// When it isn't five valid fields or a known shortcut; the message
    /// names the field.
    pub fn parse(expression: &str) -> crate::Result<Self> {
        Self::parse_text(expression).map_err(crate::Error::internal)
    }

    fn parse_text(expression: &str) -> Result<Self, String> {
        let expanded = match expression.trim() {
            "@hourly" => "0 * * * *",
            "@daily" | "@midnight" => "0 0 * * *",
            "@weekly" => "0 0 * * 0",
            "@monthly" => "0 0 1 * *",
            "@yearly" | "@annually" => "0 0 1 1 *",
            other => other,
        };
        let fields: Vec<&str> = expanded.split_whitespace().collect();
        let [minute, hour, day, month, weekday] = fields[..] else {
            return Err(format!(
                "`{expression}` should have five fields (minute hour day month weekday)"
            ));
        };
        let mut weekdays = field(weekday, 0, 7, &WEEKDAYS, "weekday")?;
        // 7 is Sunday too.
        if weekdays & (1 << 7) != 0 {
            weekdays = (weekdays & !(1 << 7)) | 1;
        }
        Ok(Self {
            minutes: field(minute, 0, 59, &[], "minute")?,
            hours: field(hour, 0, 23, &[], "hour")?,
            days: field(day, 1, 31, &[], "day of the month")?,
            months: field(month, 1, 12, &MONTHS, "month")?,
            weekdays,
            any_day: day == "*",
            any_weekday: weekday == "*",
            zone: Tz::UTC,
            app_zone: false,
            source: expression.trim().to_owned(),
        })
    }

    /// Every day at `time` (`"10:00"`, 24-hour) on the app's clock, its
    /// `time_zone`: `.at(…)` and `.glacier`'s `at "10:00"`.
    ///
    /// # Errors
    ///
    /// When `time` isn't `HH:MM`.
    pub fn daily_at(time: &str) -> crate::Result<Self> {
        let parsed = time
            .trim()
            .split_once(':')
            .and_then(|(h, m)| Some((h.parse::<u32>().ok()?, m.parse::<u32>().ok()?)))
            .filter(|(h, m)| *h < 24 && *m < 60 && time.trim().len() <= 5);
        let Some((hour, minute)) = parsed else {
            return Err(crate::Error::internal(format!(
                "`{time}` should be a time of day, as \"10:00\" or \"18:30\""
            )));
        };
        let mut cron = Self::parse(&format!("{minute} {hour} * * *"))?;
        cron.app_zone = true;
        cron.source = format!("at {time}");
        Ok(cron)
    }

    /// The schedule as written, with its zone: `0 3 * * *`, `at 10:00
    /// (Europe/London)`.
    pub fn describe(&self) -> String {
        format!("{} ({})", self.source, self.time_zone())
    }

    fn time_zone(&self) -> Tz {
        if self.app_zone {
            crate::time::zone().parse().unwrap_or(Tz::UTC)
        } else {
            self.zone
        }
    }

    /// Reads the expression in `zone`, an IANA name: `"0 3 * * *"` in
    /// `"Europe/London"` is 3am London time, whether that's GMT or BST.
    ///
    /// # Errors
    ///
    /// When there's no such zone.
    pub fn in_zone(mut self, zone: &str) -> crate::Result<Self> {
        self.app_zone = false;
        self.zone = zone
            .parse::<Tz>()
            .map_err(|_| crate::Error::internal(format!("`{zone}` isn't a time zone")))?;
        Ok(self)
    }

    /// The first time strictly after `after` that matches, or `None` if
    /// none does within five years (`0 0 31 2 *`, say).
    pub fn next_after(&self, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
        let zone = self.time_zone();
        let local = after.with_timezone(&zone).naive_local();
        let mut t = local.with_second(0)?.with_nanosecond(0)? + TimeDelta::minutes(1);
        let limit = local + TimeDelta::days(5 * 366);
        while t < limit {
            if !bit(self.months, t.month()) {
                t = first_of_next_month(t)?;
                continue;
            }
            if !self.day_matches(t.date()) {
                t = t.date().succ_opt()?.and_hms_opt(0, 0, 0)?;
                continue;
            }
            if !bit(self.hours, t.hour()) {
                t = t.with_minute(0)? + TimeDelta::hours(1);
                continue;
            }
            if !bit(self.minutes, t.minute()) {
                t += TimeDelta::minutes(1);
                continue;
            }
            // A time skipped by a clock change doesn't happen; one repeated
            // happens at its first occurrence.
            match zone.from_local_datetime(&t).earliest() {
                Some(at) if at.with_timezone(&Utc) > after => return Some(at.with_timezone(&Utc)),
                _ => t += TimeDelta::minutes(1),
            }
        }
        None
    }

    /// The latest time at or before `at` that matches, looking back at most
    /// `within`.
    pub fn latest_at_or_before(
        &self,
        at: DateTime<Utc>,
        within: TimeDelta,
    ) -> Option<DateTime<Utc>> {
        let mut latest = None;
        let mut from = at - within - TimeDelta::minutes(1);
        while let Some(next) = self.next_after(from) {
            if next > at {
                break;
            }
            latest = Some(next);
            from = next;
        }
        latest
    }

    fn day_matches(&self, date: NaiveDate) -> bool {
        let day = bit(self.days, date.day());
        let weekday = bit(self.weekdays, date.weekday().num_days_from_sunday());
        match (self.any_day, self.any_weekday) {
            (false, false) => day || weekday,
            _ => day && weekday,
        }
    }
}

impl std::str::FromStr for Cron {
    type Err = crate::Error;

    fn from_str(s: &str) -> crate::Result<Self> {
        Self::parse(s)
    }
}

fn bit(set: u64, n: u32) -> bool {
    set & (1 << n) != 0
}

fn first_of_next_month(t: NaiveDateTime) -> Option<NaiveDateTime> {
    let (year, month) = if t.month() == 12 {
        (t.year() + 1, 1)
    } else {
        (t.year(), t.month() + 1)
    };
    NaiveDate::from_ymd_opt(year, month, 1)?.and_hms_opt(0, 0, 0)
}

/// One field as a bit set of the values it allows.
fn field(text: &str, min: u32, max: u32, names: &[&str], what: &str) -> Result<u64, String> {
    let bad = || format!("`{text}` isn't a valid {what} (from {min} to {max})");
    let value = |part: &str| -> Result<u32, String> {
        let lower = part.to_ascii_lowercase();
        if let Some(i) = names.iter().position(|name| *name == lower) {
            // `jan` is 1, `sun` is 0: each list starts at the field's minimum.
            return Ok(u32::try_from(i).map_err(|_| bad())? + min);
        }
        let n: u32 = part.parse().map_err(|_| bad())?;
        if (min..=max).contains(&n) {
            Ok(n)
        } else {
            Err(bad())
        }
    };
    let mut set = 0u64;
    for part in text.split(',') {
        let (range, step) = match part.split_once('/') {
            Some((range, step)) => (
                range,
                step.parse::<u32>()
                    .ok()
                    .filter(|s| *s > 0)
                    .ok_or_else(bad)?,
            ),
            None => (part, 1),
        };
        let (from, to) = if range == "*" {
            (min, max)
        } else if let Some((a, b)) = range.split_once('-') {
            (value(a)?, value(b)?)
        } else {
            let n = value(range)?;
            // `5/15` means from 5 to the end, every 15.
            (n, if step > 1 { max } else { n })
        };
        if from > to {
            return Err(bad());
        }
        let mut n = from;
        while n <= to {
            set |= 1 << n;
            n += step;
        }
    }
    Ok(set)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(text: &str) -> DateTime<Utc> {
        DateTime::parse_from_rfc3339(text)
            .unwrap()
            .with_timezone(&Utc)
    }

    fn next(expr: &str, after: &str) -> String {
        Cron::parse(expr)
            .unwrap()
            .next_after(at(after))
            .unwrap()
            .to_rfc3339()
    }

    #[test]
    fn finds_the_next_matching_minute() {
        assert_eq!(
            next("* * * * *", "2026-10-04T10:00:30Z"),
            "2026-10-04T10:01:00+00:00"
        );
        assert_eq!(
            next("*/15 * * * *", "2026-10-04T10:00:00Z"),
            "2026-10-04T10:15:00+00:00"
        );
        assert_eq!(
            next("0 3 * * *", "2026-10-04T10:00:00Z"),
            "2026-10-05T03:00:00+00:00"
        );
        assert_eq!(
            next("@hourly", "2026-10-04T10:59:00Z"),
            "2026-10-04T11:00:00+00:00"
        );
        assert_eq!(
            next("0 0 1 jan *", "2026-10-04T10:00:00Z"),
            "2027-01-01T00:00:00+00:00"
        );
        assert_eq!(
            next("30 9 * * mon-fri", "2026-10-03T10:00:00Z"),
            "2026-10-05T09:30:00+00:00"
        );
        assert_eq!(
            next("0 12 * * 7", "2026-10-04T13:00:00Z"),
            "2026-10-11T12:00:00+00:00"
        );
        assert_eq!(
            next("0 0 29 2 *", "2026-10-04T00:00:00Z"),
            "2028-02-29T00:00:00+00:00"
        );
    }

    #[test]
    fn either_day_field_matches_when_both_are_set() {
        // The 13th, or any Friday.
        assert_eq!(
            next("0 0 13 * fri", "2026-10-04T00:00:00Z"),
            "2026-10-09T00:00:00+00:00"
        );
        assert_eq!(
            next("0 0 13 * fri", "2026-10-10T00:00:00Z"),
            "2026-10-13T00:00:00+00:00"
        );
    }

    #[test]
    fn reads_the_expression_in_its_zone() {
        let london = Cron::parse("0 3 * * *")
            .unwrap()
            .in_zone("Europe/London")
            .unwrap();
        // BST: 3am is 02:00 UTC; after the clocks go back it's 03:00 UTC.
        assert_eq!(
            london
                .next_after(at("2026-10-04T12:00:00Z"))
                .unwrap()
                .to_rfc3339(),
            "2026-10-05T02:00:00+00:00"
        );
        assert_eq!(
            london
                .next_after(at("2026-11-04T12:00:00Z"))
                .unwrap()
                .to_rfc3339(),
            "2026-11-05T03:00:00+00:00"
        );
    }

    #[test]
    fn finds_the_latest_run_within_a_window() {
        let hourly = Cron::parse("0 * * * *").unwrap();
        let latest = hourly.latest_at_or_before(at("2026-10-04T10:03:00Z"), TimeDelta::minutes(5));
        assert_eq!(latest.unwrap().to_rfc3339(), "2026-10-04T10:00:00+00:00");
        assert_eq!(
            hourly.latest_at_or_before(at("2026-10-04T10:30:00Z"), TimeDelta::minutes(5)),
            None
        );
        assert_eq!(
            hourly
                .latest_at_or_before(at("2026-10-04T10:00:00Z"), TimeDelta::minutes(5))
                .unwrap()
                .to_rfc3339(),
            "2026-10-04T10:00:00+00:00"
        );
    }

    #[test]
    fn rejects_bad_expressions() {
        for bad in [
            "",
            "* * * *",
            "60 * * * *",
            "* 24 * * *",
            "* * 0 * *",
            "*/0 * * * *",
            "5-1 * * * *",
            "* * * foo *",
        ] {
            assert!(Cron::parse(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn a_time_of_day_is_daily() {
        let cron = Cron::daily_at("10:30").unwrap();
        assert_eq!(
            cron.next_after(at("2026-10-04T11:00:00Z"))
                .unwrap()
                .to_rfc3339(),
            "2026-10-05T10:30:00+00:00"
        );
        assert_eq!(cron.describe(), "at 10:30 (UTC)");
        assert_eq!(
            Cron::parse("0 3 * * *").unwrap().describe(),
            "0 3 * * * (UTC)"
        );
        for bad in ["25:00", "10", "10:60", "ten"] {
            assert!(Cron::daily_at(bad).is_err(), "{bad}");
        }
    }
}