summaryrefslogtreecommitdiffstats
path: root/src/time.rs
blob: 1ffc1160bb17e9a0d1b88aa5c4f4ddc433a0713e (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
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) };
}

pub fn pin(ts: &str) -> Option<String> {
    CLOCK.with(|c| {
        let mut slot = c.borrow_mut();
        (*slot).replace(ts.to_string())
    })
}

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::advance(d) {
        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::advance(d) {
        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)
}

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

#[cfg(feature = "test-support")]
pub fn virtual_now() -> Option<DateTime<Utc>> {
    clock::now()
}

#[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(());

    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 the wait was virtual: the clock moved, no wall time did.
    pub fn advance(d: Duration) -> bool {
        if !ON.get() {
            return false;
        }
        let mut at = lock(&AT);
        if let Some(t) = *at {
            let step = chrono::TimeDelta::from_std(d).unwrap_or_else(|_| chrono::TimeDelta::zero());
            *at = Some(t + step);
        }
        // A control loop that never blocks still needs to let its caller run.
        std::thread::yield_now();
        true
    }

    pub 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 {
    use super::*;

    #[inline(always)]
    pub fn advance(_d: Duration) -> bool {
        false
    }

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