kernel/time.rs
1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Portable monotonic time.
8//!
9//! [`PortableInstant`] is a plain `u64` — milliseconds elapsed since an
10//! implementation-chosen origin (typically application start). The
11//! runtime never asks the platform "what time is it now"; instead, the
12//! host emits a `PortableInstant` per frame (or per event) drawn from
13//! whatever monotonic clock it prefers, and the runtime uses it for
14//! comparisons / deadlines.
15//!
16//! Desktop hosts derive `PortableInstant` from `std::time::Instant`
17//! (monotonic by construction). WASM hosts derive it from
18//! `performance.now()` (also monotonic). Because the origin is
19//! host-chosen, values from different hosts are not comparable — this
20//! is a host-bounded monotonic clock, not a global wall clock. Use
21//! [`UNIX_EPOCH`](std::time::UNIX_EPOCH)-relative timestamps for
22//! anything user-visible or persisted; use `PortableInstant` for
23//! ephemeral things like animation timers and request deadlines.
24//!
25//! Design choice: why a newtype instead of a plain `u64`?
26//!
27//! - Prevents accidental mixing of "ms since epoch" (a `u64`) with
28//! "ms-as-duration" (also `u64`). A deadline plus a duration yields
29//! a new deadline; a deadline minus another deadline yields a
30//! duration. The arithmetic is encoded in the method signatures.
31//! - Makes the portability intent explicit at type-checking time:
32//! call sites that still reach for `std::time::Instant::now()` will
33//! fail to compile against a `PortableInstant` field, surfacing
34//! the host-boundary violation.
35//!
36//! WASM portability: no `std::time::Instant`, no
37//! `std::time::SystemTime::now()`, no `std::thread`. `PortableInstant` is pure
38//! `u64` arithmetic; the wall-clock helpers use `web_time`.
39
40use serde::{Deserialize, Serialize};
41
42/// Wall-clock milliseconds since the Unix epoch.
43///
44/// `web_time` re-exports `std::time` on native targets and uses `Date.now()` in
45/// browser WASM, so persisted graph timestamps never call the unsupported
46/// `std::time::SystemTime::now()` implementation.
47pub(crate) fn unix_epoch_millis() -> u64 {
48 web_time::SystemTime::now()
49 .duration_since(web_time::UNIX_EPOCH)
50 .map(|duration| duration.as_millis() as u64)
51 .unwrap_or(0)
52}
53
54/// Wall-clock seconds since the Unix epoch.
55pub(crate) fn unix_epoch_seconds() -> u64 {
56 web_time::SystemTime::now()
57 .duration_since(web_time::UNIX_EPOCH)
58 .map(|duration| duration.as_secs())
59 .unwrap_or(0)
60}
61
62/// The wall clock as a `std::time::SystemTime`, for crates that persist one
63/// and may run in a browser, where `SystemTime::now()` panics.
64pub fn wall_clock_now() -> std::time::SystemTime {
65 let since = web_time::SystemTime::now()
66 .duration_since(web_time::UNIX_EPOCH)
67 .unwrap_or_default();
68 std::time::UNIX_EPOCH + since
69}
70
71/// Host-provided monotonic timestamp, measured in milliseconds from a
72/// host-chosen origin.
73///
74/// The origin is typically the host-process start time. The runtime
75/// treats the origin as opaque: two `PortableInstant`s from the same
76/// host are comparable, but values from different hosts (or from the
77/// same host across restarts) are not.
78#[derive(
79 Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
80)]
81#[serde(transparent)]
82pub struct PortableInstant(pub u64);
83
84impl PortableInstant {
85 /// The zero-instant (origin). Used as a sentinel for "never" in
86 /// some deadline fields; prefer `Option<PortableInstant>` for
87 /// optional deadlines rather than relying on this value.
88 pub const ORIGIN: Self = Self(0);
89
90 /// Raw milliseconds from origin.
91 pub fn millis(self) -> u64 {
92 self.0
93 }
94
95 /// Saturating elapsed-duration (in ms) between two instants.
96 /// If `earlier > self`, returns `0` rather than panicking — this
97 /// matches the common pattern of "has enough time passed?" checks
98 /// where a monotonic clock temporarily returning non-monotonic
99 /// values (clock adjustment, host bug) should degrade to "yes,
100 /// fire now" rather than underflow.
101 pub fn saturating_elapsed_since(self, earlier: Self) -> u64 {
102 self.0.saturating_sub(earlier.0)
103 }
104
105 /// Produce a deadline `ms` milliseconds in the future, saturating
106 /// at `u64::MAX` (effectively "never").
107 pub fn saturating_add_ms(self, ms: u64) -> Self {
108 Self(self.0.saturating_add(ms))
109 }
110
111 /// `true` if `self` is at or after `deadline`. Equivalent to
112 /// `self >= deadline` but reads more naturally at call sites
113 /// that ask "has the deadline fired?".
114 pub fn has_reached(self, deadline: Self) -> bool {
115 self >= deadline
116 }
117}
118
119impl std::ops::Sub for PortableInstant {
120 type Output = u64;
121
122 /// Saturating subtraction — mirrors [`saturating_elapsed_since`] so
123 /// `later - earlier` reads as "how much later".
124 ///
125 /// [`saturating_elapsed_since`]: Self::saturating_elapsed_since
126 fn sub(self, rhs: Self) -> u64 {
127 self.saturating_elapsed_since(rhs)
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn origin_is_zero() {
137 assert_eq!(PortableInstant::ORIGIN.millis(), 0);
138 assert_eq!(PortableInstant::default(), PortableInstant::ORIGIN);
139 }
140
141 #[test]
142 fn saturating_elapsed_since_handles_reverse_order() {
143 // Defensive: if the host clock ever appears non-monotonic
144 // (clock adjustment, recovered snapshot), we return 0 rather
145 // than underflow. Callers comparing "has deadline elapsed?"
146 // read 0 as "yes", which degrades safely.
147 let earlier = PortableInstant(100);
148 let later = PortableInstant(250);
149 assert_eq!(later.saturating_elapsed_since(earlier), 150);
150 assert_eq!(earlier.saturating_elapsed_since(later), 0);
151 }
152
153 #[test]
154 fn saturating_add_ms_saturates_at_max() {
155 let big = PortableInstant(u64::MAX - 5);
156 assert_eq!(big.saturating_add_ms(10), PortableInstant(u64::MAX));
157 }
158
159 #[test]
160 fn has_reached_is_true_at_and_after_deadline() {
161 let deadline = PortableInstant(500);
162 assert!(!PortableInstant(499).has_reached(deadline));
163 assert!(PortableInstant(500).has_reached(deadline));
164 assert!(PortableInstant(501).has_reached(deadline));
165 }
166
167 #[test]
168 fn sub_operator_mirrors_saturating_elapsed_since() {
169 let a = PortableInstant(300);
170 let b = PortableInstant(100);
171 assert_eq!(a - b, 200);
172 // Reverse underflow clamps to 0 — same as saturating_elapsed_since.
173 assert_eq!(b - a, 0);
174 }
175
176 #[test]
177 fn ordering_is_consistent_with_u64() {
178 assert!(PortableInstant(5) < PortableInstant(10));
179 assert!(PortableInstant(10) == PortableInstant(10));
180 assert!(PortableInstant(15) > PortableInstant(10));
181 }
182
183 #[test]
184 fn deadline_pattern_round_trip() {
185 // The canonical usage: arm a deadline, then ask "has now
186 // reached the deadline?". Pin the pattern.
187 let now = PortableInstant(1_000);
188 let debounce_ms = 75;
189 let deadline = now.saturating_add_ms(debounce_ms);
190
191 // Before the debounce window elapses: not fired.
192 let fifty_ms_later = PortableInstant(1_050);
193 assert!(!fifty_ms_later.has_reached(deadline));
194
195 // After: fired.
196 let eighty_ms_later = PortableInstant(1_080);
197 assert!(eighty_ms_later.has_reached(deadline));
198 }
199
200 #[test]
201 fn serde_round_trip_preserves_value() {
202 // Deadlines may be persisted in snapshots; pin the wire shape.
203 let original = PortableInstant(1_234_567_890);
204 let json = serde_json::to_string(&original).unwrap();
205 // Serializes as a bare u64, not a struct wrapper.
206 assert_eq!(json, "1234567890");
207 let decoded: PortableInstant = serde_json::from_str(&json).unwrap();
208 assert_eq!(decoded, original);
209 }
210
211 // Native only: there `web_time` is std's clock, so the two must agree.
212 #[cfg(not(target_arch = "wasm32"))]
213 #[test]
214 fn wall_clock_now_reads_the_platform_clock() {
215 let before = web_time::SystemTime::now();
216 let now = wall_clock_now();
217 let after = web_time::SystemTime::now();
218 assert!(before <= now && now <= after);
219 }
220}