Skip to main content

ppoppo_clock/
lib.rs

1//! **NOT a stable public API.** Engine-tier time port — **3rd parties** reach
2//! it via the SDK-family re-exports (e.g. `ppoppo_pas_external::clock::*`) and never
3//! name this crate directly. 1st-party clients outside this workspace do name
4//! it: the standalone CCC repo (RFC_202607180403) depends on it from
5//! crates.io, and must pin the same family version `ppoppo-chat-client`
6//! requires or cargo resolves two copies and the shared `Clock` trait stops
7//! typechecking across them. Do not build a 3rd-party integration on this
8//! crate's API expecting stability.
9//!
10//! Universal Clock + Timer port for the ppoppo workspace.
11//!
12//! Single deep-module port hiding the time-source substrate from every consumer.
13//! Three impl arms gated by feature: `native` (Tokio), `wasm` (js_sys::Date +
14//! Intl tz-name probe + Window.setTimeout), `mock` (FrozenClock + MockClock +
15//! AdvanceableTimer). Zone math is arm-independent: jiff's bundled tzdb makes
16//! `now_in`/`today_in` *provided* methods — each arm implements only `now()`.
17//!
18//! # SSOT relationship
19//!
20//! Standards: `STANDARDS_TIME_MECHANICS.md` §"Universal client + server time port"
21//! (jiff surface per RFC_202607130309_jiff-migration). Engine precedent:
22//! `ppoppo-token` (1st-party-consumed primitive, surface via SDK re-export).
23//! External Developer Apps consume via `ppoppo_pas_external::clock::*` — never
24//! path-dep this crate.
25//!
26//! # Dart mirror (CFC)
27//!
28//! `apps/cfc/lib/clock.dart` is the hand-maintained Dart shape mirror. Drift
29//! detection deferred to a follow-up RFC. When changing trait shape here,
30//! update the Dart mirror in the same commit.
31//!
32//! # Temporal alignment
33//!
34//! jiff is the Rust realization of the TC39 Temporal model (`Timestamp` ≙
35//! `Temporal.Instant`, `Zoned` ≙ `Temporal.ZonedDateTime`, `civil::Date` ≙
36//! `Temporal.PlainDate`, `tz::TimeZone` ≙ `Temporal.TimeZone`). The pre-jiff
37//! plan to swap the wasm arm onto `js_sys::Temporal` is obsolete — the model
38//! already lives in-process, identically on every arm.
39
40#![deny(rust_2018_idioms)]
41#![warn(missing_debug_implementations)]
42
43use futures::future::BoxFuture;
44use jiff::civil::Date;
45use jiff::tz::TimeZone;
46use jiff::{Timestamp, Zoned};
47use std::sync::Arc;
48use std::time::Duration;
49
50/// Port vocabulary re-export — consumers name jiff types through the port
51/// crate (and through `ppoppo_pas_external::clock::jiff` on the SDK surface).
52pub use jiff;
53
54#[cfg(feature = "native")]
55pub mod native;
56#[cfg(feature = "wasm")]
57pub mod wasm;
58#[cfg(feature = "mock")]
59pub mod mock;
60
61/// Wall-clock readouts. Single port for "what time is it?" across all surfaces.
62///
63/// `now()` is the only required method; the zone-aware readouts derive from it
64/// via jiff (tzdb available on every arm, including wasm via the bundled db).
65pub trait Clock: Send + Sync + 'static {
66    fn now(&self) -> Timestamp;
67
68    fn now_in(&self, tz: &TimeZone) -> Zoned {
69        self.now().to_zoned(tz.clone())
70    }
71
72    fn today_in(&self, tz: &TimeZone) -> Date {
73        self.now_in(tz).date()
74    }
75
76    fn now_unix_millis(&self) -> i64 {
77        self.now().as_millisecond()
78    }
79}
80
81/// Async scheduling primitive. Single port for "wait N ms" / "yield event-loop tick".
82pub trait Timer: Send + Sync + 'static {
83    fn sleep(&self, dur: Duration) -> BoxFuture<'static, ()>;
84    fn next_tick(&self) -> BoxFuture<'static, ()>;
85}
86
87/// Convenience aliases for the common injection shape.
88pub type ArcClock = Arc<dyn Clock>;
89pub type ArcTimer = Arc<dyn Timer>;
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    /// Fixed-instant clock for exercising the provided methods without any
96    /// feature arm — zone math must be identical regardless of arm.
97    struct FixedClock(Timestamp);
98
99    impl Clock for FixedClock {
100        fn now(&self) -> Timestamp {
101            self.0
102        }
103    }
104
105    fn utc_midnight_2026_05_10() -> Timestamp {
106        "2026-05-10T00:00:00Z".parse().expect("valid RFC 3339")
107    }
108
109    #[test]
110    fn now_in_seoul_utc_midnight_is_hour_9() {
111        // UTC 2026-05-10 00:00 → KST 09:00 (UTC+9, no DST in Korea)
112        let clock = FixedClock(utc_midnight_2026_05_10());
113        let tz = TimeZone::get("Asia/Seoul").expect("tzdb has Seoul");
114        assert_eq!(clock.now_in(&tz).hour(), 9);
115    }
116
117    #[test]
118    fn today_in_crosses_date_line() {
119        // UTC 2026-05-10 23:30 is already 2026-05-11 in Seoul.
120        let clock = FixedClock("2026-05-10T23:30:00Z".parse().expect("valid"));
121        let tz = TimeZone::get("Asia/Seoul").expect("tzdb has Seoul");
122        assert_eq!(clock.today_in(&tz), jiff::civil::date(2026, 5, 11));
123        assert_eq!(clock.today_in(&TimeZone::UTC), jiff::civil::date(2026, 5, 10));
124    }
125
126    #[test]
127    fn dst_transition_new_york_2024() {
128        // America/New_York spring-forward 2024-03-10 02:00 → 03:00
129        // 06:59 UTC = 01:59 EST; 07:00 UTC = 03:00 EDT
130        let tz = TimeZone::get("America/New_York").expect("tzdb has NY");
131        let before = FixedClock("2024-03-10T06:59:00Z".parse().expect("valid"));
132        let after = FixedClock("2024-03-10T07:00:00Z".parse().expect("valid"));
133        assert_eq!(before.now_in(&tz).hour(), 1);
134        assert_eq!(after.now_in(&tz).hour(), 3);
135    }
136
137    #[test]
138    fn now_unix_millis_matches_timestamp() {
139        let clock = FixedClock("1970-01-01T00:00:01Z".parse().expect("valid"));
140        assert_eq!(clock.now_unix_millis(), 1_000);
141    }
142
143    #[test]
144    fn dow_monday0_convention_via_zoned() {
145        // 2026-05-10 is a Sunday → to_monday_zero_offset() == 6
146        let clock = FixedClock("2026-05-10T12:00:00Z".parse().expect("valid"));
147        let zdt = clock.now_in(&TimeZone::UTC);
148        assert_eq!(zdt.weekday().to_monday_zero_offset(), 6);
149    }
150}