glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! 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,
}

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,
        })
    }

    /// 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.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 local = after.with_timezone(&self.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 self.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:?}");
        }
    }
}