Skip to main content

nitr_std/
clock.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! The one clock the standard library reads, with an override for
7//! `nitr test` (`nitr.test.clock`).
8//!
9//! Every wall-clock or elapsed-time read whose answer a script can observe
10//! goes through here: `nitr.time.now`/`monotonic`, session and JWT expiry,
11//! the `after`/`before` validation rules, cache TTLs, and the rate
12//! limiter's window. A test can then age a session or expire a cache entry
13//! by saying so, instead of sleeping.
14//!
15//! What deliberately does **not** read this clock: the runtime's execution
16//! deadline, every `tokio::time` timeout, and the body-stall timers. They
17//! measure real time by design — routed through the override,
18//! `t.clock.advance(3600)` would trip the budget of the very test that
19//! called it.
20//!
21//! The override is process-global, because several readers (the rate
22//! limiter, the cache) have no Lua state to find a per-state value in.
23//! That is sound only because nothing sets it but the `nitr test` runner,
24//! which runs files and tests strictly one after another and resets the
25//! override after every test and every file. A production process never
26//! calls [`set`] or [`advance`], and then every read costs one relaxed
27//! atomic load on top of the real clock. The standard library's own unit
28//! tests exercise a private `Clock` instance, never the global one.
29
30use std::sync::RwLock;
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
33
34/// The first second past year 9999: the bound every other date consumer
35/// in the standard library (HTTP dates above all) already respects.
36const MAX_TIMESTAMP: f64 = 253_402_300_800.0;
37
38/// The most a test may move the clock forward in total: a century is far
39/// past any TTL worth testing and far from any `Instant` overflow.
40const MAX_ADVANCE: Duration = Duration::from_secs(100 * 366 * 24 * 60 * 60);
41
42/// What the wall clock answers while an override is installed.
43#[derive(Debug, Clone, Copy)]
44enum Wall {
45    /// `set(ts)`: time stands still at this instant (plus any later
46    /// `advance`), so an assertion on `nitr.time.now()` cannot race a
47    /// second boundary.
48    Frozen(SystemTime),
49    /// `advance(d)` without a `set`: the real clock, shifted forward.
50    Shifted(Duration),
51}
52
53#[derive(Debug, Clone, Copy)]
54struct Override {
55    wall: Wall,
56    /// Added to every monotonic reading: an `Instant` cannot move
57    /// backwards, so only `advance` touches it.
58    elapsed: Duration,
59}
60
61/// A clock with an optional override. The global one backs the free
62/// functions below; tests build their own.
63struct Clock {
64    /// The fast path: false means no override, and the lock is never
65    /// taken.
66    active: AtomicBool,
67    /// Set by every `set`/`advance`, cleared by [`take_touched`]: whether
68    /// anything may have stored an instant from the overridden clock.
69    touched: AtomicBool,
70    state: RwLock<Option<Override>>,
71}
72
73impl Clock {
74    const fn new() -> Self {
75        Self {
76            active: AtomicBool::new(false),
77            touched: AtomicBool::new(false),
78            state: RwLock::new(None),
79        }
80    }
81
82    fn current(&self) -> Option<Override> {
83        if !self.active.load(Ordering::Relaxed) {
84            return None;
85        }
86        // Poisoning needs a panic while the lock is held, and nothing
87        // below can panic; the real clock is the safe answer regardless.
88        self.state.read().ok().and_then(|state| *state)
89    }
90
91    fn system(&self) -> SystemTime {
92        let real = SystemTime::now();
93        match self.current().map(|o| o.wall) {
94            None => real,
95            Some(Wall::Frozen(at)) => at,
96            Some(Wall::Shifted(by)) => real.checked_add(by).unwrap_or(real),
97        }
98    }
99
100    fn instant(&self) -> Instant {
101        let real = Instant::now();
102        match self.current() {
103            None => real,
104            Some(o) => real.checked_add(o.elapsed).unwrap_or(real),
105        }
106    }
107
108    fn set(&self, ts: f64) -> Result<(), String> {
109        if !ts.is_finite() || !(0.0..MAX_TIMESTAMP).contains(&ts) {
110            return Err(format!(
111                "clock.set({ts}): the timestamp must be unix seconds between 0 and year 9999"
112            ));
113        }
114        let at = Duration::try_from_secs_f64(ts)
115            .map(|since| UNIX_EPOCH + since)
116            .map_err(|err| format!("clock.set({ts}): {err}"))?;
117        self.update(|current| Override {
118            wall: Wall::Frozen(at),
119            elapsed: current.map_or(Duration::ZERO, |o| o.elapsed),
120        })
121    }
122
123    fn advance(&self, secs: f64) -> Result<(), String> {
124        let by = Duration::try_from_secs_f64(secs)
125            .ok()
126            .filter(|_| secs.is_finite())
127            .ok_or_else(|| {
128                format!("clock.advance({secs}): the step must be a non-negative number of seconds")
129            })?;
130        let too_far = || {
131            format!(
132                "clock.advance({secs}): the clock may move at most {} days forward in total",
133                MAX_ADVANCE.as_secs() / 86_400
134            )
135        };
136        let current = self.current();
137        let elapsed = current
138            .map_or(Duration::ZERO, |o| o.elapsed)
139            .checked_add(by)
140            .filter(|total| *total <= MAX_ADVANCE)
141            .ok_or_else(too_far)?;
142        let wall = match current.map(|o| o.wall) {
143            None => Wall::Shifted(by),
144            Some(Wall::Shifted(shift)) => Wall::Shifted(
145                shift
146                    .checked_add(by)
147                    .filter(|total| *total <= MAX_ADVANCE)
148                    .ok_or_else(too_far)?,
149            ),
150            Some(Wall::Frozen(at)) => {
151                let moved = at.checked_add(by).ok_or_else(too_far)?;
152                let limit = UNIX_EPOCH + Duration::from_secs(MAX_TIMESTAMP as u64);
153                if moved >= limit {
154                    return Err(too_far());
155                }
156                Wall::Frozen(moved)
157            }
158        };
159        self.update(|_| Override { wall, elapsed })
160    }
161
162    fn update(&self, next: impl FnOnce(Option<Override>) -> Override) -> Result<(), String> {
163        let mut state = self
164            .state
165            .write()
166            .map_err(|_| "the clock override lock is poisoned".to_string())?;
167        *state = Some(next(*state));
168        self.active.store(true, Ordering::Relaxed);
169        self.touched.store(true, Ordering::Relaxed);
170        Ok(())
171    }
172
173    fn reset(&self) {
174        self.active.store(false, Ordering::Relaxed);
175        if let Ok(mut state) = self.state.write() {
176            *state = None;
177        }
178    }
179}
180
181static CLOCK: Clock = Clock::new();
182
183/// The wall clock.
184pub fn now_system() -> SystemTime {
185    CLOCK.system()
186}
187
188/// The wall clock as whole unix seconds (`0` before the epoch).
189pub fn now_unix() -> i64 {
190    now_system()
191        .duration_since(UNIX_EPOCH)
192        .map_or(0, |d| d.as_secs() as i64)
193}
194
195/// The wall clock as fractional unix seconds (`0.0` before the epoch).
196pub fn now_unix_f64() -> f64 {
197    now_system()
198        .duration_since(UNIX_EPOCH)
199        .map_or(0.0, |d| d.as_secs_f64())
200}
201
202/// The monotonic clock, moved forward by [`advance`].
203pub fn now_instant() -> Instant {
204    CLOCK.instant()
205}
206
207/// Freezes the wall clock at `ts` unix seconds. Monotonic time keeps
208/// flowing: an `Instant` cannot be moved backwards. For `nitr test` only.
209///
210/// # Errors
211///
212/// A timestamp that is not finite, negative, or past year 9999.
213pub fn set(ts: f64) -> Result<(), String> {
214    CLOCK.set(ts)
215}
216
217/// Moves wall and monotonic time forward together by `secs` — what a TTL
218/// or a rate-limit window needs to see. For `nitr test` only.
219///
220/// # Errors
221///
222/// A negative or non-finite step, or a total past a century.
223pub fn advance(secs: f64) -> Result<(), String> {
224    CLOCK.advance(secs)
225}
226
227/// Removes any override: every reader sees the real clock again.
228pub fn reset() {
229    CLOCK.reset();
230}
231
232/// Whether the clock was set or advanced since the last call — even if
233/// it has been reset since. Anything that stored an instant meanwhile (a
234/// cache entry's expiry) carries the overridden time: the runner clears
235/// such state when this says so.
236pub fn take_touched() -> bool {
237    CLOCK.touched.swap(false, Ordering::Relaxed)
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    fn unix(clock: &Clock) -> f64 {
245        clock
246            .system()
247            .duration_since(UNIX_EPOCH)
248            .expect("after the epoch")
249            .as_secs_f64()
250    }
251
252    #[test]
253    fn without_an_override_the_real_clock_answers() {
254        let clock = Clock::new();
255        let before = SystemTime::now();
256        let read = clock.system();
257        assert!(read >= before && read <= SystemTime::now());
258        let before = Instant::now();
259        let read = clock.instant();
260        assert!(read >= before && read <= Instant::now());
261    }
262
263    #[test]
264    fn set_freezes_the_wall_clock_and_leaves_elapsed_time_alone() {
265        let clock = Clock::new();
266        clock.set(1_735_689_600.0).expect("set");
267        assert_eq!(unix(&clock), 1_735_689_600.0);
268        assert_eq!(unix(&clock), 1_735_689_600.0, "frozen, not flowing");
269        let before = Instant::now();
270        let read = clock.instant();
271        assert!(read >= before && read <= Instant::now() + Duration::from_millis(50));
272    }
273
274    #[test]
275    fn advance_moves_wall_and_elapsed_time_together() {
276        let clock = Clock::new();
277        clock.set(1_000.0).expect("set");
278        clock.advance(3_600.0).expect("advance");
279        assert_eq!(unix(&clock), 4_600.0);
280        let lead = clock.instant().duration_since(Instant::now());
281        assert!(lead > Duration::from_secs(3_599), "elapsed moved: {lead:?}");
282
283        // Without a `set`, advancing shifts the real wall clock.
284        let shifted = Clock::new();
285        let real = SystemTime::now();
286        shifted.advance(86_400.0).expect("advance");
287        let ahead = shifted.system().duration_since(real).expect("ahead");
288        assert!(ahead >= Duration::from_secs(86_400) && ahead < Duration::from_secs(86_460));
289    }
290
291    #[test]
292    fn reset_restores_the_real_clock() {
293        let clock = Clock::new();
294        assert!(!clock.touched.load(Ordering::Relaxed));
295        clock.set(5.0).expect("set");
296        clock.advance(10.0).expect("advance");
297        clock.reset();
298        assert!(
299            clock.touched.swap(false, Ordering::Relaxed),
300            "a reset keeps the record that the clock moved"
301        );
302        let now = SystemTime::now();
303        let read = clock.system();
304        assert!(read.duration_since(now).unwrap_or_default() < Duration::from_secs(1));
305        assert!(clock.instant() <= Instant::now());
306    }
307
308    #[test]
309    fn out_of_range_steps_are_refused_without_moving_the_clock() {
310        let clock = Clock::new();
311        for bad in [f64::NAN, f64::INFINITY, -1.0, 253_402_300_800.0, 1e300] {
312            let err = clock.set(bad).expect_err("bad set");
313            assert!(err.contains("year 9999"), "{bad}: {err}");
314        }
315        for bad in [f64::NAN, f64::INFINITY, -1.0, 1e300] {
316            clock.advance(bad).expect_err("bad advance");
317        }
318        let err = clock
319            .advance(MAX_ADVANCE.as_secs_f64() + 1.0)
320            .expect_err("too far");
321        assert!(err.contains("at most"), "{err}");
322        assert!(clock.current().is_none(), "a refused step installs nothing");
323
324        // Frozen near the end of time, a step past year 9999 is refused.
325        clock.set(253_402_300_000.0).expect("set");
326        clock.advance(1_000.0).expect_err("past year 9999");
327        assert_eq!(unix(&clock), 253_402_300_000.0);
328    }
329}