1use crate::{history::ClockSync, sequence_newer};
44const MAX_US: u64 = 1 << 53;
45const MAX_PROBE_AGE_US: u64 = 5_000_000;
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum ClockSampleIgnored {
53 TimestampOutOfRange,
55 ServerTimeReversed,
57 LocalTimeReversed,
59 ProbeNotRetained,
62 ProbeTimestampMismatch,
64 ProbeExpired,
66 ServerTimeNotNewer,
68 TickNotCurrentOrNewer,
71 RttOutOfRange,
73 TickOverflow,
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum ClockAge {
83 Unknown,
85 TimestampOutOfRange,
87 BeforeTimestamp,
89 AgeMicros(u64),
91}
92
93fn age_at(timestamp: Option<u64>, now_us: u64) -> ClockAge {
94 let Some(timestamp) = timestamp else {
95 return ClockAge::Unknown;
96 };
97 if now_us > MAX_US {
98 ClockAge::TimestampOutOfRange
99 } else if let Some(age) = now_us.checked_sub(timestamp) {
100 ClockAge::AgeMicros(age)
101 } else {
102 ClockAge::BeforeTimestamp
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub struct PendingClockProbe {
112 pub nonce: u32,
113 pub client_us: u64,
114 pub age: ClockAge,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq)]
121#[non_exhaustive]
122pub struct ClockDiagnostics {
123 pub local_us: u64,
124 pub tick_rate_hz: u16,
125 pub pending_probes: [Option<PendingClockProbe>; 4],
127 pub last_observed_us: Option<u64>,
128 pub sample_age: ClockAge,
129 pub rtt_seconds: Option<f64>,
130 pub offset_seconds: Option<f64>,
132 pub jitter_seconds: f64,
133 pub render_delay_ticks: u32,
136}
137#[derive(Clone, Copy, Debug)]
138struct Probe {
139 nonce: u32,
140 sent: u64,
141}
142#[derive(Clone, Copy, Debug)]
143struct Anchor {
144 tick: u32,
145 extended: u64,
146 server_us: u64,
147}
148#[derive(Clone, Debug, Default)]
151pub struct ClientClock {
152 sync: ClockSync,
153 probes: [Option<Probe>; 4],
154 next_nonce: u32,
155 anchor: Option<Anchor>,
156 jitter: f64,
157 last_rtt: Option<f64>,
158 last_observed_us: Option<u64>,
159}
160impl ClientClock {
161 pub fn probe(&mut self, local_us: u64) -> Option<(u32, u64)> {
165 if local_us > MAX_US {
166 return None;
167 }
168 self.next_nonce = self.next_nonce.wrapping_add(1);
169 let nonce = self.next_nonce;
170 self.probes[nonce as usize % 4] = Some(Probe {
171 nonce,
172 sent: local_us,
173 });
174 Some((nonce, local_us))
175 }
176 pub fn observe(
179 &mut self,
180 nonce: u32,
181 client_us: u64,
182 receive_us: u64,
183 send_us: u64,
184 tick: u32,
185 now_us: u64,
186 ) -> bool {
187 self.observe_detailed(nonce, client_us, receive_us, send_us, tick, now_us)
188 .is_ok()
189 }
190
191 pub fn observe_detailed(
197 &mut self,
198 nonce: u32,
199 client_us: u64,
200 receive_us: u64,
201 send_us: u64,
202 tick: u32,
203 now_us: u64,
204 ) -> Result<(), ClockSampleIgnored> {
205 if [client_us, receive_us, send_us, now_us]
206 .into_iter()
207 .any(|v| v > MAX_US)
208 {
209 return Err(ClockSampleIgnored::TimestampOutOfRange);
210 }
211 if send_us < receive_us {
212 return Err(ClockSampleIgnored::ServerTimeReversed);
213 }
214 if now_us < client_us {
215 return Err(ClockSampleIgnored::LocalTimeReversed);
216 }
217 let index = nonce as usize % 4;
218 let Some(probe) = self.probes[index] else {
219 return Err(ClockSampleIgnored::ProbeNotRetained);
220 };
221 if probe.nonce != nonce {
222 return Err(ClockSampleIgnored::ProbeNotRetained);
223 }
224 if probe.sent != client_us {
225 return Err(ClockSampleIgnored::ProbeTimestampMismatch);
226 }
227 if now_us - client_us > MAX_PROBE_AGE_US {
228 return Err(ClockSampleIgnored::ProbeExpired);
229 }
230 if let Some(a) = self.anchor {
231 if send_us <= a.server_us {
232 return Err(ClockSampleIgnored::ServerTimeNotNewer);
233 }
234 if !sequence_newer(tick, a.tick) && tick != a.tick {
235 return Err(ClockSampleIgnored::TickNotCurrentOrNewer);
236 }
237 }
238 let mut sync = self.sync;
239 if !sync.observe(
240 client_us as f64 / 1e6,
241 receive_us as f64 / 1e6,
242 send_us as f64 / 1e6,
243 now_us as f64 / 1e6,
244 ) {
245 return Err(ClockSampleIgnored::RttOutOfRange);
246 }
247 let extended = if let Some(a) = self.anchor {
248 let Some(n) = a.extended.checked_add(u64::from(tick.wrapping_sub(a.tick))) else {
249 return Err(ClockSampleIgnored::TickOverflow);
250 };
251 n
252 } else {
253 u64::from(tick)
254 };
255 let rtt = (now_us - client_us) as f64 / 1e6 - (send_us - receive_us) as f64 / 1e6;
256 if let Some(old) = self.last_rtt {
257 self.jitter += (rtt - old)
258 .abs()
259 .min(0.25)
260 .mul_add(0.125, -self.jitter * 0.125);
261 }
262 self.last_rtt = Some(rtt);
263 self.sync = sync;
264 self.anchor = Some(Anchor {
265 tick,
266 extended,
267 server_us: send_us,
268 });
269 self.probes[index] = None;
270 self.last_observed_us = Some(now_us);
271 Ok(())
272 }
273
274 pub fn diagnostics(&self, local_us: u64, hz: u16) -> ClockDiagnostics {
280 ClockDiagnostics {
281 local_us,
282 tick_rate_hz: hz,
283 pending_probes: self.probes.map(|probe| {
284 probe.map(|p| PendingClockProbe {
285 nonce: p.nonce,
286 client_us: p.sent,
287 age: age_at(Some(p.sent), local_us),
288 })
289 }),
290 last_observed_us: self.last_observed_us,
291 sample_age: age_at(self.last_observed_us, local_us),
292 rtt_seconds: self.rtt_seconds(),
293 offset_seconds: self.anchor.map(|_| self.sync.offset_seconds),
294 jitter_seconds: self.jitter,
295 render_delay_ticks: self.render_delay_ticks(hz),
296 }
297 }
298
299 pub fn reset(&mut self) {
306 *self = Self {
307 next_nonce: self.next_nonce,
308 ..Self::default()
309 };
310 }
311 pub fn rtt_seconds(&self) -> Option<f64> {
312 self.anchor.map(|_| self.sync.rtt_seconds)
313 }
314 pub fn jitter_seconds(&self) -> f64 {
315 self.jitter
316 }
317 pub fn render_delay_ticks(&self, hz: u16) -> u32 {
318 (6. + (self.jitter * f64::from(hz) * 2.).ceil()).clamp(6., 12.) as u32
319 }
320 pub fn estimated_tick(&self, local_us: u64, hz: u16) -> Option<f64> {
321 let a = self.anchor?;
322 if local_us > MAX_US || !(1..=1000).contains(&hz) {
323 return None;
324 }
325 let server_now = self.sync.server_time(local_us as f64 / 1e6);
326 let elapsed = (server_now - a.server_us as f64 / 1e6).clamp(-0.25, 5.);
327 Some(a.extended as f64 + elapsed * f64::from(hz))
328 }
329 pub fn render_tick(&self, local_us: u64, hz: u16) -> Option<f64> {
330 Some(self.estimated_tick(local_us, hz)? - f64::from(self.render_delay_ticks(hz)))
331 }
332}
333#[derive(Clone, Copy, Debug, Default)]
334pub struct TickUnwrapper {
335 latest: Option<(u32, u64)>,
336}
337impl TickUnwrapper {
338 pub fn reset(&mut self) {
342 self.latest = None;
343 }
344 pub fn observe(&mut self, tick: u32) -> Option<u64> {
345 let extended = match self.latest {
346 None => u64::from(tick),
347 Some((old, n)) => {
348 if !sequence_newer(tick, old) {
349 return None;
350 }
351 n.checked_add(u64::from(tick.wrapping_sub(old)))?
352 }
353 };
354 self.latest = Some((tick, extended));
355 Some(extended)
356 }
357 pub fn project(&self, tick: u32) -> Option<u64> {
358 let (last, n) = self.latest?;
359 if tick == last {
360 Some(n)
361 } else if sequence_newer(tick, last) {
362 n.checked_add(u64::from(tick.wrapping_sub(last)))
363 } else {
364 n.checked_sub(u64::from(last.wrapping_sub(tick)))
365 }
366 }
367}
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 fn ignored(
373 c: &mut ClientClock,
374 sample: (u32, u64, u64, u64, u32, u64),
375 why: ClockSampleIgnored,
376 ) {
377 let before = format!("{c:?}");
378 let mut legacy = c.clone();
379 let (id, client, receive, send, tick, now) = sample;
380 assert_eq!(
381 c.observe_detailed(id, client, receive, send, tick, now),
382 Err(why)
383 );
384 assert_eq!(format!("{c:?}"), before);
387 assert!(!legacy.observe(id, client, receive, send, tick, now));
388 assert_eq!(format!("{legacy:?}"), before);
389 }
390
391 #[test]
392 fn all_malformed_timestamps_preserve_the_probe_and_full_estimator() {
393 let mut c = ClientClock::default();
394 let (id, client) = c.probe(1_000_000).unwrap();
395 for sample in [
396 (id, MAX_US + 1, 11_050_000, 11_051_000, 1, 1_101_000),
397 (id, client, MAX_US + 1, 11_051_000, 1, 1_101_000),
398 (id, client, 11_050_000, MAX_US + 1, 1, 1_101_000),
399 (id, client, 11_050_000, 11_051_000, 1, MAX_US + 1),
400 ] {
401 ignored(&mut c, sample, ClockSampleIgnored::TimestampOutOfRange);
402 }
403 ignored(
404 &mut c,
405 (id, client, 11_051_000, 11_050_000, 1, 1_101_000),
406 ClockSampleIgnored::ServerTimeReversed,
407 );
408 ignored(
409 &mut c,
410 (id, client, 11_050_000, 11_051_000, 1, client - 1),
411 ClockSampleIgnored::LocalTimeReversed,
412 );
413 ignored(
414 &mut c,
415 (id, client + 1, 11_050_000, 11_051_000, 1, 1_101_000),
416 ClockSampleIgnored::ProbeTimestampMismatch,
417 );
418 ignored(
419 &mut c,
420 (id, client, 11_000_000, 11_200_000, 1, 1_100_000),
421 ClockSampleIgnored::RttOutOfRange,
422 );
423 assert!(c.observe(id, client, 11_050_000, 11_051_000, 1, 1_101_000));
424 assert!((c.sync.offset_seconds - 10.0).abs() < 1e-9);
425 assert!((c.sync.rtt_seconds - 0.1).abs() < 1e-9);
426
427 let (id, client) = c.probe(2_000_000).unwrap();
430 ignored(
431 &mut c,
432 (id, client, 12_000_000, 12_200_000, 2, 2_100_000),
433 ClockSampleIgnored::RttOutOfRange,
434 );
435 assert!(c.observe(id, client, 22_100_000, 22_101_000, 2, 2_201_000));
436 assert!((c.sync.offset_seconds - 11.25).abs() < 1e-9);
437 assert!((c.sync.rtt_seconds - 0.1125).abs() < 1e-9);
438 }
439
440 #[test]
441 fn retention_is_bounded_and_unknown_overwritten_consumed_share_one_reason() {
442 let mut c = ClientClock::default();
443 ignored(
444 &mut c,
445 (1, 0, 10, 10, 0, 10),
446 ClockSampleIgnored::ProbeNotRetained,
447 );
448 let first = c.probe(0).unwrap();
449 for t in 1..4 {
450 c.probe(t).unwrap();
451 }
452 let before = format!("{c:?}");
453 assert_eq!(c.probe(MAX_US + 1), None);
454 assert_eq!(format!("{c:?}"), before);
455 assert_eq!(
456 c.diagnostics(4, 64).pending_probes.iter().flatten().count(),
457 4
458 );
459 let newest = c.probe(4).unwrap();
460 ignored(
461 &mut c,
462 (first.0, first.1, 10, 10, 0, 10),
463 ClockSampleIgnored::ProbeNotRetained,
464 );
465 assert!(c.observe(newest.0, newest.1, 10, 10, 0, 10));
466 ignored(
467 &mut c,
468 (newest.0, newest.1, 10, 10, 0, 10),
469 ClockSampleIgnored::ProbeNotRetained,
470 );
471 assert_eq!(
472 c.diagnostics(10, 64)
473 .pending_probes
474 .iter()
475 .flatten()
476 .count(),
477 3
478 );
479 }
480
481 #[test]
482 fn expiration_is_inclusive_and_ignored_expired_samples_do_not_consume() {
483 let mut c = ClientClock::default();
484 let (id, client) = c.probe(1_000_000).unwrap();
485 ignored(
486 &mut c,
487 (id, client, 11_000_000, 11_000_000, 1, 6_000_001),
488 ClockSampleIgnored::ProbeExpired,
489 );
490 let p = c.diagnostics(6_000_001, 64).pending_probes[id as usize % 4].unwrap();
491 assert_eq!(p.age, ClockAge::AgeMicros(5_000_001));
492 assert!(c.observe(id, client, 11_000_000, 11_000_000, 1, 6_000_000));
494 assert_eq!(c.rtt_seconds(), Some(5.0));
495 }
496
497 #[test]
498 fn newer_server_anchor_does_not_impose_a_new_local_receive_watermark() {
499 let mut c = ClientClock::default();
500 let (early, early_sent) = c.probe(1_000_000).unwrap();
501 let (later, later_sent) = c.probe(1_050_000).unwrap();
502 assert!(c.observe(later, later_sent, 11_050_000, 11_051_000, 10, 1_200_000));
503 assert!(c.observe(early, early_sent, 11_060_000, 11_061_000, 11, 1_190_000));
506 assert_eq!(
507 c.diagnostics(1_200_000, 64).last_observed_us,
508 Some(1_190_000)
509 );
510 assert_eq!(
511 c.diagnostics(1_200_000, 64).sample_age,
512 ClockAge::AgeMicros(10_000)
513 );
514 }
515
516 #[test]
517 fn reorder_ambiguous_ticks_and_overflow_preserve_every_field() {
518 let mut c = ClientClock::default();
519 let (id, client) = c.probe(1_000_000).unwrap();
520 assert!(c.observe(id, client, 11_050_000, 11_051_000, u32::MAX, 1_101_000));
521 let (id, client) = c.probe(2_000_000).unwrap();
522 ignored(
523 &mut c,
524 (id, client, 11_050_000, 11_051_000, 0, 2_101_000),
525 ClockSampleIgnored::ServerTimeNotNewer,
526 );
527 for tick in [u32::MAX - 1, u32::MAX.wrapping_add(1 << 31)] {
528 ignored(
529 &mut c,
530 (id, client, 12_050_000, 12_051_000, tick, 2_101_000),
531 ClockSampleIgnored::TickNotCurrentOrNewer,
532 );
533 }
534 assert!(c.observe(id, client, 12_050_000, 12_051_000, u32::MAX, 2_101_000));
536 let (id, client) = c.probe(3_000_000).unwrap();
537 assert!(c.observe(id, client, 13_050_000, 13_051_000, 0, 3_101_000));
538 assert_eq!(c.anchor.unwrap().extended, 1 << 32);
539
540 c.anchor.as_mut().unwrap().extended = u64::MAX;
542 let (id, client) = c.probe(4_000_000).unwrap();
543 ignored(
544 &mut c,
545 (id, client, 14_050_000, 14_051_000, 1, 4_101_000),
546 ClockSampleIgnored::TickOverflow,
547 );
548 }
549
550 #[test]
551 fn timestamp_and_nonce_extremes_keep_legacy_domains() {
552 let mut c = ClientClock::default();
553 let (id, sent) = c.probe(MAX_US).unwrap();
554 assert!(c.observe(id, sent, MAX_US, MAX_US, u32::MAX, MAX_US));
555 assert_eq!(c.rtt_seconds(), Some(0.0));
556 assert_eq!(c.diagnostics(MAX_US, 64).offset_seconds, Some(0.0));
557 assert_eq!(c.estimated_tick(MAX_US, 1), Some(f64::from(u32::MAX)));
558 assert_eq!(c.estimated_tick(MAX_US + 1, 64), None);
559 assert_eq!(c.estimated_tick(MAX_US, 0), None);
560 assert_eq!(c.estimated_tick(MAX_US, 1001), None);
561 assert!(c.estimated_tick(MAX_US, 1000).is_some());
562 c.reset();
563 c.next_nonce = u32::MAX - 1;
564 let (last, sent) = c.probe(0).unwrap();
565 assert_eq!(last, u32::MAX);
566 let (zero, _) = c.probe(1).unwrap();
567 assert_eq!(zero, 0);
568 assert!(c.observe(last, sent, 0, 0, 0, 0));
569 assert!(c.observe(zero, 1, 1, 1, 1, 1));
570 }
571
572 #[test]
573 fn estimates_match_existing_sync_jitter_delay_and_elapsed_clamps() {
574 let mut c = ClientClock::default();
575 let mut sync = ClockSync::default();
576 let mut previous_rtt: Option<f64> = None;
577 let mut jitter = 0.0;
578 for (i, duration) in [100_000, 200_000, 4_000_000, 50_000]
579 .into_iter()
580 .enumerate()
581 {
582 let local = 10_000_000 * (i as u64 + 1);
583 let server_receive = local + 10_000_000 + duration / 2;
584 let server_send = server_receive + 1_000;
585 let now = local + duration + 1_000;
586 let (id, sent) = c.probe(local).unwrap();
587 assert!(sync.observe(
588 sent as f64 / 1e6,
589 server_receive as f64 / 1e6,
590 server_send as f64 / 1e6,
591 now as f64 / 1e6
592 ));
593 assert_eq!(
594 c.observe_detailed(id, sent, server_receive, server_send, i as u32, now),
595 Ok(())
596 );
597 let rtt = duration as f64 / 1e6;
598 if let Some(previous) = previous_rtt {
599 jitter += ((rtt - previous).abs().min(0.25) - jitter) * 0.125;
600 }
601 previous_rtt = Some(rtt);
602 assert_eq!(c.rtt_seconds(), Some(sync.rtt_seconds));
603 assert_eq!(
604 c.diagnostics(now, 64).offset_seconds,
605 Some(sync.offset_seconds)
606 );
607 assert!((c.jitter_seconds() - jitter).abs() < 1e-14);
608 for hz in [0, 1, 64, 1000, u16::MAX] {
609 let delay = (6.0 + (jitter * f64::from(hz) * 2.0).ceil()).clamp(6.0, 12.0) as u32;
610 assert_eq!(c.render_delay_ticks(hz), delay);
611 assert_eq!(c.diagnostics(now, hz).render_delay_ticks, delay);
612 }
613 assert_eq!(c.estimated_tick(0, 64), Some(i as f64 - 16.0));
614 assert_eq!(
615 c.estimated_tick(now + 10_000_000, 64),
616 Some(i as f64 + 320.0)
617 );
618 }
619 }
620
621 #[test]
622 fn unwrapper_reset_wrap_half_space_and_overflow_remain_explicit() {
623 let mut u = TickUnwrapper::default();
624 assert_eq!(u.project(0), None);
625 assert_eq!(u.observe(u32::MAX), Some(u64::from(u32::MAX)));
626 assert_eq!(u.observe(0), Some(1 << 32));
627 assert_eq!(u.project(u32::MAX), Some((1 << 32) - 1));
628 let before = u.latest;
629 assert_eq!(u.observe(0), None);
630 assert_eq!(u.observe(1 << 31), None);
631 assert_eq!(u.latest, before);
632 u.latest = Some((0, u64::MAX));
633 assert_eq!(u.observe(1), None);
634 assert_eq!(u.project(1), None);
635 assert_eq!(u.latest, Some((0, u64::MAX)));
636 u.reset();
637 assert_eq!(u.project(u32::MAX), None);
638 assert_eq!(u.observe(0), Some(0));
639 assert_eq!(u.project(u32::MAX), None);
640 }
641
642 #[test]
643 fn probes_are_correlated_reorder_safe_and_wrap_ticks() {
644 let mut c = ClientClock::default();
645 let (id, sent) = c.probe(1_000_000).unwrap();
646 assert!(!c.observe(id, sent + 1, 11_050_000, 11_051_000, u32::MAX, 1_101_000));
647 assert!(c.observe(id, sent, 11_050_000, 11_051_000, u32::MAX, 1_101_000));
648 assert!((c.rtt_seconds().unwrap() - 0.1).abs() < 1e-9);
649 assert!(!c.observe(id, sent, 11_050_000, 11_051_000, u32::MAX, 1_101_000));
650 let (a, at) = c.probe(1_200_000).unwrap();
651 let (b, bt) = c.probe(1_300_000).unwrap();
652 assert!(c.observe(b, bt, 11_350_000, 11_351_000, 18, 1_401_000));
653 assert!(!c.observe(a, at, 11_250_000, 11_251_000, 12, 1_402_000));
654 assert!(c.estimated_tick(1_401_000, 64).unwrap() > u32::MAX as f64);
655 assert!((6..=12).contains(&c.render_delay_ticks(64)));
656 let mut u = TickUnwrapper::default();
657 assert_eq!(u.observe(u32::MAX), Some(u64::from(u32::MAX)));
658 assert_eq!(u.observe(0), Some(1 << 32));
659 assert_eq!(u.project(u32::MAX), Some((1 << 32) - 1));
660 assert_eq!(u.observe(u32::MAX), None);
661 }
662}