1use std::collections::VecDeque;
21use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
22use std::time::{Duration, SystemTime};
23
24use schedr_proto::pb;
25
26const DRIFT_PER_MILLE: u32 = 1;
29
30const PAUSE_SLACK: Duration = Duration::from_secs(1);
33
34const PAUSE_PER_MILLE: u32 = 2;
36
37pub const SENT_KEPT: usize = 100_000;
42
43pub const DEFAULT_SAMPLE_WINDOW: Duration = Duration::from_mins(10);
46
47pub const DEFAULT_SKEW_WARNING: Duration = Duration::from_secs(2);
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct Local {
54 pub boot: Duration,
56 pub wall: SystemTime,
58}
59
60impl Local {
61 #[must_use]
63 pub fn now() -> Self {
64 Self {
65 boot: boot_now(),
66 wall: SystemTime::now(),
67 }
68 }
69}
70
71#[must_use]
74pub fn boot_now() -> Duration {
75 #[cfg(any(target_os = "linux", target_os = "android"))]
76 let clock = rustix::time::ClockId::Boottime;
77 #[cfg(not(any(target_os = "linux", target_os = "android")))]
78 let clock = rustix::time::ClockId::Monotonic;
79 let now = rustix::time::clock_gettime(clock);
80 Duration::new(
81 u64::try_from(now.tv_sec).unwrap_or(0),
82 u32::try_from(now.tv_nsec).unwrap_or(0),
83 )
84}
85
86fn paused(then: Local, now: Local) -> bool {
89 let since = now.boot.saturating_sub(then.boot);
90 let walked = now.wall.duration_since(then.wall).unwrap_or_default();
91 walked > since + PAUSE_SLACK + since / 1000 * PAUSE_PER_MILLE
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97struct Sample {
98 timeline: u64,
99 sent: Local,
100 master_ms: i64,
101 arrived: Local,
102}
103
104impl Sample {
105 fn at_least_as_tight_as(&self, older: &Self) -> bool {
111 let sent = i128::try_from(self.sent.boot.as_nanos()).unwrap_or(i128::MAX)
112 - i128::try_from(older.sent.boot.as_nanos()).unwrap_or(i128::MAX);
113 let master = (i128::from(self.master_ms) - i128::from(older.master_ms)) * 1_000_000;
114 let allowed = master - master / 1000 * i128::from(DRIFT_PER_MILLE);
115 sent >= allowed
116 }
117}
118
119impl Sample {
120 fn half_round_trip(&self) -> Duration {
122 self.arrived.boot.saturating_sub(self.sent.boot) / 2
123 }
124
125 fn places_as_closely_as(&self, older: &Self) -> bool {
128 let since = self.sent.boot.saturating_sub(older.sent.boot);
129 self.half_round_trip() <= older.half_round_trip() + since / 1000 * DRIFT_PER_MILLE
130 }
131}
132
133fn wall_skew(master_ms: i64, from: SystemTime, to: SystemTime) -> Duration {
135 let master = SystemTime::UNIX_EPOCH
136 + Duration::from_millis(u64::try_from(master_ms).unwrap_or_default());
137 master
138 .duration_since(to)
139 .or_else(|_| from.duration_since(master))
140 .unwrap_or_default()
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct LastStamp {
146 pub master_ms: i64,
148 pub wall_ms: i64,
150 pub arrived: Local,
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub struct SampleReading {
157 pub age: Duration,
159 pub round_trip: Duration,
161}
162
163#[derive(Debug, Clone)]
168pub struct Outbox {
169 sent: VecDeque<(u64, Local)>,
171 next: u64,
173 handled: u64,
175 kept: usize,
177}
178
179impl Default for Outbox {
180 fn default() -> Self {
181 Self {
182 sent: VecDeque::new(),
183 next: 0,
184 handled: 0,
185 kept: SENT_KEPT,
186 }
187 }
188}
189
190impl Outbox {
191 pub fn sent(&mut self, at: Local) -> u64 {
193 let sequence = self.next;
194 self.next += 1;
195 if self.sent.len() >= self.kept {
196 self.sent.pop_front();
197 }
198 self.sent.push_back((sequence, at));
199 sequence
200 }
201
202 pub fn stamp(&mut self, at: Local) -> pb::WorkerClock {
205 pb::WorkerClock {
206 sequence: self.sent(at),
207 heard_sequence: self.handled,
208 }
209 }
210
211 pub fn handled(&mut self, sequence: u64) {
214 self.handled = self.handled.max(sequence);
215 }
216}
217
218pub type SharedOutbox = Arc<Mutex<Outbox>>;
220
221pub fn lock(outbox: &SharedOutbox) -> MutexGuard<'_, Outbox> {
223 outbox.lock().unwrap_or_else(PoisonError::into_inner)
224}
225
226#[derive(Debug)]
228pub struct MasterTime {
229 outbox: SharedOutbox,
231 samples: VecDeque<Sample>,
234 narrowest: Option<Sample>,
237 window: Duration,
239 last: Option<LastStamp>,
241 heard_sent: Option<Local>,
244}
245
246impl Clone for MasterTime {
247 fn clone(&self) -> Self {
249 Self {
250 outbox: Arc::new(Mutex::new(lock(&self.outbox).clone())),
251 samples: self.samples.clone(),
252 narrowest: self.narrowest,
253 window: self.window,
254 last: self.last,
255 heard_sent: self.heard_sent,
256 }
257 }
258}
259
260impl Default for MasterTime {
261 fn default() -> Self {
262 Self::with_window(DEFAULT_SAMPLE_WINDOW)
263 }
264}
265
266impl MasterTime {
267 #[must_use]
270 pub fn keeping(self, most: usize) -> Self {
271 self.outbox
272 .lock()
273 .unwrap_or_else(std::sync::PoisonError::into_inner)
274 .kept = most.max(1);
275 self
276 }
277
278 #[must_use]
280 pub fn with_window(window: Duration) -> Self {
281 Self {
282 outbox: SharedOutbox::default(),
283 samples: VecDeque::new(),
284 narrowest: None,
285 window,
286 last: None,
287 heard_sent: None,
288 }
289 }
290
291 pub fn open(&mut self) -> tokio::time::Instant {
295 let opened = tokio::time::Instant::now();
296 *self = Self::with_window(self.window);
297 opened
298 }
299
300 #[must_use]
302 pub fn outbox(&self) -> SharedOutbox {
303 Arc::clone(&self.outbox)
304 }
305
306 fn best(&self) -> Option<Sample> {
308 self.samples.front().copied()
309 }
310
311 #[must_use]
313 pub const fn last(&self) -> Option<LastStamp> {
314 self.last
315 }
316
317 #[must_use]
324 pub fn estimate(&self, now: Local) -> Option<(u64, i64)> {
325 let best = self.narrowest?;
326 if paused(best.sent, now) {
327 return None;
328 }
329 let middle = best.sent.boot + best.arrived.boot.saturating_sub(best.sent.boot) / 2;
330 let since = i64::try_from(now.boot.saturating_sub(middle).as_millis()).ok()?;
331 Some((best.timeline, best.master_ms.checked_add(since)?))
332 }
333
334 #[must_use]
336 pub fn reading(&self, now: Local) -> Option<SampleReading> {
337 let best = self.best()?;
338 Some(SampleReading {
339 age: now.boot.saturating_sub(best.sent.boot),
340 round_trip: best.arrived.boot.saturating_sub(best.sent.boot),
341 })
342 }
343
344 pub fn sent(&mut self, at: Local) -> u64 {
346 lock(&self.outbox).sent(at)
347 }
348
349 pub fn heard(&mut self, clock: &pb::MasterClock, now: Local) -> Option<Duration> {
353 self.last = Some(LastStamp {
354 master_ms: clock.master_ms,
355 wall_ms: clock.wall_ms,
356 arrived: now,
357 });
358 if self
359 .best()
360 .is_some_and(|best| best.timeline != clock.timeline)
361 {
362 self.samples.clear();
363 self.narrowest = None;
364 }
365 let (number, sent) = {
367 let mut outbox = lock(&self.outbox);
368 while outbox
369 .sent
370 .front()
371 .is_some_and(|(number, _)| *number < clock.heard_sequence)
372 {
373 outbox.sent.pop_front();
374 }
375 *outbox.sent.front()?
376 };
377 if number != clock.heard_sequence {
378 return None;
379 }
380 self.heard_sent = Some(sent);
381 let sample = Sample {
382 timeline: clock.timeline,
383 sent,
384 master_ms: clock.master_ms,
385 arrived: now,
386 };
387 if self.best().is_some_and(|best| paused(best.sent, sent)) {
390 self.samples.clear();
391 }
392 if self
393 .narrowest
394 .is_none_or(|old| paused(old.sent, sent) || sample.places_as_closely_as(&old))
395 {
396 self.narrowest = Some(sample);
397 }
398 while self
401 .samples
402 .back()
403 .is_some_and(|last| sample.at_least_as_tight_as(last))
404 {
405 self.samples.pop_back();
406 }
407 self.samples.push_back(sample);
408 while self
409 .samples
410 .front()
411 .is_some_and(|first| sent.boot.saturating_sub(first.sent.boot) > self.window)
412 {
413 self.samples.pop_front();
414 }
415 Some(wall_skew(clock.wall_ms, sent.wall, now.wall))
416 }
417
418 #[must_use]
424 pub fn cutoff_in(&self, lease: Duration, now: Local) -> Option<Duration> {
425 let last = self.last?;
426 self.best()?;
427 let lease_ms = i64::try_from(lease.as_millis()).unwrap_or(i64::MAX);
428 let by_stamp = self.until(last.master_ms.saturating_add(lease_ms), now);
429 let by_heard = self.heard_sent.map(|sent| {
430 if paused(sent, now) {
431 return Duration::ZERO;
432 }
433 let at = sent.boot + lease.saturating_sub(lease / 1000 * DRIFT_PER_MILLE);
434 at.saturating_sub(now.boot)
435 });
436 Some(by_heard.map_or(by_stamp, |heard| heard.min(by_stamp)))
437 }
438
439 #[must_use]
442 pub fn until(&self, by_ms: i64, now: Local) -> Duration {
443 self.reached_at(by_ms, now)
444 .map_or(Duration::ZERO, |at| at.saturating_sub(now.boot))
445 }
446
447 fn reached_at(&self, by_ms: i64, now: Local) -> Option<Duration> {
450 let best = self.best()?;
451 if paused(best.sent, now) {
452 return None;
453 }
454 let ahead = Duration::from_millis(u64::try_from(by_ms - best.master_ms - 1).ok()?);
456 Some(best.sent.boot + ahead.saturating_sub(ahead / 1000 * DRIFT_PER_MILLE))
457 }
458
459 #[must_use]
462 pub fn past(&self, by_ms: i64, reserve: Duration, now: Local) -> bool {
463 self.slack(by_ms, reserve, now).is_none()
464 }
465
466 #[must_use]
469 pub fn slack(&self, by_ms: i64, reserve: Duration, now: Local) -> Option<Duration> {
470 let at = self.reached_at(by_ms, now)?.saturating_sub(reserve);
471 at.checked_sub(now.boot).filter(|left| !left.is_zero())
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478
479 fn at(boot_ms: u64) -> Local {
480 Local {
481 boot: Duration::from_millis(boot_ms),
482 wall: SystemTime::UNIX_EPOCH + Duration::from_millis(boot_ms),
483 }
484 }
485
486 fn clock(timeline: u64, master_ms: i64, heard: u64) -> pb::MasterClock {
487 pb::MasterClock {
488 timeline,
489 master_ms,
490 heard_sequence: heard,
491 wall_ms: 0,
492 lease_epoch: 0,
493 sequence: 0,
494 }
495 }
496
497 fn opened(register_at: u64) -> MasterTime {
498 let mut time = MasterTime::default();
499 assert_eq!(time.sent(at(register_at)), 0, "the Register");
500 time
501 }
502
503 #[test]
504 fn a_deadline_counts_from_the_send_of_what_the_master_had_heard() {
505 let mut time = opened(1000);
507 assert!(time.past(60_000, Duration::ZERO, at(1001)), "no sample yet");
508 time.heard(&clock(7, 50_000, 0), at(0));
509 assert!(!time.past(60_000, Duration::ZERO, at(10_989)));
511 assert!(time.past(60_000, Duration::ZERO, at(10_990)));
512 assert!(time.past(60_000, Duration::from_secs(2), at(8_990)));
514 assert!(time.past(49_000, Duration::ZERO, at(1001)));
516 }
517
518 #[test]
519 fn master_time_now_is_estimated_from_the_middle_of_the_best_samples_round_trip() {
520 let mut time = opened(1000);
523 assert_eq!(time.estimate(at(1001)), None, "no sample yet");
524 time.heard(&clock(7, 50_000, 0), at(1200));
525 assert_eq!(time.estimate(at(3100)), Some((7, 52_000)));
526 let paused = Local {
528 boot: Duration::from_millis(3100),
529 wall: SystemTime::UNIX_EPOCH + Duration::from_secs(3600),
530 };
531 assert_eq!(time.estimate(paused), None);
532 }
533
534 #[test]
535 fn the_estimate_takes_the_narrowest_round_trip_not_the_tightest_lower_bound() {
536 let mut time = opened(0);
540 time.heard(&clock(7, 100, 0), at(10_000));
541 assert_eq!(time.estimate(at(10_000)), Some((7, 5100)));
542 assert_eq!(time.sent(at(11_000)), 1);
543 time.heard(&clock(7, 11_200, 1), at(11_100));
544 assert_eq!(time.estimate(at(20_000)), Some((7, 20_150)));
545 assert_eq!(time.sent(at(12_000)), 2);
547 time.heard(&clock(7, 12_400, 2), at(12_600));
548 assert_eq!(time.estimate(at(20_000)), Some((7, 20_150)));
549 assert_eq!(time.best().map(|b| b.master_ms), Some(100));
550 }
551
552 #[test]
553 fn the_tightest_sample_counts_and_one_naming_nothing_sent_changes_nothing() {
554 let mut time = opened(0);
555 let one = time.sent(at(1000));
556 let two = time.sent(at(2000));
557 assert_eq!((one, two), (1, 2));
558 time.heard(&clock(7, 10_000, 1), at(0));
560 time.heard(&clock(7, 12_500, 2), at(0));
562 assert!(!time.past(20_000, Duration::ZERO, at(10_989)));
563 assert!(time.past(20_000, Duration::ZERO, at(10_990)));
564 time.heard(&clock(7, 1, 9), at(0));
566 time.heard(&clock(7, 1, 1), at(0));
567 assert!(!time.past(20_000, Duration::ZERO, at(10_989)));
568 }
569
570 #[test]
571 fn another_timeline_drops_what_was_known() {
572 let mut time = opened(0);
573 time.heard(&clock(7, 10_000, 0), at(0));
574 let beat = time.sent(at(1000));
575 time.heard(&clock(8, 3_000, beat), at(0));
577 assert!(!time.past(5_000, Duration::ZERO, at(2_997)));
579 assert!(time.past(5_000, Duration::ZERO, at(2_998)));
580 }
581
582 #[test]
583 fn a_pause_the_boot_clock_didnt_count_makes_every_deadline_passed() {
584 let mut time = opened(1000);
585 time.heard(&clock(7, 0, 0), at(0));
586 let paused = Local {
588 boot: Duration::from_millis(3000),
589 wall: SystemTime::UNIX_EPOCH + Duration::from_secs(11),
590 };
591 assert!(time.past(60_000, Duration::ZERO, paused));
592 let running = Local {
594 boot: Duration::from_millis(3000),
595 wall: SystemTime::UNIX_EPOCH + Duration::from_millis(3_900),
596 };
597 assert!(!time.past(60_000, Duration::ZERO, running));
598 }
599
600 #[test]
601 fn after_a_pause_the_next_sample_replaces_the_old_one() {
602 let mut time = opened(1000);
603 time.heard(&clock(7, 0, 0), at(0));
604 let after = Local {
606 boot: Duration::from_millis(3000),
607 wall: SystemTime::UNIX_EPOCH + Duration::from_secs(11),
608 };
609 let beat = time.sent(after);
610 time.heard(&clock(7, 10_000, beat), at(0));
612 let later = Local {
613 boot: Duration::from_millis(3500),
614 wall: SystemTime::UNIX_EPOCH + Duration::from_millis(11_500),
615 };
616 assert!(!time.past(12_000, Duration::ZERO, later));
618 assert!(time.past(
619 12_000,
620 Duration::ZERO,
621 Local {
622 boot: Duration::from_millis(4998),
623 wall: SystemTime::UNIX_EPOCH + Duration::from_millis(12_998),
624 }
625 ));
626 }
627
628 #[test]
629 fn an_equally_tight_later_sample_replaces_an_hours_old_one() {
630 let mut time = opened(0);
633 time.heard(&clock(7, 0, 0), at(0));
634 let hours = 40_000_000;
635 let deadline = hours + 60_000;
636 let now = at(u64::try_from(hours).unwrap());
637 assert!(
638 time.past(deadline, Duration::from_secs(20), now),
639 "the old one alone"
640 );
641 let beat = time.sent(now);
642 time.heard(&clock(7, hours, beat), at(0));
643 assert!(!time.past(deadline, Duration::from_secs(20), now));
644 let mut time = opened(0);
646 time.heard(&clock(7, 0, 0), at(0));
647 let beat = time.sent(at(10_000));
648 time.heard(&clock(7, 11_000, beat), at(0));
649 assert!(!time.past(20_000, Duration::ZERO, at(19_979)));
650 assert!(time.past(20_000, Duration::ZERO, at(19_980)));
651 }
652
653 #[test]
654 fn the_boot_clock_reads() {
655 let first = boot_now();
656 assert!(boot_now() >= first);
657 }
658}
659
660#[cfg(test)]
661mod window_tests {
662 use super::*;
663
664 fn at(boot_ms: u64) -> Local {
665 Local {
666 boot: Duration::from_millis(boot_ms),
667 wall: SystemTime::UNIX_EPOCH + Duration::from_millis(boot_ms),
668 }
669 }
670
671 fn clock(master_ms: i64, heard: u64) -> pb::MasterClock {
672 pb::MasterClock {
673 timeline: 7,
674 master_ms,
675 heard_sequence: heard,
676 wall_ms: master_ms,
677 lease_epoch: 0,
678 sequence: 0,
679 }
680 }
681
682 #[test]
683 fn the_tightest_sample_is_taken_over_the_window() {
684 let mut time = MasterTime::with_window(Duration::from_secs(10));
687 time.open();
688 let one = time.sent(at(1_000));
689 time.heard(&clock(11_000, one), at(1_010));
690 let two = time.sent(at(5_000));
691 time.heard(&clock(16_000, two), at(5_600));
692 assert_eq!(
695 time.until(30_000, at(9_000)),
696 Duration::from_micros(10_980_001)
697 );
698 let reading = time.reading(at(9_000)).unwrap();
699 assert_eq!(
700 (reading.age, reading.round_trip),
701 (Duration::from_secs(8), Duration::from_millis(10))
702 );
703 let three = time.sent(at(12_000));
706 time.heard(&clock(24_000, three), at(12_900));
707 assert_eq!(
708 time.until(30_000, at(9_000)),
709 Duration::from_micros(9_985_001)
710 );
711 assert!(time.slack(30_000, Duration::ZERO, at(18_986)).is_none());
712 assert!(time.slack(30_000, Duration::ZERO, at(18_985)).is_some());
713 assert_eq!(time.last().unwrap().wall_ms, 24_000);
714 }
715
716 #[test]
717 fn the_cutoff_counts_from_the_last_stamp_on_master_time() {
718 let mut time = MasterTime::with_window(Duration::from_secs(600));
724 assert_eq!(
725 time.cutoff_in(Duration::from_secs(10), at(0)),
726 None,
727 "nothing heard"
728 );
729 time.sent(at(1_000));
730 time.heard(&clock(50_000, 0), at(1_100));
731 let mut pushed = time.clone();
732 pushed.heard(&clock(55_000, 0), at(9_000));
733 assert_eq!(
734 pushed.cutoff_in(Duration::from_secs(10), at(9_000)),
735 Some(Duration::from_millis(1_990))
736 );
737 time.sent(at(8_000));
740 time.heard(&clock(55_000, 1), at(9_000));
741 assert_eq!(
742 time.cutoff_in(Duration::from_secs(10), at(9_000)),
743 Some(Duration::from_micros(8_989_001))
744 );
745 assert_eq!(
746 time.cutoff_in(Duration::from_secs(10), at(17_990)),
747 Some(Duration::ZERO)
748 );
749 }
750
751 #[test]
752 fn the_cutoff_counts_from_the_send_of_what_the_master_last_heard() {
753 let mut time = MasterTime::with_window(Duration::from_secs(600));
759 time.sent(at(1_000));
760 time.heard(&clock(50_000, 0), at(1_100));
761 time.sent(at(11_000));
762 time.heard(&clock(80_000, 0), at(31_000));
763 assert_eq!(
764 time.cutoff_in(Duration::from_secs(60), at(31_000)),
765 Some(Duration::from_millis(29_940))
766 );
767 }
768
769 #[test]
770 fn the_masters_wall_clock_is_compared_over_the_round_trip() {
771 let skew = |wall_ms| {
774 let mut time = MasterTime::default();
775 time.sent(at(1_000));
776 time.heard(
777 &pb::MasterClock {
778 wall_ms,
779 ..clock(5_000, 0)
780 },
781 at(1_500),
782 )
783 };
784 assert_eq!(skew(1_200), Some(Duration::ZERO));
785 assert_eq!(skew(3_500), Some(Duration::from_secs(2)));
786 assert_eq!(skew(200), Some(Duration::from_millis(800)));
787 let mut time = MasterTime::default();
788 assert_eq!(
789 time.heard(&clock(5_000, 3), at(1_500)),
790 None,
791 "not a sample"
792 );
793 }
794
795 #[test]
796 fn messages_never_answered_dont_hold_back_the_count() {
797 let mut time = MasterTime::with_window(Duration::from_secs(600));
800 for n in 0..6 {
801 assert_eq!(time.sent(at(1_000 + n * 1_000)), n);
802 }
803 time.heard(&clock(50_000, 5), at(6_100));
804 assert_eq!(
805 time.reading(at(6_100)).map(|r| r.round_trip),
806 Some(Duration::from_millis(100))
807 );
808 }
809
810 #[test]
811 fn the_outbox_numbers_each_message_and_echoes_what_was_handled() {
812 let mut outbox = Outbox::default();
815 let register = outbox.stamp(at(1_000));
816 assert_eq!((register.sequence, register.heard_sequence), (0, 0));
817 outbox.handled(1);
818 let started = outbox.stamp(at(1_010));
819 outbox.handled(4);
820 outbox.handled(3);
821 let beat = outbox.stamp(at(1_020));
822 assert_eq!(
823 [
824 (started.sequence, started.heard_sequence),
825 (beat.sequence, beat.heard_sequence)
826 ],
827 [(1, 1), (2, 4)],
828 "the highest handled, never lower"
829 );
830 }
831
832 #[test]
833 fn a_copy_of_master_time_goes_its_own_way() {
834 let mut time = MasterTime::default();
836 time.sent(at(1_000));
837 let mut copy = time.clone();
838 assert_eq!(copy.sent(at(2_000)), 1);
839 assert_eq!(time.sent(at(3_000)), 1);
840 }
841
842 #[test]
843 fn a_tighter_sample_drops_the_looser_ones_before_it() {
844 let mut time = MasterTime::with_window(Duration::from_secs(600));
845 time.open();
846 let one = time.sent(at(1_000));
847 time.heard(&clock(12_000, one), at(1_500));
848 let two = time.sent(at(2_000));
849 time.heard(&clock(12_000, two), at(2_001));
850 assert_eq!(time.samples.len(), 1);
852 assert_eq!(
853 time.until(13_000, at(2_000)),
854 Duration::from_micros(998_001)
855 );
856 }
857}