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