Skip to main content

pitboard_core/
time.rs

1//! Time through jiff: epoch seconds in everything pitboard stores, the local time zone only
2//! in what it shows a person.
3//!
4//! There is no free function that reads the clock. Everything that needs to know the time
5//! asks its [`Context`](crate::context::Context), which holds a [`Clock`]. The expiry of a
6//! parked login, whether a renewal is due, and how long doctor says is left are all
7//! judgements about time, and none of them could be tested while the clock was a call into
8//! the operating system made wherever it was needed.
9
10use jiff::Timestamp;
11use jiff::tz::TimeZone;
12
13/// What pitboard reads the time from.
14#[doc(hidden)]
15pub trait Clock: Send + Sync + std::fmt::Debug {
16    /// Epoch seconds: what everything pitboard stores is measured in.
17    fn now(&self) -> i64;
18
19    /// Epoch milliseconds. Park names carry this, so two parks of one account in the same
20    /// second do not collide.
21    fn now_millis(&self) -> i64;
22}
23
24/// This machine's clock, which is what every real context uses.
25#[derive(Debug, Clone, Copy)]
26pub(crate) struct SystemClock;
27
28impl Clock for SystemClock {
29    fn now(&self) -> i64 {
30        Timestamp::now().as_second()
31    }
32
33    fn now_millis(&self) -> i64 {
34        Timestamp::now().as_millisecond()
35    }
36}
37
38/// A clock that says what it is told, and can be moved. What the interesting judgements in
39/// this crate are about is when something happens, so a test needs to say when.
40#[cfg(any(test, feature = "test-support"))]
41#[doc(hidden)]
42#[derive(Debug)]
43pub struct FixedClock(std::sync::atomic::AtomicI64);
44
45#[cfg(any(test, feature = "test-support"))]
46impl FixedClock {
47    pub fn at(epoch_seconds: i64) -> FixedClock {
48        FixedClock(std::sync::atomic::AtomicI64::new(epoch_seconds))
49    }
50
51    /// Move the clock forward, or back.
52    pub fn advance(&self, seconds: i64) {
53        self.0
54            .fetch_add(seconds, std::sync::atomic::Ordering::Relaxed);
55    }
56}
57
58#[cfg(any(test, feature = "test-support"))]
59impl Clock for FixedClock {
60    fn now(&self) -> i64 {
61        self.0.load(std::sync::atomic::Ordering::Relaxed)
62    }
63
64    fn now_millis(&self) -> i64 {
65        self.now() * 1000
66    }
67}
68
69/// An RFC 3339 instant such as `2026-09-20T22:20:00.095287+00:00`, as epoch seconds. `None`
70/// for anything else, including a time without an offset, which names no instant.
71pub fn parse(text: &str) -> Option<i64> {
72    text.parse::<Timestamp>().ok().map(Timestamp::as_second)
73}
74
75/// `epoch` in this machine's time zone, formatted with `strftime` directives.
76pub fn local(epoch: i64, pattern: &str) -> String {
77    Timestamp::from_second(epoch)
78        .map(|t| t.to_zoned(TimeZone::system()).strftime(pattern).to_string())
79        .unwrap_or_default()
80}
81
82/// What a person reads for a moment: "14:02", or with the date once it is not today.
83pub fn moment(epoch: i64, now: i64) -> String {
84    let pattern = if local(epoch, "%F") == local(now, "%F") {
85        "%H:%M"
86    } else {
87        "%b %-d %H:%M"
88    };
89    local(epoch, pattern)
90}
91
92/// A length of time to the precision a person reads: "6d 4h", "2h 05m", "47m", "<1m".
93pub fn span(seconds: i64) -> String {
94    let s = seconds.max(0);
95    let (days, hours, minutes) = (s / 86_400, s % 86_400 / 3_600, s % 3_600 / 60);
96    match (days, hours) {
97        (0, 0) if minutes == 0 => "<1m".into(),
98        (0, 0) => format!("{minutes}m"),
99        (0, h) => format!("{h}h {minutes:02}m"),
100        (d, h) => format!("{d}d {h}h"),
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn parses_the_shapes_the_usage_api_actually_emits() {
110        // Captured verbatim from a live /api/oauth/usage response.
111        assert_eq!(parse("2026-09-20T22:20:00.095287+00:00"), Some(1789942800));
112        assert_eq!(parse("2026-09-27T02:00:00.095306+00:00"), Some(1790474400));
113        assert_eq!(parse("2026-09-20T22:20:00Z"), Some(1789942800));
114        assert_eq!(parse("2026-09-21T05:20:00+07:00"), Some(1789942800));
115    }
116
117    #[test]
118    fn refuses_rather_than_guesses() {
119        for bad in [
120            "",
121            "not a date",
122            "2026-09-20",
123            "2026-09-20T22:20:00",
124            "2026/09/20T22:20:00Z",
125            "2026-13-01T00:00:00Z",
126            "2026-01-32T00:00:00Z",
127            "2026-01-01T24:00:00Z",
128        ] {
129            assert_eq!(parse(bad), None, "should refuse {bad:?}");
130        }
131    }
132
133    #[test]
134    fn spans_read_at_a_glance() {
135        assert_eq!(span(-5), "<1m");
136        assert_eq!(span(59), "<1m");
137        assert_eq!(span(60 * 47), "47m");
138        assert_eq!(span(3600 * 2 + 60 * 5), "2h 05m");
139        assert_eq!(span(86_400 * 6 + 3600 * 4 + 59), "6d 4h");
140    }
141
142    #[test]
143    fn a_moment_today_is_just_its_time() {
144        let now = SystemClock.now();
145        assert_eq!(moment(now, now).len(), 5);
146        assert!(moment(now - 3 * 86_400, now).len() > 5);
147    }
148
149    #[test]
150    fn formats_in_the_local_zone() {
151        assert_eq!(local(0, "%Y").len(), 4);
152        assert_eq!(
153            local(i64::MAX, "%Y"),
154            "",
155            "out of range is empty, not a panic"
156        );
157    }
158}