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