glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Times in a place: a UTC timestamp shown on a hospital's (or a user's)
//! wall clock, as Rails' `in_time_zone`.

use std::future::Future;
use std::sync::{Arc, Mutex};

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

tokio::task_local! {
    /// A test's clock: `Some` while it has travelled.
    static CLOCK: Arc<Mutex<Option<DateTime<Utc>>>>;
}

/// The time now, in UTC: what records are stamped with and jobs are due
/// by. Tests can move it (`glacier::testing::travel_to`). In `.glacier`,
/// `Timestamp.now()`.
pub fn now() -> DateTime<Utc> {
    CLOCK
        .try_with(|clock| *clock.lock().unwrap_or_else(|e| e.into_inner()))
        .ok()
        .flatten()
        .unwrap_or_else(Utc::now)
}

/// Today's date, in UTC. In `.glacier`, `Date.today()`.
pub fn today() -> NaiveDate {
    now().date_naive()
}

/// Runs `fut` with a clock that `glacier::testing::travel_to` can move.
/// `#[glacier::test]` does this for every test.
#[doc(hidden)]
pub async fn with_test_clock<F: Future>(fut: F) -> F::Output {
    CLOCK.scope(Arc::default(), fut).await
}

/// Sets the test clock: `false` outside a test. Kept to whole
/// microseconds, as Postgres stores times, so a time saved and read back
/// equals the frozen `now()` (Linux's clock has nanoseconds).
pub(crate) fn set_clock(at: Option<DateTime<Utc>>) -> bool {
    use chrono::SubsecRound as _;
    let at = at.map(|at| at.trunc_subsecs(6));
    CLOCK
        .try_with(|clock| *clock.lock().unwrap_or_else(|e| e.into_inner()) = at)
        .is_ok()
}

/// `Timestamp.now()`: [`now`].
pub trait Now {
    fn now() -> Self;
}

impl Now for DateTime<Utc> {
    fn now() -> Self {
        now()
    }
}

/// `NaiveTimestamp.now()`, for Rails' `timestamp without time zone`
/// columns: the time now in UTC, without the zone.
impl Now for NaiveDateTime {
    fn now() -> Self {
        now().naive_utc()
    }
}

/// `Date.today()`: [`today`].
pub trait Today {
    fn today() -> Self;
}

impl Today for NaiveDate {
    fn today() -> Self {
        today()
    }
}

/// Lengths of time from a number, as Rails' `30.days`: `30.days()`,
/// `2.hours()`.
pub trait Durations {
    fn seconds(self) -> TimeDelta;
    fn minutes(self) -> TimeDelta;
    fn hours(self) -> TimeDelta;
    fn days(self) -> TimeDelta;
    fn weeks(self) -> TimeDelta;
}

impl Durations for i64 {
    fn seconds(self) -> TimeDelta {
        TimeDelta::seconds(self)
    }
    fn minutes(self) -> TimeDelta {
        TimeDelta::minutes(self)
    }
    fn hours(self) -> TimeDelta {
        TimeDelta::hours(self)
    }
    fn days(self) -> TimeDelta {
        TimeDelta::days(self)
    }
    fn weeks(self) -> TimeDelta {
        TimeDelta::weeks(self)
    }
}

/// A length of time before or after now: `30.days().ago()`,
/// `2.hours().from_now()`.
pub trait Relative {
    fn ago(self) -> DateTime<Utc>;
    // Rails' name, not a conversion.
    #[allow(clippy::wrong_self_convention)]
    fn from_now(self) -> DateTime<Utc>;
}

impl Relative for TimeDelta {
    fn ago(self) -> DateTime<Utc> {
        now() - self
    }
    fn from_now(self) -> DateTime<Utc> {
        now() + self
    }
}

/// `at` (UTC) on the clock of `zone`, an IANA name such as
/// `"Europe/London"`; `None` for a zone it doesn't know.
pub fn in_zone(at: DateTime<Utc>, zone: &str) -> Option<DateTime<Tz>> {
    let zone: Tz = zone.parse().ok()?;
    Some(at.with_timezone(&zone))
}

/// `at` (UTC) formatted on the clock of `zone` with a `strftime` pattern,
/// as Rails' `time.in_time_zone(zone).strftime(format)`.
pub fn format_in_zone(at: DateTime<Utc>, zone: &str, format: &str) -> Option<String> {
    in_zone(at, zone).map(|local| local.format(format).to_string())
}

/// [`format_in_zone`] for a `timestamp without time zone` taken as UTC.
pub fn format_naive_in_zone(at: NaiveDateTime, zone: &str, format: &str) -> Option<String> {
    format_in_zone(at.and_utc(), zone, format)
}

/// An HTTP date (`Thu, 01 Oct 2026 10:52:12 GMT`), as Rails' `Time.parse`
/// reads one: the weekday isn't checked against the date.
pub fn parse_http_date(text: &str) -> Option<DateTime<Utc>> {
    let text = text.trim();
    let without_weekday = text.split_once(", ").map_or(text, |(_, rest)| rest);
    DateTime::parse_from_rfc2822(without_weekday)
        .or_else(|_| DateTime::parse_from_rfc2822(text))
        .ok()
        .map(|at| at.with_timezone(&Utc))
}

/// A date or time as a client sends it, read as Rails' `Time.zone.parse`
/// reads the common forms: RFC 3339 (`2026-10-05T11:00:00Z`, with its own
/// offset), or a date or date and time without one (`2026-10-05`,
/// `2026-10-05 11:00`, `2026-10-05T11:00:00.5`), on the clock of `zone`.
/// An HTTP date works too. `None` for anything else.
pub fn parse(text: &str, zone: &str) -> Option<DateTime<Utc>> {
    let text = text.trim();
    if let Ok(at) = DateTime::parse_from_rfc3339(text) {
        return Some(at.with_timezone(&Utc));
    }
    let local = [
        "%Y-%m-%dT%H:%M:%S%.f",
        "%Y-%m-%d %H:%M:%S%.f",
        "%Y-%m-%dT%H:%M",
        "%Y-%m-%d %H:%M",
    ]
    .iter()
    .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok())
    .or_else(|| {
        chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d")
            .ok()
            .and_then(|date| date.and_hms_opt(0, 0, 0))
    });
    match local {
        Some(local) => local_to_utc(local, zone).map(|at| at.and_utc()),
        None => parse_http_date(text),
    }
}

/// A wall-clock time in `zone` as UTC, for storing: Rails' `end_of_day` on
/// a local time, saved. An ambiguous time (clocks going back) takes the
/// earlier; one skipped (clocks going forward) is `None`.
pub fn local_to_utc(local: NaiveDateTime, zone: &str) -> Option<NaiveDateTime> {
    let zone: Tz = zone.parse().ok()?;
    zone.from_local_datetime(&local)
        .earliest()
        .map(|at| at.naive_utc())
}

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

    #[tokio::test]
    async fn a_frozen_clock_keeps_whole_microseconds() {
        with_test_clock(async {
            let at = DateTime::parse_from_rfc3339("2026-10-05T12:32:14.175663533Z")
                .unwrap()
                .with_timezone(&Utc);
            assert!(set_clock(Some(at)));
            assert_eq!(now().to_rfc3339(), "2026-10-05T12:32:14.175663+00:00");
        })
        .await;
    }

    #[test]
    fn parses_as_time_zone_parse() {
        let at = |text: &str, zone: &str| parse(text, zone).map(|t| t.to_rfc3339());
        let utc = Some("2026-10-05T00:00:00+00:00".to_owned());
        assert_eq!(at("2026-10-05", "UTC"), utc);
        assert_eq!(at(" 2026-10-05 ", "Etc/UTC"), utc);
        assert_eq!(
            at("2026-10-05", "Europe/London"),
            Some("2026-10-04T23:00:00+00:00".to_owned()),
            "midnight on the zone's clock"
        );
        assert_eq!(
            at("2026-10-05T11:00:00Z", "Europe/London"),
            Some("2026-10-05T11:00:00+00:00".to_owned()),
            "an offset wins"
        );
        assert_eq!(
            at("2026-10-05 11:30", "UTC"),
            Some("2026-10-05T11:30:00+00:00".to_owned())
        );
        assert_eq!(
            at("2026-10-05T11:30:15.250", "UTC"),
            Some("2026-10-05T11:30:15.250+00:00".to_owned())
        );
        assert_eq!(at("garbage", "UTC"), None);
        assert_eq!(at("2026-13-45", "UTC"), None);
    }

    #[test]
    fn reads_http_dates_whatever_the_weekday() {
        let at = parse_http_date("Mon, 01 Jan 2030 00:00:00 GMT").unwrap();
        assert_eq!(
            at.to_rfc3339(),
            "2030-01-01T00:00:00+00:00",
            "1 Jan 2030 is a Tuesday"
        );
        assert!(parse_http_date("not a date").is_none());
    }

    #[test]
    fn stores_local_times_as_utc() {
        let local = chrono::NaiveDate::from_ymd_opt(2026, 8, 3)
            .unwrap()
            .and_hms_opt(23, 59, 59)
            .unwrap();
        assert_eq!(
            local_to_utc(local, "Europe/London").unwrap().to_string(),
            "2026-08-03 22:59:59"
        );
        assert!(local_to_utc(local, "Nowhere/Else").is_none());
    }

    #[test]
    fn shows_utc_times_on_local_clocks() {
        let at = DateTime::parse_from_rfc3339("2026-08-03T19:24:07Z")
            .unwrap()
            .to_utc();
        assert_eq!(
            format_in_zone(at, "Europe/London", "%d-%b-%Y %H:%M").as_deref(),
            Some("03-Aug-2026 20:24"),
            "British Summer Time"
        );
        let winter = DateTime::parse_from_rfc3339("2026-01-05T23:30:00Z")
            .unwrap()
            .to_utc();
        assert_eq!(
            format_in_zone(winter, "Australia/Sydney", "%d/%m/%Y").as_deref(),
            Some("06/01/2026")
        );
        assert_eq!(format_in_zone(at, "Nowhere/Special", "%Y"), None);
    }
}