Cotton code
175 lines · 6.4 KB · RustRaw
//! The one way anything in this server learns what time it is.//!//! `deps.now()` in the TypeScript — a function on the deps rather than a call//! to `new Date()`, because a suite that fixed the clock has to see the time it//! fixed, and because half the refusals on the device chokepoint are ABOUT//! time (`device_clock` names `serverTime`, a nonce is remembered for 240 s, a//! pairing code expires in 90).//!//! The store crate holds no clock at all (spec R7); this is the server's, and//! it is injected for the same reason.use std::sync::{Arc, Mutex};use chrono::{DateTime, Utc};/// What time it is, as far as this server is concerned.pub trait Clock: Send + Sync + std::fmt::Debug {    fn now(&self) -> DateTime<Utc>;}/// The wall clock. The one implementation a running server uses.#[derive(Debug, Clone, Copy, Default)]pub struct SystemClock;impl Clock for SystemClock {    fn now(&self) -> DateTime<Utc> {        Utc::now()    }}/// A clock a test sets and moves.////// `advance` rather than only `set` because most suites want "and then a minute/// later", and computing the second instant from the first is where an/// off-by-an-hour hides.#[derive(Debug, Clone)]pub struct FixedClock {    at: Arc<Mutex<DateTime<Utc>>>,}impl FixedClock {    pub fn new(at: DateTime<Utc>) -> FixedClock {        FixedClock {            at: Arc::new(Mutex::new(at)),        }    }    /// The instant most suites start from. Any fixed instant would do; one    /// shared constant means two suites comparing stamps agree.    pub fn default_start() -> FixedClock {        FixedClock::new(            DateTime::parse_from_rfc3339("2026-09-08T10:00:00Z")                .expect("a literal instant")                .with_timezone(&Utc),        )    }    pub fn set(&self, at: DateTime<Utc>) {        *self.at.lock().unwrap_or_else(|error| error.into_inner()) = at;    }    pub fn advance(&self, by: chrono::Duration) {        let mut guard = self.at.lock().unwrap_or_else(|error| error.into_inner());        *guard += by;    }}impl Clock for FixedClock {    fn now(&self) -> DateTime<Utc> {        *self.at.lock().unwrap_or_else(|error| error.into_inner())    }}/// `Date.prototype.toISOString()` — always UTC, always three fractional/// digits, always a `Z`.////// Every timestamp this server writes crosses to a TypeScript client or into a/// column a TypeScript writer also writes, so the SHAPE is wire, not taste:/// chrono's `to_rfc3339` would write `+00:00` and a variable number of/// fractional digits, and two spellings of one instant in one column is a/// comparison that silently stops matching.pub fn iso(at: DateTime<Utc>) -> String {    at.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()}/// A person's own wall clock, as the two things a nightly worker asks of it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LocalNow {    /// `YYYY-MM-DD` in their zone. The stamp a "once per local night" gate is    /// kept against — a DATE, never an instant, because "has tonight happened"    /// means the night they are living in.    pub date: String,    /// Minutes past local midnight.    pub minutes: i64,}/// What day and what time it is where the person is.////// Shared because the host runs `TZ=UTC`: every worker with a local window/// (money notices at 09:30, summaries at 03:00) needs the same reading, and/// India's half-hour offset is exactly the case a naive hours-based/// implementation gets wrong.////// An UNKNOWN zone falls back to UTC rather than failing, exactly as the/// TypeScript's `try { new Intl.DateTimeFormat(zone) } catch` does — it is data/// arriving from a column, not a reason for the sweep to stop. A caller that/// must NOT run on the host's clock asks whether the zone is known BEFORE/// calling this (the summaries worker rests instead); that decision belongs to/// the worker, not to the clock.pub fn local_now(now: DateTime<Utc>, timezone: &str) -> LocalNow {    let parts = cotton_core::transforms::zoned_clock::zoned_parts(now.timestamp_millis(), timezone)        .or_else(|_| cotton_core::transforms::zoned_clock::zoned_parts(now.timestamp_millis(), "UTC"));    match parts {        Ok(parts) => LocalNow {            date: format!("{:04}-{:02}-{:02}", parts.year, parts.month, parts.day),            minutes: parts.hour * 60 + parts.minute,        },        // Unreachable for any instant a `DateTime<Utc>` can hold; answered        // rather than panicked so this function has no panic path at all.        Err(_) => LocalNow {            date: now.format("%Y-%m-%d").to_string(),            minutes: i64::from(now.format("%H").to_string().parse::<u32>().unwrap_or(0)) * 60,        },    }}#[cfg(test)]mod tests {    use super::*;    #[test]    fn iso_is_to_iso_string() {        let at = DateTime::parse_from_rfc3339("2026-09-08T10:00:00Z")            .unwrap()            .with_timezone(&Utc);        assert_eq!(iso(at), "2026-09-08T10:00:00.000Z");        let with_millis = DateTime::parse_from_rfc3339("2026-09-08T10:00:00.007Z")            .unwrap()            .with_timezone(&Utc);        assert_eq!(iso(with_millis), "2026-09-08T10:00:00.007Z");    }    #[test]    fn local_now_reads_the_person_s_own_half_hour_offset() {        let at = DateTime::parse_from_rfc3339("2026-09-03T22:30:00Z")            .unwrap()            .with_timezone(&Utc);        // 04:00 on the 4th in Kolkata — the date turns over and the offset is        // not a whole number of hours.        let local = local_now(at, "Asia/Kolkata");        assert_eq!(local.date, "2026-09-04");        assert_eq!(local.minutes, 4 * 60);        assert_eq!(local_now(at, "UTC").date, "2026-09-03");        assert_eq!(local_now(at, "UTC").minutes, 22 * 60 + 30);    }    #[test]    fn an_unknown_zone_reads_as_utc_rather_than_failing() {        let at = DateTime::parse_from_rfc3339("2026-09-03T22:30:00Z")            .unwrap()            .with_timezone(&Utc);        assert_eq!(local_now(at, "Mars/Olympus"), local_now(at, "UTC"));    }    #[test]    fn a_fixed_clock_does_not_move_on_its_own_and_moves_when_told() {        let clock = FixedClock::default_start();        let first = clock.now();        assert_eq!(first, clock.now());        clock.advance(chrono::Duration::seconds(90));        assert_eq!(clock.now() - first, chrono::Duration::seconds(90));        assert_eq!(iso(clock.now()), "2026-09-08T10:01:30.000Z");    }}