Skip to main content

moq_net/
time.rs

1//! Caller-supplied time for protocol and model drivers.
2//!
3//! Drivers take the current [`Instant`] on every poll and never read a clock.
4
5pub use kio::clock::Instant;
6pub(crate) use kio::clock::{Deadline, Deadlines};
7
8/// MoQ's epoch, 2020-01-01T00:00:00Z: wall times on the wire count from it.
9///
10/// Counting from 50 years after the Unix epoch keeps a millisecond count about 1.5e12
11/// smaller, trimming a byte or two off its varint.
12pub const EPOCH: kio::clock::Wall = kio::clock::Wall::from_unix_secs(1_577_836_800);
13
14use crate::Error;
15
16/// A state machine polled with caller-supplied time.
17///
18/// Each poll advances the driver to `now`, processes ready work, and registers
19/// `waiter` for external activity. `Ok(Some(at))` asks to be polled again by
20/// `at` (or sooner, on a wake); `Ok(None)` means only external activity can
21/// make progress. `Err` is terminal: the driver has finished and must not be
22/// polled again. A clean finish is [`Error::Closed`].
23pub trait Driver {
24	/// Advance to `now` and process ready work.
25	fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Result<Option<Instant>, Error>;
26}
27
28/// Run a driver to completion on the ambient runtime, sleeping until each deadline.
29#[cfg(feature = "async")]
30pub fn run<D: Driver>(driver: D) -> impl Future<Output = Error> {
31	let mut driver = Box::new(driver);
32	kio::clock::drive(move |now, waiter| driver.poll(now, waiter))
33}
34
35/// A deadline queue attached to the deterministic test clock.
36#[cfg(all(test, feature = "async"))]
37pub(crate) fn sim() -> Deadlines {
38	let deadlines = Deadlines::new(kio::clock::now());
39	kio::clock::sim::attach(&deadlines);
40	deadlines
41}