-
-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathengine.rs
More file actions
617 lines (556 loc) · 22.7 KB
/
engine.rs
File metadata and controls
617 lines (556 loc) · 22.7 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/// Drift-correcting timer engine running on a dedicated OS thread.
///
/// Uses `std::time::Instant` (monotonic clock) and `recv_timeout` to
/// schedule ticks against a fixed timeline rather than sleeping for a
/// constant 1 s. This eliminates cumulative drift from wakeup latency.
///
/// Sleep/wake behaviour (OQ-1): on `Suspend` the engine saves `elapsed_secs`
/// and blocks; on `WakeResume` it restarts from that position without advancing.
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};
// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub enum TimerCommand {
Start,
Pause,
Resume,
Reset,
/// Immediately fires a `Complete` event (user-initiated skip).
Skip,
/// Change the total duration; moves engine to Idle so caller must Start.
Reconfigure { duration_secs: u32 },
/// Update the stored duration without altering phase or elapsed time.
/// Used to arm the next round/reset path without clobbering a fresh Start.
Prime { duration_secs: u32 },
/// OS sleep detected: freeze elapsed position, block until WakeResume.
Suspend,
/// OS wake detected: resume from the saved elapsed position.
WakeResume,
Shutdown,
}
#[derive(Debug, Clone)]
pub enum TimerEvent {
Started { total_secs: u32 },
Tick { elapsed_secs: u32, total_secs: u32 },
Complete { skipped: bool },
Paused { elapsed_secs: u32 },
Resumed { elapsed_secs: u32 },
Reset,
Suspended { elapsed_secs: u32 },
}
/// Cheap-to-clone handle for sending commands to the engine thread.
#[derive(Clone)]
pub struct EngineHandle {
pub cmd_tx: Sender<TimerCommand>,
}
impl EngineHandle {
pub fn send(&self, cmd: TimerCommand) {
// Ignore send errors: the thread may have exited on Shutdown.
let _ = self.cmd_tx.send(cmd);
}
}
/// Spawn the timer engine thread.
///
/// `tick_interval` is 1 second in production; tests pass a shorter value
/// (e.g. 20 ms) to keep test execution fast.
pub fn spawn(duration_secs: u32, tick_interval: Duration) -> (EngineHandle, Receiver<TimerEvent>) {
let (cmd_tx, cmd_rx) = mpsc::channel::<TimerCommand>();
let (event_tx, event_rx) = mpsc::channel::<TimerEvent>();
std::thread::Builder::new()
.name("timer-engine".to_string())
.spawn(move || run_loop(duration_secs, event_tx, cmd_rx, tick_interval))
.expect("failed to spawn timer engine thread");
(EngineHandle { cmd_tx }, event_rx)
}
// ---------------------------------------------------------------------------
// Internal state machine
// ---------------------------------------------------------------------------
struct RunningSegment {
/// When this run segment started (used for drift-correction).
start: Instant,
/// `elapsed_secs` at the moment this segment began (0 on Start, N on Resume).
elapsed_at_start: u32,
/// Ticks fired within this segment.
ticks: u32,
}
enum Phase {
Idle,
Running(RunningSegment),
Paused,
Suspended,
}
enum Transition {
Stay,
To(Phase),
Break,
}
fn run_loop(
duration_secs: u32,
event_tx: Sender<TimerEvent>,
cmd_rx: Receiver<TimerCommand>,
tick_interval: Duration,
) {
let mut total_secs = duration_secs;
let mut elapsed_secs: u32 = 0;
let mut phase = Phase::Idle;
'engine: loop {
let tr = match &mut phase {
// -----------------------------------------------------------------
Phase::Idle => match cmd_rx.recv() {
Ok(TimerCommand::Start) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Started { total_secs });
Transition::To(Phase::Running(RunningSegment {
start: Instant::now(),
elapsed_at_start: 0,
ticks: 0,
}))
}
Ok(TimerCommand::Reconfigure { duration_secs: d }) => {
total_secs = d;
Transition::Stay
}
Ok(TimerCommand::Prime { duration_secs: d }) => {
total_secs = d;
Transition::Stay
}
// Reset while Idle: emit the event so the listener can update
// the frontend and then sync the next-round duration. Without
// this handler the command would be silently swallowed,
// leaving the listener blocked in recv() and the UI stale.
Ok(TimerCommand::Reset) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Reset);
Transition::Stay
}
// Skip while Idle: advance to the next round without starting.
Ok(TimerCommand::Skip) => {
let _ = event_tx.send(TimerEvent::Complete { skipped: true });
Transition::Stay
}
Ok(TimerCommand::Shutdown) | Err(_) => Transition::Break,
_ => Transition::Stay,
},
// -----------------------------------------------------------------
Phase::Paused | Phase::Suspended => match cmd_rx.recv() {
Ok(TimerCommand::Resume | TimerCommand::WakeResume) => {
let _ = event_tx.send(TimerEvent::Resumed { elapsed_secs });
Transition::To(Phase::Running(RunningSegment {
start: Instant::now(),
elapsed_at_start: elapsed_secs,
ticks: 0,
}))
}
Ok(TimerCommand::Reset) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Reset);
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Skip) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Complete { skipped: true });
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Reconfigure { duration_secs: d }) => {
total_secs = d;
elapsed_secs = 0;
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Prime { duration_secs: d }) => {
// Clamp so a stale Prime never causes immediate completion
// on the next Resume tick.
total_secs = d.max(elapsed_secs.saturating_add(1));
Transition::Stay
}
Ok(TimerCommand::Shutdown) | Err(_) => Transition::Break,
_ => Transition::Stay,
},
// -----------------------------------------------------------------
Phase::Running(seg) => {
// Drift-correcting sleep: target the absolute instant of the
// next scheduled tick rather than sleeping for a fixed period.
let next_tick = seg.start + tick_interval * (seg.ticks + 1);
let wait = next_tick.saturating_duration_since(Instant::now());
match cmd_rx.recv_timeout(wait) {
// --- tick fired ---
Err(RecvTimeoutError::Timeout) => {
seg.ticks += 1;
elapsed_secs = seg.elapsed_at_start + seg.ticks;
let _ = event_tx.send(TimerEvent::Tick { elapsed_secs, total_secs });
if elapsed_secs >= total_secs {
let _ = event_tx.send(TimerEvent::Complete { skipped: false });
elapsed_secs = 0;
Transition::To(Phase::Idle)
} else {
Transition::Stay
}
}
Err(RecvTimeoutError::Disconnected) => Transition::Break,
// --- commands ---
Ok(TimerCommand::Pause) => {
let _ = event_tx.send(TimerEvent::Paused { elapsed_secs });
Transition::To(Phase::Paused)
}
Ok(TimerCommand::Suspend) => {
let _ = event_tx.send(TimerEvent::Suspended { elapsed_secs });
Transition::To(Phase::Suspended)
}
Ok(TimerCommand::Skip) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Complete { skipped: true });
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Reset) => {
elapsed_secs = 0;
let _ = event_tx.send(TimerEvent::Reset);
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Reconfigure { duration_secs: d }) => {
total_secs = d;
elapsed_secs = 0;
Transition::To(Phase::Idle)
}
Ok(TimerCommand::Prime { duration_secs: d }) => {
// Clamp so a stale Prime arriving while the timer is
// running never causes an immediate spurious completion
// on the next tick.
total_secs = d.max(elapsed_secs.saturating_add(1));
Transition::Stay
}
Ok(TimerCommand::Shutdown) => Transition::Break,
_ => Transition::Stay,
}
}
};
match tr {
Transition::Stay => {}
Transition::To(new_phase) => phase = new_phase,
Transition::Break => break 'engine,
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
/// Short tick used by all tests so the suite runs in < 1 s total.
const TICK: Duration = Duration::from_millis(20);
fn drain(rx: &Receiver<TimerEvent>) -> Vec<TimerEvent> {
let mut events = Vec::new();
while let Ok(e) = rx.recv_timeout(Duration::from_millis(5)) {
events.push(e);
}
events
}
fn collect_until_complete(rx: &Receiver<TimerEvent>, timeout: Duration) -> Vec<TimerEvent> {
let deadline = Instant::now() + timeout;
let mut events = Vec::new();
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
match rx.recv_timeout(remaining) {
Ok(e) => {
let done = matches!(e, TimerEvent::Complete { .. });
events.push(e);
if done {
break;
}
}
Err(_) => break,
}
}
events
}
#[test]
fn fires_correct_number_of_ticks_and_completes() {
let (handle, rx) = spawn(5, TICK);
handle.send(TimerCommand::Start);
let events = collect_until_complete(&rx, Duration::from_secs(2));
let ticks: Vec<_> = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { .. }))
.collect();
assert_eq!(ticks.len(), 5, "expected 5 ticks, got {}", ticks.len());
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"last event must be Complete"
);
}
#[test]
fn elapsed_secs_increments_monotonically() {
let (handle, rx) = spawn(4, TICK);
handle.send(TimerCommand::Start);
let events = collect_until_complete(&rx, Duration::from_secs(2));
let mut last_elapsed = 0;
for e in &events {
if let TimerEvent::Tick { elapsed_secs, .. } = e {
assert!(*elapsed_secs > last_elapsed);
last_elapsed = *elapsed_secs;
}
}
}
#[test]
fn pause_stops_ticks_and_resume_continues() {
let (handle, rx) = spawn(6, TICK);
handle.send(TimerCommand::Start);
// Let 2 ticks fire, then pause.
std::thread::sleep(TICK * 2 + TICK / 2);
handle.send(TimerCommand::Pause);
// Collect events so far.
std::thread::sleep(TICK * 3); // no ticks should arrive during this gap
let events_before_resume = drain(&rx);
let paused = events_before_resume
.iter()
.filter(|e| matches!(e, TimerEvent::Paused { .. }))
.count();
let ticks_before_pause = events_before_resume
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { .. }))
.count();
assert_eq!(paused, 1, "expected 1 Paused event");
assert!(ticks_before_pause >= 2, "should have at least 2 ticks before pause");
// Resume and let the rest complete.
handle.send(TimerCommand::Resume);
let events_after = collect_until_complete(&rx, Duration::from_secs(2));
assert!(
events_after
.iter()
.any(|e| matches!(e, TimerEvent::Resumed { .. })),
"expected Resumed event"
);
assert!(
events_after
.iter()
.any(|e| matches!(e, TimerEvent::Complete { .. })),
"expected Complete after resume"
);
}
#[test]
fn reset_returns_to_zero_and_fires_reset_event() {
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Start);
std::thread::sleep(TICK * 2 + TICK / 2);
handle.send(TimerCommand::Reset);
let events = drain(&rx);
assert!(
events.iter().any(|e| matches!(e, TimerEvent::Reset)),
"expected Reset event"
);
// No Complete should have fired.
assert!(
!events.iter().any(|e| matches!(e, TimerEvent::Complete { .. })),
"Complete must not fire on Reset"
);
}
#[test]
fn skip_fires_complete_immediately() {
let (handle, rx) = spawn(30, TICK);
handle.send(TimerCommand::Start);
std::thread::sleep(TICK / 2);
handle.send(TimerCommand::Skip);
let events = collect_until_complete(&rx, Duration::from_millis(500));
assert!(
events.iter().any(|e| matches!(e, TimerEvent::Complete { .. })),
"Skip must trigger Complete"
);
// Should have completed well before 30 ticks elapsed.
let ticks = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { .. }))
.count();
assert!(ticks < 5, "Skip should complete before many ticks fire");
}
#[test]
fn suspend_and_wake_resume_preserves_position() {
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Start);
// Let 3 ticks fire, then suspend.
std::thread::sleep(TICK * 3 + TICK / 2);
handle.send(TimerCommand::Suspend);
let before = drain(&rx);
let suspended_elapsed = before.iter().find_map(|e| {
if let TimerEvent::Suspended { elapsed_secs } = e {
Some(*elapsed_secs)
} else {
None
}
});
assert!(
suspended_elapsed.is_some(),
"expected Suspended event with elapsed_secs"
);
let saved = suspended_elapsed.unwrap();
assert!(saved >= 3, "elapsed at suspend should be >= 3 s, got {saved}");
// Gap: simulate OS sleep (no ticks must fire).
std::thread::sleep(TICK * 5);
let during_suspend = drain(&rx);
assert!(
!during_suspend.iter().any(|e| matches!(e, TimerEvent::Tick { .. })),
"no ticks must fire while suspended"
);
// Wake and verify the timer continues from the saved position.
handle.send(TimerCommand::WakeResume);
let after = collect_until_complete(&rx, Duration::from_secs(2));
let resumed = after.iter().find_map(|e| {
if let TimerEvent::Resumed { elapsed_secs } = e {
Some(*elapsed_secs)
} else {
None
}
});
assert_eq!(
resumed,
Some(saved),
"Resumed event must carry the same elapsed_secs as Suspended"
);
assert!(
after.iter().any(|e| matches!(e, TimerEvent::Complete { .. })),
"timer must complete after WakeResume"
);
}
#[test]
fn shutdown_terminates_thread_cleanly() {
let (handle, _rx) = spawn(60, TICK);
handle.send(TimerCommand::Start);
std::thread::sleep(TICK);
// Shutdown must not deadlock or panic.
handle.send(TimerCommand::Shutdown);
// Give the thread time to exit gracefully.
std::thread::sleep(Duration::from_millis(50));
}
#[test]
fn reset_while_idle_emits_reset_event() {
// Before this fix Reset was silently dropped in Phase::Idle, leaving
// the event listener blocked and the frontend stale.
let (handle, rx) = spawn(5, TICK);
// Do NOT start — engine begins in Idle.
handle.send(TimerCommand::Reset);
let events = drain(&rx);
assert!(
events.iter().any(|e| matches!(e, TimerEvent::Reset)),
"Reset while Idle must emit a Reset event"
);
}
#[test]
fn reconfigure_changes_duration_in_idle() {
// Spawn with duration=10, then Reconfigure to 3 before Start.
// The engine must use the new duration when Started.
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Reconfigure { duration_secs: 3 });
handle.send(TimerCommand::Start);
let events = collect_until_complete(&rx, Duration::from_secs(2));
let ticks = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { .. }))
.count();
assert_eq!(ticks, 3, "Reconfigure to 3s should yield 3 ticks, got {ticks}");
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"last event must be Complete after reconfigured timer"
);
}
#[test]
fn prime_updates_duration_without_cancelling_fresh_start() {
// Models the skip/reset race: the UI sends Start for the next round
// before the listener's follow-up duration update reaches the engine.
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Start);
std::thread::sleep(TICK / 2);
handle.send(TimerCommand::Prime { duration_secs: 3 });
let events = collect_until_complete(&rx, Duration::from_secs(2));
let ticks = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { .. }))
.count();
assert_eq!(ticks, 3, "Prime to 3s should keep the timer running and yield 3 ticks, got {ticks}");
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"last event must be Complete after priming a fresh start"
);
}
#[test]
fn prime_below_elapsed_while_running_does_not_complete_immediately() {
// If Prime fires with duration_secs < elapsed_secs while the timer is
// running, the engine must not complete on the very next tick — it
// should run at least one more tick first.
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Start);
// Let 5 ticks fire so elapsed_secs = 5.
std::thread::sleep(TICK * 5 + TICK / 2);
// Prime with duration below elapsed — without the clamp this would fire
// Complete on the very next tick.
handle.send(TimerCommand::Prime { duration_secs: 2 });
let events = collect_until_complete(&rx, Duration::from_secs(2));
let ticks_after_prime: Vec<_> = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { elapsed_secs, .. } if *elapsed_secs > 5))
.collect();
assert!(
!ticks_after_prime.is_empty(),
"at least one tick must fire after Prime before Complete"
);
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"timer must still complete after clamped Prime"
);
}
#[test]
fn prime_below_elapsed_while_paused_does_not_complete_immediately_on_resume() {
// Same edge case in Paused phase: Prime with duration_secs < elapsed_secs
// must not cause immediate completion on the first tick after Resume.
let (handle, rx) = spawn(10, TICK);
handle.send(TimerCommand::Start);
// Let 5 ticks fire, then pause.
std::thread::sleep(TICK * 5 + TICK / 2);
handle.send(TimerCommand::Pause);
std::thread::sleep(TICK); // let Paused event arrive
drain(&rx);
// Prime with duration below elapsed.
handle.send(TimerCommand::Prime { duration_secs: 2 });
handle.send(TimerCommand::Resume);
let events = collect_until_complete(&rx, Duration::from_secs(2));
let ticks_after_resume: Vec<_> = events
.iter()
.filter(|e| matches!(e, TimerEvent::Tick { elapsed_secs, .. } if *elapsed_secs > 5))
.collect();
assert!(
!ticks_after_resume.is_empty(),
"at least one tick must fire after Resume before Complete"
);
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"timer must still complete after clamped Prime in Paused phase"
);
}
#[test]
fn drift_complete_within_tolerance() {
// 5 ticks at TICK (20 ms) = nominal 100 ms.
// Allow generous ±100 ms for CI scheduling jitter while still
// catching runaway drift (e.g. the engine sleeping for 1 s instead of 20 ms).
let (handle, rx) = spawn(5, TICK);
let t0 = Instant::now();
handle.send(TimerCommand::Start);
let events = collect_until_complete(&rx, Duration::from_millis(600));
let wall = t0.elapsed();
assert!(
matches!(events.last(), Some(TimerEvent::Complete { .. })),
"timer must complete"
);
let nominal = TICK * 5; // 100 ms
assert!(
wall >= nominal / 2,
"completed suspiciously fast ({wall:?}); possible clock issue"
);
assert!(
wall <= nominal + Duration::from_millis(200),
"drift exceeded tolerance: {wall:?} for nominal {nominal:?}"
);
}
}