1use std::sync::Mutex;
2
3use web_time::{SystemTime, UNIX_EPOCH};
4
5use crate::model::crypto::Timestamped;
6
7pub type TimeGetter = fn() -> Timestamp;
8
9#[derive(Clone, Debug)]
10pub struct Timestamp(pub i64);
11
12pub fn get_time() -> Timestamp {
13 let time = match SystemTime::now().duration_since(UNIX_EPOCH) {
14 Ok(t) => t.as_millis() as i64,
15 Err(e) => -(e.duration().as_millis() as i64),
16 };
17
18 Timestamp(time)
19}
20
21pub fn timestamp<T>(t: T, time_getter: TimeGetter) -> Timestamped<T> {
22 Timestamped { value: t, timestamp: time_getter().0 }
23}
24
25pub struct Clock {
27 source: TimeGetter,
28 last: Mutex<i64>,
30}
31
32impl Clock {
33 pub fn new(source: TimeGetter) -> Self {
34 Self { source, last: Mutex::new(i64::MIN) }
35 }
36
37 pub fn now(&self) -> Timestamp {
38 let mut last = self.last.lock().unwrap();
39 let reading = (self.source)().0;
41 if reading < *last {
42 tracing::warn!(back_ms = *last - reading, "clock went backwards");
43 } else {
44 *last = reading;
45 }
46 Timestamp(*last)
47 }
48}
49
50impl Clone for Clock {
51 fn clone(&self) -> Self {
53 Self { source: self.source, last: Mutex::new(*self.last.lock().unwrap()) }
54 }
55}
56
57impl Default for Clock {
58 fn default() -> Self {
59 Self::new(get_time)
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::{Clock, Timestamp};
66 use std::sync::atomic::{AtomicUsize, Ordering};
67
68 const READINGS: [i64; 8] = [100, 105, 103, 103, 90, 106, 106, 50];
69 static NEXT: AtomicUsize = AtomicUsize::new(0);
70
71 fn scripted() -> Timestamp {
72 Timestamp(READINGS[NEXT.fetch_add(1, Ordering::SeqCst)])
73 }
74
75 #[test]
76 fn never_reports_earlier_time() {
77 let clock = Clock::new(scripted);
78 let reported: Vec<i64> = READINGS.iter().map(|_| clock.now().0).collect();
79 assert_eq!(reported, [100, 105, 105, 105, 105, 106, 106, 106]);
80 }
81}