1use chrono::{DateTime, Duration as ChronoDuration, Utc};
17use std::sync::Mutex;
18use std::sync::PoisonError;
19use std::time::{Duration, Instant};
20
21const SUSPEND_GAP_THRESHOLD: Duration = Duration::from_secs(20);
24
25const MAX_GAP_LOG: usize = 128;
29
30struct GapRecord {
31 detected_at: DateTime<Utc>,
32 gap: ChronoDuration,
33}
34
35#[derive(Debug)]
36struct Checkpoint {
37 instant: Instant,
38 wall: DateTime<Utc>,
39}
40
41fn gap_since(
46 prev: &Checkpoint,
47 now_instant: Instant,
48 now_wall: DateTime<Utc>,
49) -> Option<ChronoDuration> {
50 let monotonic_elapsed = now_instant.saturating_duration_since(prev.instant);
51 let wall_elapsed = (now_wall - prev.wall).to_std().unwrap_or_default();
52 let gap = wall_elapsed.saturating_sub(monotonic_elapsed);
53 if gap < SUSPEND_GAP_THRESHOLD {
54 return None;
55 }
56 Some(ChronoDuration::from_std(gap).unwrap_or_else(|_| ChronoDuration::zero()))
57}
58
59static LAST_CHECKPOINT: Mutex<Option<Checkpoint>> = Mutex::new(None);
60static GAP_LOG: Mutex<Vec<GapRecord>> = Mutex::new(Vec::new());
61
62pub fn checkpoint() -> Option<ChronoDuration> {
65 let now_instant = Instant::now();
66 let now_wall = Utc::now();
67
68 let prev = {
69 let mut guard = LAST_CHECKPOINT
70 .lock()
71 .unwrap_or_else(PoisonError::into_inner);
72 guard.replace(Checkpoint {
73 instant: now_instant,
74 wall: now_wall,
75 })
76 };
77 let prev = prev?;
78 let gap = gap_since(&prev, now_instant, now_wall)?;
79
80 let mut log = GAP_LOG.lock().unwrap_or_else(PoisonError::into_inner);
81 log.push(GapRecord {
82 detected_at: now_wall,
83 gap,
84 });
85 if log.len() > MAX_GAP_LOG {
86 let excess = log.len() - MAX_GAP_LOG;
87 log.drain(0..excess);
88 }
89 Some(gap)
90}
91
92#[derive(Debug)]
101pub struct SuspendDetector {
102 last: Option<Checkpoint>,
103}
104
105impl SuspendDetector {
106 pub fn new() -> Self {
107 Self { last: None }
108 }
109
110 pub fn check(&mut self) -> Option<ChronoDuration> {
113 let now_instant = Instant::now();
114 let now_wall = Utc::now();
115 let prev = self.last.replace(Checkpoint {
116 instant: now_instant,
117 wall: now_wall,
118 })?;
119 gap_since(&prev, now_instant, now_wall)
120 }
121
122 pub fn gap_within(&mut self, window: Duration) -> Option<ChronoDuration> {
125 let own = self.check();
126 let shared = gap_detected_within(window);
127 match (own, shared) {
128 (Some(a), Some(b)) => Some(a.max(b)),
129 (a, b) => a.or(b),
130 }
131 }
132}
133
134impl Default for SuspendDetector {
135 fn default() -> Self {
136 Self::new()
137 }
138}
139
140pub fn suspended_duration_since(since: DateTime<Utc>) -> ChronoDuration {
143 let log = GAP_LOG.lock().unwrap_or_else(PoisonError::into_inner);
144 log.iter()
145 .filter(|r| r.detected_at > since)
146 .fold(ChronoDuration::zero(), |acc, r| acc + r.gap)
147}
148
149pub fn gap_detected_within(window: Duration) -> Option<ChronoDuration> {
153 let window = ChronoDuration::from_std(window).unwrap_or_else(|_| ChronoDuration::zero());
154 let cutoff = Utc::now() - window;
155 let log = GAP_LOG.lock().unwrap_or_else(PoisonError::into_inner);
156 log.iter()
157 .rev()
158 .find(|r| r.detected_at >= cutoff)
159 .map(|r| r.gap)
160}
161
162#[cfg(test)]
166pub(crate) fn inject_gap_for_test(detected_at: DateTime<Utc>, gap: ChronoDuration) {
167 let mut log = GAP_LOG.lock().unwrap_or_else(PoisonError::into_inner);
168 log.push(GapRecord { detected_at, gap });
169}
170
171#[cfg(test)]
174pub(crate) fn clear_for_test() {
175 let mut log = GAP_LOG.lock().unwrap_or_else(PoisonError::into_inner);
176 log.clear();
177}
178
179#[cfg(test)]
180mod tests {
181 use std::thread;
182
183 use super::*;
184 use serial_test::serial;
185
186 #[test]
187 #[serial(suspend_state)]
188 fn suspended_duration_since_sums_only_later_gaps() {
189 clear_for_test();
190 let t0 = Utc::now() - ChronoDuration::minutes(10);
191 let t1 = Utc::now() - ChronoDuration::minutes(5);
192 inject_gap_for_test(t0, ChronoDuration::minutes(3));
193 inject_gap_for_test(t1, ChronoDuration::minutes(2));
194
195 let total = suspended_duration_since(t0 - ChronoDuration::seconds(1));
197 assert_eq!(total, ChronoDuration::minutes(5));
198
199 let total = suspended_duration_since(t0 + ChronoDuration::seconds(1));
201 assert_eq!(total, ChronoDuration::minutes(2));
202
203 let total = suspended_duration_since(t1 + ChronoDuration::seconds(1));
205 assert_eq!(total, ChronoDuration::zero());
206
207 clear_for_test();
208 }
209
210 #[test]
211 fn suspend_detector_first_check_has_no_baseline() {
212 let mut detector = SuspendDetector::new();
213 assert_eq!(detector.check(), None);
214 }
215
216 #[test]
217 fn suspend_detector_reports_no_gap_for_normal_elapsed_time() {
218 let mut detector = SuspendDetector::new();
219 detector.check();
220 thread::sleep(Duration::from_millis(10));
221 assert_eq!(detector.check(), None);
222 }
223
224 #[test]
225 #[serial(suspend_state)]
226 fn gap_detected_within_finds_recent_gap() {
227 clear_for_test();
228 inject_gap_for_test(Utc::now(), ChronoDuration::minutes(7));
229
230 let found = gap_detected_within(Duration::from_secs(60));
231 assert_eq!(found, Some(ChronoDuration::minutes(7)));
232
233 clear_for_test();
234 }
235}