summaryrefslogtreecommitdiffstats
path: root/src/time.rs
blob: 4f5ab7f4a298d22a328b784198b0f4ce64d3f49d (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

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

pub fn now() -> String {
    #[cfg(feature = "test-support")]
    if let Some(t) = clock::now() {
        return fmt(t);
    }
    match pinned() {
        Some(pinned) => pinned,
        None => fmt(Utc::now()),
    }
}

fn base() -> DateTime<Utc> {
    #[cfg(feature = "test-support")]
    if let Some(t) = clock::now() {
        return t;
    }
    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) };
}

/// Freeze the clock for this thread, returning the previous pin if any.
///
/// Test-tier only, together with `unpin` — the two are one capability and
/// gating half of it would leave a release binary able to freeze time and
/// unable to release it. The census never reported `pin` as test-only because
/// its name match also fires inside `upstream_pins` and `source_digests`; the
/// only callers in the crate are tests.
#[cfg(feature = "test-support")]
pub fn pin(ts: &str) -> Option<String> {
    CLOCK.with(|c| {
        let mut slot = c.borrow_mut();
        (*slot).replace(ts.to_string())
    })
}

/// Release a pin set by `pin`. See the note there about why both are gated.
#[cfg(feature = "test-support")]
pub fn unpin() {
    CLOCK.with(|c| *c.borrow_mut() = None);
}

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))
        })
}

pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
    Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
}

pub fn secs_ago(secs: i64) -> String {
    fmt(base() - chrono::Duration::seconds(secs))
}

pub fn secs_ahead(secs: i64) -> String {
    fmt(base() + chrono::Duration::seconds(secs))
}

// ---- waiting ----

/// Wait for `d`, checking `stop` every `slice`. Returns false if `stop` was set
/// before the wait finished, so a control loop can leave instead of doing one
/// more pass.
pub fn wait(d: Duration, slice: Duration, stop: &AtomicBool) -> bool {
    if clock::virtual_sleep() {
        return !stop.load(Ordering::SeqCst);
    }
    let mut left = d;
    while !left.is_zero() {
        if stop.load(Ordering::SeqCst) {
            return false;
        }
        let step = slice.min(left);
        std::thread::sleep(step);
        left -= step;
    }
    true
}

pub fn sleep(d: Duration) {
    if clock::virtual_sleep() {
        return;
    }
    std::thread::sleep(d);
}

/// Wrap a closure about to be spawned so the child thread inherits this one's
/// clock setting. Without it a control loop spawned by a test runs on wall time
/// while the test itself runs on the virtual clock, and the two disagree.
pub fn inherit<F, T>(f: F) -> impl FnOnce() -> T
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    clock::wrap(f)
}

/// The handle tests hold to keep the clock frozen; dropping it releases the
/// clock, which is why `virtualize` hands one back rather than setting a global.
#[cfg(feature = "test-support")]
pub use clock::VirtualClock;

#[cfg(feature = "test-support")]
pub fn virtualize() -> clock::VirtualClock {
    clock::virtualize()
}

#[cfg(feature = "test-support")]
mod clock {
    use super::*;
    use std::cell::Cell;
    use std::sync::{Mutex, MutexGuard};

    thread_local! {
        static ON: Cell<bool> = const { Cell::new(false) };
    }

    static AT: Mutex<Option<DateTime<Utc>>> = Mutex::new(None);
    static OWNER: Mutex<()> = Mutex::new(());

// VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it.
    pub struct VirtualClock {
        _owner: MutexGuard<'static, ()>,
    }

    pub fn virtualize() -> VirtualClock {
        let owner = OWNER.lock().unwrap_or_else(|e| e.into_inner());
        *lock(&AT) = Some(Utc::now());
        ON.set(true);
        VirtualClock { _owner: owner }
    }

    impl Drop for VirtualClock {
        fn drop(&mut self) {
            ON.set(false);
            *lock(&AT) = None;
        }
    }

    fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
        m.lock().unwrap_or_else(|e| e.into_inner())
    }

    pub fn now() -> Option<DateTime<Utc>> {
        if !ON.get() {
            return None;
        }
        *lock(&AT)
    }

    /// Returns true when this thread is on the virtual clock: the wait cost a
    /// yield and no wall time. The clock does not move by itself - a test moves it
    /// with `advance`, so a frozen lease stays frozen however fast the loop runs.
    pub fn virtual_sleep() -> bool {
        if !ON.get() {
            return false;
        }
        // A control loop that never blocks still needs to let its caller run.
        std::thread::yield_now();
        true
    }

    pub(super) fn wrap<F, T>(f: F) -> impl FnOnce() -> T
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        let on = ON.get();
        move || {
            ON.set(on);
            f()
        }
    }
}

#[cfg(not(feature = "test-support"))]
mod clock {
    #[inline(always)]
    pub fn virtual_sleep() -> bool {
        false
    }

    #[inline(always)]
    pub(super) fn wrap<F, T>(f: F) -> F
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        f
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Moved verbatim from tests/time.rs. These two are arithmetic on the
    // clock itself and need nothing else; the third test in that file pins a
    // lease against a pinned clock, which needs a database, so it stayed.

    #[cfg(feature = "test-support")]
    #[test]
    fn a_pinned_clock_moves_relative_arithmetic_with_it() {
        pin("2026-01-01T00:00:00Z");
        assert_eq!(now(), "2026-01-01T00:00:00Z");
        assert_eq!(secs_ahead(90), "2026-01-01T00:01:30Z");
        assert_eq!(secs_ago(90), "2025-12-31T23:58:30Z");
        unpin();
    }

    #[test]
    fn an_unpinned_clock_is_the_real_one() {
        let n = now();
        assert_eq!(delta_secs(&n, &secs_ahead(60)), Some(60));
        assert_eq!(delta_secs(&n, &secs_ago(60)), Some(-60));
    }
}