summaryrefslogtreecommitdiffstats
path: root/src/time.rs
blob: 88a27c72466572e12dab4c3692b625f531d7626e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//! Clock helpers.
//!
//! DESIGN.md §16: "use DB time (`strftime` at write) for all ordering and audit
//! stamps". We store timestamps as UTC ISO-8601 with second resolution so that
//! lexicographic ordering equals chronological ordering, and every write path
//! funnels through [`now`] so a test can pin the clock.

use chrono::{DateTime, SecondsFormat, TimeZone, Utc};

/// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`.
pub fn now() -> String {
    // A test may pin the clock (see `pin`); production reads the real clock.
    match pinned() {
        Some(pinned) => pinned,
        None => fmt(Utc::now()),
    }
}

/// The instant relative arithmetic should use.
///
/// This is what makes `secs_ago` and `secs_ahead` honest under a pinned clock
/// (§6 m-1): a test that pins the clock and then asks for a 90-second lease
/// means a lease expiring 90 seconds after *the pinned instant*, not after the
/// real one. Reading the wall clock here instead would hand a pinned test a
/// lease that had already expired — or would not expire for a century — and the
/// test would pass while proving nothing about expiry at all.
fn base() -> DateTime<Utc> {
    match pinned().and_then(|p| parse(&p)) {
        Some(t) => t,
        None => Utc::now(),
    }
}

fn fmt(t: DateTime<Utc>) -> String {
    t.to_rfc3339_opts(SecondsFormat::Secs, true)
}

fn pinned() -> Option<String> {
    CLOCK.with(|c| c.borrow().clone())
}

thread_local! {
    static CLOCK: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Pin the clock for the current thread (tests only). Returns the previous value.
pub fn pin(ts: &str) -> Option<String> {
    CLOCK.with(|c| {
        let mut slot = c.borrow_mut();
        (*slot).replace(ts.to_string())
    })
}

/// Unpin the clock for the current thread.
pub fn unpin() {
    CLOCK.with(|c| *c.borrow_mut() = None);
}

/// Parse a DB timestamp back into a `DateTime<Utc>`.
pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(ts)
        .ok()
        .map(|d| d.with_timezone(&Utc))
        .or_else(|| {
            chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S")
                .ok()
                .map(|n| Utc.from_utc_datetime(&n))
        })
}

/// Whole seconds between two timestamps (`b - a`), or `None` if unparseable.
pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
    Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
}

/// A timestamp `secs` seconds in the past, canonical format. Honors the pinned
/// clock — see [`base`].
pub fn secs_ago(secs: i64) -> String {
    fmt(base() - chrono::Duration::seconds(secs))
}

/// A timestamp `secs` seconds in the future, canonical format. Honors the
/// pinned clock — see [`base`].
pub fn secs_ahead(secs: i64) -> String {
    fmt(base() + chrono::Duration::seconds(secs))
}