ppoppo-clock 0.1.1

Universal Clock + Timer port for ppoppo workspace — chat-as-infrastructure primitive
Documentation
//! Universal Clock + Timer port for the ppoppo workspace.
//!
//! Single deep-module port hiding the time-source substrate from every consumer.
//! Three impl arms gated by feature: `native` (Tokio), `wasm` (js_sys::Date +
//! Intl tz-name probe + Window.setTimeout), `mock` (FrozenClock + MockClock +
//! AdvanceableTimer). Zone math is arm-independent: jiff's bundled tzdb makes
//! `now_in`/`today_in` *provided* methods — each arm implements only `now()`.
//!
//! # SSOT relationship
//!
//! Standards: `STANDARDS_TIME_MECHANICS.md` §"Universal client + server time port"
//! (jiff surface per RFC_202607130309_jiff-migration). Engine precedent:
//! `ppoppo-token` (1st-party-consumed primitive, surface via SDK re-export).
//! External Developer Apps consume via `pas_external::clock::*` — never
//! path-dep this crate.
//!
//! # Dart mirror (CFC)
//!
//! `apps/cfc/lib/clock.dart` is the hand-maintained Dart shape mirror. Drift
//! detection deferred to a follow-up RFC. When changing trait shape here,
//! update the Dart mirror in the same commit.
//!
//! # 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`). The pre-jiff
//! plan to swap the wasm arm onto `js_sys::Temporal` is obsolete — the model
//! already lives in-process, identically on every arm.

#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::panic))]

use futures::future::BoxFuture;
use jiff::civil::Date;
use jiff::tz::TimeZone;
use jiff::{Timestamp, Zoned};
use std::sync::Arc;
use std::time::Duration;

/// Port vocabulary re-export — consumers name jiff types through the port
/// crate (and through `pas_external::clock::jiff` on the SDK surface).
pub use jiff;

#[cfg(feature = "native")]
pub mod native;
#[cfg(feature = "wasm")]
pub mod wasm;
#[cfg(feature = "mock")]
pub mod mock;

/// 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 {
    fn now(&self) -> Timestamp;

    fn now_in(&self, tz: &TimeZone) -> Zoned {
        self.now().to_zoned(tz.clone())
    }

    fn today_in(&self, tz: &TimeZone) -> Date {
        self.now_in(tz).date()
    }

    fn now_unix_millis(&self) -> i64 {
        self.now().as_millisecond()
    }
}

/// Async scheduling primitive. Single port for "wait N ms" / "yield event-loop tick".
pub trait Timer: Send + Sync + 'static {
    fn sleep(&self, dur: Duration) -> BoxFuture<'static, ()>;
    fn next_tick(&self) -> BoxFuture<'static, ()>;
}

/// Convenience aliases for the common injection shape.
pub type ArcClock = Arc<dyn Clock>;
pub type ArcTimer = Arc<dyn Timer>;

#[cfg(test)]
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);
    }
}