ppoppo-clock 1.0.0

Universal Clock + Timer port for ppoppo workspace — chat-as-infrastructure primitive
Documentation
#![doc = include_str!("../README.md")]
//!
//! **STABLE VOCABULARY.** Nameable by any application, semver-versioned on its
//! own: the port's signature changes only on a major version. Every ppoppo
//! face takes and returns these traits, so a consumer holding an
//! [`ArcClock`] built here hands the same value to each face.
//!
//! # The port
//!
//! A single deep module hiding the time source from every consumer. Three
//! impl arms, each behind a feature: `native` (Tokio), `wasm`
//! (`js_sys::Date` + an `Intl` time-zone-name probe + `Window.setTimeout`),
//! `mock` (frozen and advanceable clocks plus a timer driven by them). Zone
//! math is arm-independent: jiff's bundled tzdb makes [`Clock::now_in`] and
//! [`Clock::today_in`] *provided* methods, so each arm implements only
//! [`Clock::now`].
//!
//! Standards: `STS_TIME_MECHANICS.md` §"Universal client + server time port".
//! Inside the ppoppo workspace the xtask CLOCK-PORT rule refuses an ambient
//! time source outside this crate.
//!
//! # Temporal alignment
//!
//! jiff is the Rust realization of the TC39 Temporal model (`Timestamp` ≙
//! `Temporal.Instant`, `Zoned` ≙ `Temporal.ZonedDateTime`, `civil::Date` ≙
//! `Temporal.PlainDate`, `tz::TimeZone` ≙ `Temporal.TimeZone`), identically
//! on every arm.

#![deny(rust_2018_idioms)]
#![deny(missing_docs)]
#![warn(missing_debug_implementations)]

use jiff::civil::Date;
use jiff::tz::TimeZone;
use jiff::{Timestamp, Zoned};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

/// The port's value types — `Timestamp`, `Zoned`, `tz::TimeZone`,
/// `civil::Date` — re-exported so a consumer names the exact jiff version the
/// port speaks. The one sanctioned whole-crate foreign door in the family.
pub use jiff;

/// Deterministic test arm: a frozen clock, a settable clock, and a timer
/// whose sleeps resolve only when that clock is advanced.
#[cfg(feature = "mock")]
pub mod mock;
/// Tokio arm: the system wall clock and a Tokio-backed timer.
#[cfg(feature = "native")]
pub mod native;
/// Browser arm: `Date.now()` as the clock and `Window.setTimeout` as the
/// timer.
#[cfg(feature = "wasm")]
pub mod wasm;

/// Wall-clock readouts. Single port for "what time is it?" across all surfaces.
///
/// `now()` is the only required method; the zone-aware readouts derive from it
/// via jiff (tzdb available on every arm, including wasm via the bundled db).
pub trait Clock: Send + Sync + 'static {
    /// The current instant. The one method an arm implements.
    fn now(&self) -> Timestamp;

    /// The current instant as a wall-clock reading in `tz`.
    fn now_in(&self, tz: &TimeZone) -> Zoned {
        self.now().to_zoned(tz.clone())
    }

    /// Today's calendar date in `tz` — the date a person in that zone reads
    /// off their calendar, which differs from the UTC date near midnight.
    fn today_in(&self, tz: &TimeZone) -> Date {
        self.now_in(tz).date()
    }

    /// The current instant as Unix epoch milliseconds.
    fn now_unix_millis(&self) -> i64 {
        self.now().as_millisecond()
    }
}

/// Async scheduling primitive. Single port for "wait N ms" / "yield event-loop tick".
///
/// The futures are written out as `Pin<Box<dyn Future + Send>>` — every name
/// in them is `core`'s. An alias from `futures` would put a foreign crate on
/// this vocabulary's surface (RFC_202610142318 R4); `futures::future::BoxFuture`
/// is the same type, so an implementor may still spell it that way.
pub trait Timer: Send + Sync + 'static {
    /// A future that completes once `dur` has elapsed on this timer.
    fn sleep(&self, dur: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>>;
    /// A future that completes on the runtime's next scheduling turn — a
    /// yield, not a delay.
    fn next_tick(&self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
}

/// A shared [`Clock`] — the shape every ppoppo constructor takes.
pub type ArcClock = Arc<dyn Clock>;
/// A shared [`Timer`] — the shape every ppoppo constructor takes.
pub type ArcTimer = Arc<dyn Timer>;

#[cfg(test)]
// Outer, not the usual inner `#![allow(..)]`: ARCH-BOUNDARY pins the exact
// inner-attribute block of a published-tier `lib.rs` and scans every line,
// so an indented inner attribute inside this module trips it too.
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    /// Fixed-instant clock for exercising the provided methods without any
    /// feature arm — zone math must be identical regardless of arm.
    struct FixedClock(Timestamp);

    impl Clock for FixedClock {
        fn now(&self) -> Timestamp {
            self.0
        }
    }

    fn utc_midnight_2026_05_10() -> Timestamp {
        "2026-05-10T00:00:00Z".parse().expect("valid RFC 3339")
    }

    #[test]
    fn now_in_seoul_utc_midnight_is_hour_9() {
        // UTC 2026-05-10 00:00 → KST 09:00 (UTC+9, no DST in Korea)
        let clock = FixedClock(utc_midnight_2026_05_10());
        let tz = TimeZone::get("Asia/Seoul").expect("tzdb has Seoul");
        assert_eq!(clock.now_in(&tz).hour(), 9);
    }

    #[test]
    fn today_in_crosses_date_line() {
        // UTC 2026-05-10 23:30 is already 2026-05-11 in Seoul.
        let clock = FixedClock("2026-05-10T23:30:00Z".parse().expect("valid"));
        let tz = TimeZone::get("Asia/Seoul").expect("tzdb has Seoul");
        assert_eq!(clock.today_in(&tz), jiff::civil::date(2026, 5, 11));
        assert_eq!(
            clock.today_in(&TimeZone::UTC),
            jiff::civil::date(2026, 5, 10)
        );
    }

    #[test]
    fn dst_transition_new_york_2024() {
        // America/New_York spring-forward 2024-03-10 02:00 → 03:00
        // 06:59 UTC = 01:59 EST; 07:00 UTC = 03:00 EDT
        let tz = TimeZone::get("America/New_York").expect("tzdb has NY");
        let before = FixedClock("2024-03-10T06:59:00Z".parse().expect("valid"));
        let after = FixedClock("2024-03-10T07:00:00Z".parse().expect("valid"));
        assert_eq!(before.now_in(&tz).hour(), 1);
        assert_eq!(after.now_in(&tz).hour(), 3);
    }

    #[test]
    fn now_unix_millis_matches_timestamp() {
        let clock = FixedClock("1970-01-01T00:00:01Z".parse().expect("valid"));
        assert_eq!(clock.now_unix_millis(), 1_000);
    }

    #[test]
    fn dow_monday0_convention_via_zoned() {
        // 2026-05-10 is a Sunday → to_monday_zero_offset() == 6
        let clock = FixedClock("2026-05-10T12:00:00Z".parse().expect("valid"));
        let zdt = clock.now_in(&TimeZone::UTC);
        assert_eq!(zdt.weekday().to_monday_zero_offset(), 6);
    }
}