diff --git a/quest/m1/README.md b/quest/m1/README.md index 293cb64ec03..effa2069e6f 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -100,7 +100,6 @@ audit's receive-memory, priority, and lease bugs rank ahead of that reshape. - [Stats groups as tracks](/quest/m1/stats-group-tracks.md) - one stable node broadcast per stats producer, with each group a produced track listed by TRACKS - [No reused track names](/quest/m1/name-reuse.md) - no first-party publisher re-creates a finished track under its old name - [Routing guide](/quest/m1/routing-guide.md) - concepts and practical outbound federation setup -- [Controlled time](/quest/m1/time/README.md) - every crate and package reads time through moq-clock or @moq/clock, with regression tests for the changed contracts - [Receive pinning](/quest/m1/quic-receive-pinning.md) - tiny DATAGRAM or STREAM frames cannot pin moq-quic receive batches past the receive budgets - [Priority requeue](/quest/m1/quic-priority-requeue.md) - raising a queued QUIC stream's priority moves it at once instead of after it next sends - [Lease bookkeeping](/quest/m1/quic-lease-bookkeeping.md) - receive leases and the connection window keep exact books, and eviction stops scanning every stream diff --git a/quest/m1/binding-timestamps.md b/quest/m1/binding-timestamps.md index 18b8ced7a81..c3323e887ad 100644 --- a/quest/m1/binding-timestamps.md +++ b/quest/m1/binding-timestamps.md @@ -61,10 +61,9 @@ Decided 2026-10-20 (maintainer): the moq-c half lands on the [generated C package](/quest/m1/c/README.md), not the frozen hand-written ABI, so C users break once. +Wall and monotonic times stay `moq_clock::Wall` and `moq_clock::Instant`, not +media timestamps; keep the types distinct. + ## Required - [Generated C bindings](/quest/m1/c/README.md) - `moq_timestamp` reaches C through the generated package, so C users break once - -## Related - -- [Controlled time](/quest/m1/time/README.md) - wall and monotonic time, not media timestamps; keep the types distinct diff --git a/quest/m1/test-flakes-2/README.md b/quest/m1/test-flakes-2/README.md index 520ecf2fb6b..1d9391c3868 100644 --- a/quest/m1/test-flakes-2/README.md +++ b/quest/m1/test-flakes-2/README.md @@ -21,7 +21,8 @@ Rules every child keeps: slow, fix that. - A paused clock auto-advances while the runtime idles, so it can fire a timer before a real socket delivers. Where real sockets fight the paused - clock, make the timers mockable or move the test off real sockets. + clock, drive the timers with a `moq_clock::Manual` clock or the sim (every + crate's timers run on `moq-clock`), or move the test off real sockets. - A mocked clock still flakes when the code jitters its timers with `rand` (the draft-16 cancel race was a retry sweep jittered past a fixed settle budget). Wait out the jitter's whole window, not a count of small steps. @@ -44,7 +45,3 @@ Public API: none. Wire: none. - [IETF22 fallback](/quest/m1/test-flakes-2/ietf22-fallback.md) - an IETF22 browser viewer follows a fallback within the media lane's bound, keeping its session and its audio - [Interop timestamp gap](/quest/m1/test-flakes-2/interop-timestamp-gap.md) - `rust -> js-native-node` audio has no gap under load - [Go reservation grant](/quest/m1/test-flakes-2/go-reservation-grant.md) - the Go reservation test waits for its grant - -## Related - -- [Controlled time](/quest/m1/time/README.md) - the systemic fix these rules ask for: every crate on a controlled clock diff --git a/quest/m1/time/README.md b/quest/m1/time/README.md deleted file mode 100644 index 596cd881541..00000000000 --- a/quest/m1/time/README.md +++ /dev/null @@ -1,113 +0,0 @@ -# [XS] Controlled time - -## Goal - -Every MoQ crate and package reads time and arms timers only through -`moq-clock` (Rust) or `@moq/clock` (JS), with the production and public API migrations completed in m1. Tests -needed to prove these changes use controlled time. The backend is -the current runtime's (tokio, browser, io_uring, or the simulator), so the -same logic runs on each and a test can swap in simulated time. - -Tests that do real I/O (sockets, browsers, codecs, hardware) follow one rule: -behavioral assertions use controlled time; real-I/O tests synchronize on -events, with wall time allowed only for harness watchdogs and explicit -performance measurements. - -Out of scope here: a runtime trait for spawn and I/O -([Runtime trait](/quest/m2/runtime-trait.md)), QUIC over simulated UDP -([QUIC on the sim](/quest/m2/quic-sim.md)), and seeded randomness -([Seeded sim](/quest/m2/sim-seed.md)). - -## Plan - -Decided 2026-10-10 from an audit of `main` (`355f45864`), with -reasons, so later sessions don't reopen them: - -- **Why.** Flaky tests, and runtime independence: browser wasm has no - `std::time::Instant`, and paused tokio time does not pause - `std::time::Instant`, so a test that mixes them (std `elapsed()` beside a - tokio sleep) advances one clock and not the other. -- **One clock supplies both now and deadlines.** Wrapping `Instant` alone does - not make tests deterministic. -- **A new published crate, `moq-clock`,** extracted from moq-net's private - `Clock`/`Deadline`, not a public `moq_net::time` (mux, downstream apps, and other - crates would depend on moq-net for time) and not web-async (a separate repo, - and the thing the runtime trait replaces). -- **Named `moq-clock`,** with its proc-macro helper `moq-clock-macros` - (decided 2026-10-13 by the maintainer, replacing `moq-time`). The crates.io - name is ours: the "CLOCK over QUIC" demo binary held it until 0.10.21 and - stopped publishing when #1488 and #1494 made it the moq-tokio `clock` - example. The library publishes as 0.11.0, a semver break from the demo. - The JS mirror is `@moq/clock` (same decision), and the private JS CLOCK - demo that held that name is gone. Wall time is `moq_clock::Wall`, so it - never reads as `moq_net::Timestamp` (media time). -- **The instant is logical:** `Instant(u64)` nanoseconds from the clock's - origin, so a test starts at zero with fixed coordinates and never reads the - host clock. Native, wasm, and io_uring instants convert at the backend. - Nanoseconds match `Duration` and QUIC pacing. In JS a plain `number` of - nanoseconds is exact for 104 days of uptime and only loses sub-microsecond - precision after. The browser backend must preserve clock origin and units - across Rust and JS; a source translator's `Instant` mapping is chosen with - that backend, while WASM retains Rust time types. Its methods mirror - `std::time::Instant`'s, so swapping one for the other is an import change. -- **Wall time is a separate type from the same clock.** The manual clock's - `advance()` moves both; `step_wall()` moves only wall time, so a test can - prove a clock correction never manufactures elapsed (billable) time. -- **Runtime-ambient access.** State machines keep taking `now` (moq-net's - `Driver::poll(now, waiter)`). Async glue - calls `moq_clock::now()`, `sleep()`, `timeout()`, and `interval()`, which - resolve to the current runtime's clock: one clock per runtime, nothing to - plumb, no process-global test override. The ambient functions stay behind - moq-net's `async` feature, so the sans-IO core keeps explicit instants. -- **The simulator folds into `moq-clock`** behind a `sim` feature (a - dev-dependency only, so production builds never compile it). It is one - backend of the ambient clock, starts at zero, keeps deadlock detection, and - seeds the later runtime trait. `#[moq_clock::test]` runs tests on this - backend. -- **Tests for migrated contracts use the sim wherever possible.** A test with no real I/O - that cannot run on the sim yet uses paused tokio, whose clock `moq-clock` - reads. A real-I/O test never uses paused tokio, which auto-advances to the - next timer while the OS event is still in flight; it syncs on events, with - wall time only for its watchdog. -- **Landing.** Everything lands on `main`, the trunk. The crate and the JS - package land first and additively; the migrations that change a published - type (moq-net's `time::Instant`, moq-mux's `Clock`, `@moq/net`'s time - units) follow as breaking changes. No backport: `release` is touched only - to cut a release or backport a critical fix, so pinned consumers adopt - `moq-clock` from the next cut (decided 2026-10-10 from review, replacing an - earlier backport plan). -- **Lint ratchet.** Each migration quest bans direct clock reads and timers in - the crates and packages it finishes: clippy `disallowed-methods` and - `disallowed-types` in a per-crate `clippy.toml`, and a biome - `noRestrictedGlobals` override, allowing only the backend modules. The - workspace-wide test and lint sweep follows in m2. -- **Third-party std clocks.** A third-party API that takes - `std::time::Instant` (str0m, srt-tokio, winit, qlog) converts with - `Instant::into_std` and `Instant::from_std`, native only, through the runtime - clock's origin: exact on a running clock, durations only on paused tokio or - the simulator. Device threads outside any runtime keep `std::thread::sleep` - under a per-site `#[allow]`, since they have no ambient clock to wait on - (decided 2026-10-20 by the maintainer, in - [#6135](https://github.com/moq-dev/moq/pull/6135)). -- **Consolidation.** perf/3122 (one clock read per io_uring turn) landed with - moq-uring on moq-clock in [#5926](https://github.com/moq-dev/moq/pull/5926). The relay seam - [bench-relay](/quest/m2/bench-relay.md) needed is `moq_relay::Accepted`: - a `moq_relay::Connection` over any moq-net transport, such as the in-memory - one. Its tests run on paused tokio until - [the runtime trait](/quest/m2/runtime-trait.md) can spawn on the sim. Quests that already asked - for "mocked time" Require the core quest. moq-quic takes the logical - instant at its boundary. - -This milestone verifies the exported clock contract and production consumers -needed by the in-tree QUIC stack and clustering regressions. Unrelated test/private -cleanup and the global lint ratchet belong to -[the follow-up sweep](/quest/m2/time-test-sweep.md). - -Remaining: every child has landed, with public wall times on `moq_clock::Wall` -in [#6298](https://github.com/moq-dev/moq/pull/6298). Move the decisions the -m2 quests still cite into them, then retire this epic. - -## Related - -- [More tests under load](/quest/m1/test-flakes-2/README.md) - the per-flake fixes this line makes systemic -- [Rust-backed @moq/net](/quest/m2/rs2ts/README.md) - Rust and JS clocks must agree across either browser backend diff --git a/quest/m2/rs2ts/README.md b/quest/m2/rs2ts/README.md index 6b5383a7c53..4ae9502b11e 100644 --- a/quest/m2/rs2ts/README.md +++ b/quest/m2/rs2ts/README.md @@ -41,8 +41,12 @@ This supersedes the earlier generated-TypeScript-only decision, the absolute no-regression gate, and the codec/model/session translation sequence. Keep Rust async, kio, integer representations, and storage unless evidence calls for a source change. A batched boundary is an optimization candidate, not a -reason to require a full sans-IO rewrite. Controlled time remains independently -useful; source-level `Instant` mappings depend on the chosen backend. +reason to require a full sans-IO rewrite. + +The Rust and JS clocks (`moq-clock` and `@moq/clock`) must agree on origin and +units under either backend. WASM keeps Rust's time types; a source translator +chooses its `Instant` mapping with its backend. A JS `number` of nanoseconds is +exact for 104 days of uptime and only loses sub-microsecond precision after. Decided with the maintainer on 2026-10-17 ([#5838](https://github.com/moq-dev/moq/pull/5838)): the WASM binding is moq-ffi @@ -79,4 +83,3 @@ any necessary breaks. Wire: no changes intended. - [JS-only @moq/net](/quest/m2/rs2ts-js.md) - the eventual distribution uses no WASM runtime - [rust2's TS translator](https://github.com/kixelated/rust2/blob/main/quest/m2/ts.md) - a parallel research track translating moq-net's codec through an own rustc driver - [Browser media report](/quest/m2/rs2ts-browser-report.md) - broader media measurements after adoption -- [Controlled time](/quest/m1/time/README.md) - coherent Rust and JS clocks regardless of backend diff --git a/quest/m2/runtime-trait.md b/quest/m2/runtime-trait.md index 428bbca28f1..67ab4ccd0f8 100644 --- a/quest/m2/runtime-trait.md +++ b/quest/m2/runtime-trait.md @@ -13,12 +13,7 @@ the sim: today `Cluster::new` and the auth decider `tokio::spawn`. ## Plan -Decided 2026-10-10: deferred until [controlled time](/quest/m1/time/README.md) -lands; time came first because it is what tests need. Decide in a planning +Time landed first, as `moq-clock`, because it is what tests need. Decide in a planning pass whether I/O seams belong in the trait, given moq-quic's sans-IO core and moq-sock already split I/O by runtime. The sim in `moq-clock` is its first non-tokio implementation. - -## Required - -- [Controlled time](/quest/m1/time/README.md) - the time half this builds on diff --git a/quest/m2/sim-seed.md b/quest/m2/sim-seed.md index 12a09939ccd..a6e02cee0c2 100644 --- a/quest/m2/sim-seed.md +++ b/quest/m2/sim-seed.md @@ -9,6 +9,5 @@ replays bit-exact. ## Plan -Decided 2026-10-10: out of [controlled time](/quest/m1/time/README.md); with -controlled time a test advances past the largest jitter, so seeding only adds -exact replay. Production keeps its OS randomness. +Decided 2026-10-10: with controlled time a test advances past the largest +jitter, so seeding only adds exact replay. Production keeps its OS randomness. diff --git a/quest/m2/time-test-sweep.md b/quest/m2/time-test-sweep.md index 4d2513b95ce..6ada071d840 100644 --- a/quest/m2/time-test-sweep.md +++ b/quest/m2/time-test-sweep.md @@ -7,11 +7,27 @@ workspace lint prevents new direct reads outside backends and measurements. ## Plan -The production and exported API migrations stay in m1. This follow-up owns -unrelated legacy test conversions, the workspace-wide lint ratchet, and the -final audit of harness exceptions. Real I/O synchronizes on events; only -watchdogs and performance measurements use wall time. +Production code and exported APIs already read time through `moq-clock` and +`@moq/clock`. This follow-up owns the legacy test conversions, the +workspace-wide lint ratchet, and the final audit of harness exceptions. -## Required +Decided with the m1 migrations, so this sweep doesn't reopen them: -- [Controlled time](/quest/m1/time/README.md) - the clocks and production migrations +- **Sim first.** A test with no real I/O runs on the `moq-clock` sim + (`#[moq_clock::test]`). One that cannot run there yet uses paused tokio, + whose clock `moq-clock` reads. +- **Real I/O syncs on events.** A test with sockets, browsers, codecs, or + hardware never uses paused tokio, which auto-advances to the next timer while + the OS event is still in flight. Wall time is allowed only for its watchdog + and explicit performance measurements. +- **The ratchet.** Today each crate's `clippy.toml` bans direct clock reads and + timers (`disallowed-methods`, `disallowed-types`), and tests opt out with + `expect(clippy::disallowed_methods)`; the biome `noRestrictedGlobals` + override skips `*.test.ts`. The sweep removes those opt-outs as it converts, + leaving only the backend modules. +- **Third-party std clocks.** An API that takes `std::time::Instant` (str0m, + srt-tokio, winit, qlog) converts with `Instant::into_std` and + `Instant::from_std`. Device threads outside any runtime keep + `std::thread::sleep` under a per-site `#[allow]`, since they have no ambient + clock (decided 2026-10-20 by the maintainer, in + [#6135](https://github.com/moq-dev/moq/pull/6135)). diff --git a/rs/qmux/clippy.toml b/rs/qmux/clippy.toml new file mode 100644 index 00000000000..43c935eacb3 --- /dev/null +++ b/rs/qmux/clippy.toml @@ -0,0 +1,22 @@ +disallowed-methods = [ + { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, + { path = "std::time::Instant", reason = "use moq_clock::Instant" }, + { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, + { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/qmux/examples/common/mod.rs b/rs/qmux/examples/common/mod.rs index d3ff1828f5b..f667d7a51af 100644 --- a/rs/qmux/examples/common/mod.rs +++ b/rs/qmux/examples/common/mod.rs @@ -32,7 +32,7 @@ pub fn payload(seed: usize) -> Vec { /// Write all of `data` then the FIN, bounded by [`TIMEOUT`]. pub async fn send_all(send: &mut SendStream, data: &[u8], what: &str) -> anyhow::Result<()> { let mut data = Bytes::copy_from_slice(data); - tokio::time::timeout(TIMEOUT, async { + moq_clock::timeout(TIMEOUT, async { while !data.is_empty() { send.write_buf(&mut data).await?; } @@ -47,7 +47,7 @@ pub async fn send_all(send: &mut SendStream, data: &[u8], what: &str) -> anyhow: /// Read until the FIN, bounded by [`TIMEOUT`]. pub async fn recv_all(recv: &mut RecvStream, what: &str) -> anyhow::Result { let mut buf = BytesMut::new(); - tokio::time::timeout(TIMEOUT, async { + moq_clock::timeout(TIMEOUT, async { while let Some(chunk) = recv.read_chunk(usize::MAX).await? { buf.extend_from_slice(&chunk); } diff --git a/rs/qmux/examples/interop-client.rs b/rs/qmux/examples/interop-client.rs index 7b46a8af452..80dd33e8dd4 100644 --- a/rs/qmux/examples/interop-client.rs +++ b/rs/qmux/examples/interop-client.rs @@ -19,7 +19,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { } // Rust -> TypeScript. - let mut send = tokio::time::timeout(TIMEOUT, session.open_uni(SendOptions::default())) + let mut send = moq_clock::timeout(TIMEOUT, session.open_uni(SendOptions::default())) .await .context("timed out opening the client unidirectional stream")??; send_all(&mut send, &payload(CLIENT_SEED), "the client flow-control payload").await?; @@ -27,7 +27,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { // TypeScript -> Rust. Server-initiated streams are the ids only a // `Session::accept` session may mint; a client-role server would be rejected // here rather than accepted. - let mut recv = tokio::time::timeout(TIMEOUT, session.accept_uni()) + let mut recv = moq_clock::timeout(TIMEOUT, session.accept_uni()) .await .context("timed out accepting the server unidirectional stream")??; let received = recv_all(&mut recv, "the server flow-control payload").await?; @@ -36,7 +36,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { } // Exercise both halves of one bidirectional stream and FIN propagation. - let (mut send, mut recv) = tokio::time::timeout(TIMEOUT, session.open_bi(SendOptions::default())) + let (mut send, mut recv) = moq_clock::timeout(TIMEOUT, session.open_bi(SendOptions::default())) .await .context("timed out opening the bidirectional stream")??; let request = format!("ping:{}", version.alpn()); @@ -49,7 +49,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { // DATAGRAM is available only on record-framed drafts (QMux01+). if version.uses_records() { session.send_datagram(Bytes::from_static(b"rust-datagram"), SendOptions::default())?; - let datagram = tokio::time::timeout(TIMEOUT, session.recv_datagram()) + let datagram = moq_clock::timeout(TIMEOUT, session.recv_datagram()) .await .context("timed out receiving the TypeScript datagram")??; if datagram.as_ref() != b"typescript-datagram" { @@ -59,7 +59,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { bail!("QMux00 unexpectedly negotiated datagram support"); } - let closed = tokio::time::timeout(TIMEOUT, session.closed()) + let closed = moq_clock::timeout(TIMEOUT, session.closed()) .await .context("timed out waiting for the TypeScript server to close")?; match closed { diff --git a/rs/qmux/examples/interop-server.rs b/rs/qmux/examples/interop-server.rs index 2bff5aed8fb..f1720444d78 100644 --- a/rs/qmux/examples/interop-server.rs +++ b/rs/qmux/examples/interop-server.rs @@ -22,7 +22,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { } // TypeScript -> Rust, with the default Rust windows. - let mut recv = tokio::time::timeout(TIMEOUT, session.accept_uni()) + let mut recv = moq_clock::timeout(TIMEOUT, session.accept_uni()) .await .context("timed out accepting the client unidirectional stream")??; let received = recv_all(&mut recv, "the client flow-control payload").await?; @@ -32,13 +32,13 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { // Rust -> TypeScript. The client advertises deliberately small receive // windows, so this cannot finish unless it consumes and replenishes credit. - let mut send = tokio::time::timeout(TIMEOUT, session.open_uni(SendOptions::default())) + let mut send = moq_clock::timeout(TIMEOUT, session.open_uni(SendOptions::default())) .await .context("timed out opening the server unidirectional stream")??; send_all(&mut send, &payload(SERVER_SEED), "the server flow-control payload").await?; // Exercise both halves of one bidirectional stream and FIN propagation. - let (mut send, mut recv) = tokio::time::timeout(TIMEOUT, session.accept_bi()) + let (mut send, mut recv) = moq_clock::timeout(TIMEOUT, session.accept_bi()) .await .context("timed out accepting the bidirectional stream")??; let request = recv_all(&mut recv, "the bidirectional request").await?; @@ -51,7 +51,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { // DATAGRAM is available only on record-framed drafts (QMux01+). if version.uses_records() { session.send_datagram(Bytes::from_static(b"rust-datagram"), SendOptions::default())?; - let datagram = tokio::time::timeout(TIMEOUT, session.recv_datagram()) + let datagram = moq_clock::timeout(TIMEOUT, session.recv_datagram()) .await .context("timed out receiving the TypeScript datagram")??; if datagram.as_ref() != b"typescript-datagram" { @@ -61,7 +61,7 @@ async fn run(mut session: Session, version: Version) -> anyhow::Result<()> { bail!("QMux00 unexpectedly negotiated datagram support"); } - let closed = tokio::time::timeout(TIMEOUT, session.closed()) + let closed = moq_clock::timeout(TIMEOUT, session.closed()) .await .context("timed out waiting for the TypeScript client to close")?; match closed { diff --git a/rs/qmux/src/session/tests.rs b/rs/qmux/src/session/tests.rs index 2b1450920fa..dc84064d624 100644 --- a/rs/qmux/src/session/tests.rs +++ b/rs/qmux/src/session/tests.rs @@ -193,7 +193,7 @@ async fn resets_and_stops_carry_their_codes() { write_all(&mut send, Bytes::from_static(b"refused")).await; let mut recv = server.accept_uni().await.unwrap(); recv.stop(11); - tokio::time::sleep(Duration::from_millis(1)).await; + moq_clock::sleep(Duration::from_millis(1)).await; assert!(matches!(send.finish(), Err(Error::StreamStop(11)))); assert!(matches!(send.closed().await, Err(Error::StreamStop(11)))); } @@ -253,7 +253,7 @@ async fn request_credit_is_refused_without_parking_an_open() { /// Poll `future` once, after letting every other task run. async fn futures_poll_once(future: &mut F) -> Option { - tokio::time::sleep(Duration::from_millis(10)).await; + moq_clock::sleep(Duration::from_millis(10)).await; std::future::poll_fn(|cx| { Poll::Ready(match Pin::new(&mut *future).poll(cx) { Poll::Ready(output) => Some(output), @@ -322,7 +322,7 @@ async fn websocket_keep_alive_runs_during_continuous_output() { if b_write.write_all(&buf[..n]).await.is_err() { return; } - tokio::time::sleep(Duration::from_millis(1)).await; + moq_clock::sleep(Duration::from_millis(1)).await; } }); tokio::spawn(async move { tokio::io::copy(&mut b_read, &mut a_write).await }); @@ -340,7 +340,7 @@ async fn websocket_keep_alive_runs_during_continuous_output() { let mut sender = Session::new(a, Side::Client, config.clone()).unwrap(); let _receiver = Session::new(b, Side::Server, config).unwrap(); while sender.max_datagram_size() == 0 { - tokio::time::sleep(Duration::from_millis(1)).await; + moq_clock::sleep(Duration::from_millis(1)).await; } // Far past the 500ms deadline, queueing more each tick than one batch carries @@ -420,10 +420,10 @@ async fn a_close_behind_a_stalled_peer_is_bounded() { up.send(Flow::Stall).unwrap(); // Fill the pipe so the writer is mid-write when the close comes. let mut send = client.open_uni(SendOptions::default()).await.unwrap(); - let _ = tokio::time::timeout(Duration::from_millis(100), send.write(&payload(1 << 20, 0))).await; - tokio::time::sleep(Duration::from_millis(100)).await; + let _ = moq_clock::timeout(Duration::from_millis(100), send.write(&payload(1 << 20, 0))).await; + moq_clock::sleep(Duration::from_millis(100)).await; - let start = tokio::time::Instant::now(); + let start = moq_clock::now(); client.close(5, "stalled"); let err = client.closed().await; assert!(matches!(err, Error::ConnectionClosed { code: 5, .. }), "got {err:?}"); @@ -441,7 +441,7 @@ async fn a_silent_peer_times_out() { up.send(Flow::Drop).unwrap(); down.send(Flow::Drop).unwrap(); - let start = tokio::time::Instant::now(); + let start = moq_clock::now(); assert!(matches!(client.closed().await, Error::IdleTimeout)); assert!(matches!(server.closed().await, Error::IdleTimeout)); assert!(start.elapsed() >= Duration::from_secs(30) - Duration::from_secs(1)); @@ -451,7 +451,7 @@ async fn a_silent_peer_times_out() { #[tokio::test(start_paused = true)] async fn an_idle_session_stays_up() { let (mut client, _server) = pair(config(Version::QMux01), config(Version::QMux01)).await; - let closed = tokio::time::timeout(Duration::from_secs(120), client.closed()).await; + let closed = moq_clock::timeout(Duration::from_secs(120), client.closed()).await; assert!(closed.is_err(), "closed with {closed:?}"); } @@ -459,7 +459,7 @@ async fn an_idle_session_stays_up() { async fn a_peer_that_never_sends_parameters_times_out_the_handshake() { let (client, _silent) = tokio::io::duplex(PIPE); let config = config(Version::QMux02); - let start = tokio::time::Instant::now(); + let start = moq_clock::now(); let err = Session::connect(Stream::new(client), config).await.unwrap_err(); assert!(matches!(err, Error::HandshakeTimeout), "got {err:?}"); assert!(start.elapsed() >= Duration::from_secs(10)); diff --git a/rs/qmux/src/transport.rs b/rs/qmux/src/transport.rs index 7d3c4b4b858..bbbac1d7998 100644 --- a/rs/qmux/src/transport.rs +++ b/rs/qmux/src/transport.rs @@ -818,14 +818,13 @@ pub(crate) use stream_session::build as build_stream_session; // WsTransport: message I/O over WebSocket. #[cfg(feature = "ws")] mod ws_transport { - use std::pin::Pin; use std::time::Duration; use bytes::Bytes; use futures::stream::SplitSink; + use moq_clock::{Interval, MissedTickBehavior, Sleep}; use tokio::sync::mpsc; use tokio::task::JoinHandle; - use tokio::time::{Instant, Interval, MissedTickBehavior, Sleep}; use tokio_tungstenite::tungstenite; use super::{Reader, Transport, Writer}; @@ -902,11 +901,10 @@ mod ws_transport { impl PingState { fn new(config: KeepAlive) -> Self { + // The first tick is one interval out, so we don't ping on connect. + let mut interval = moq_clock::interval_at(moq_clock::now() + config.interval, config.interval); // Skip catch-up bursts after a long pause; we just want one Ping per tick. - let mut interval = tokio::time::interval(config.interval); interval.set_missed_tick_behavior(MissedTickBehavior::Delay); - // First tick fires immediately by default; consume it so we don't ping on connect. - interval.reset(); Self { interval } } } @@ -914,7 +912,7 @@ mod ws_transport { /// Reader-side keep-alive: close the session if no frame arrives within `timeout`. struct DeadlineState { // Resets every time we receive a frame. If it elapses, the peer is gone. - deadline: Pin>, + deadline: Sleep, timeout: Duration, } @@ -922,13 +920,13 @@ mod ws_transport { fn new(config: KeepAlive) -> Self { let timeout = config.timeout; Self { - deadline: Box::pin(tokio::time::sleep(timeout)), + deadline: moq_clock::sleep(timeout), timeout, } } fn observe_recv(&mut self) { - self.deadline.as_mut().reset(Instant::now() + self.timeout); + self.deadline.reset(moq_clock::now() + self.timeout); } } @@ -1078,7 +1076,7 @@ mod ws_transport { Some(d) => tokio::select! { biased; msg = stream.next() => msg, - _ = d.deadline.as_mut() => { + _ = &mut d.deadline => { tracing::debug!("websocket keep_alive timeout"); let _ = tx.send(Err(Error::Closed)).await; return; @@ -1199,7 +1197,7 @@ mod ws_transport { // Model a session wedged on a full accept channel: don't read for well // over the 50ms keep-alive timeout while the pump is parked on delivery. - tokio::time::sleep(Duration::from_millis(150)).await; + moq_clock::sleep(Duration::from_millis(150)).await; assert_eq!( rx.recv().await.expect("channel open").expect("no timeout"), @@ -1225,7 +1223,7 @@ mod ws_transport { let (tx, mut rx) = mpsc::channel(4); let pump = tokio::spawn(ws_pump(stream, Some(DeadlineState::new(ka)), usize::MAX, tx)); - let result = tokio::time::timeout(Duration::from_secs(1), rx.recv()) + let result = moq_clock::timeout(Duration::from_secs(1), rx.recv()) .await .expect("keep-alive deadline should fire on a silent peer"); assert!( @@ -1247,7 +1245,7 @@ mod ws_transport { let pump = tokio::spawn(ws_pump(stream, None, usize::MAX, tx)); // No deadline, so recv stays pending well past any keep-alive window. - let pending = tokio::time::timeout(Duration::from_millis(100), rx.recv()).await; + let pending = moq_clock::timeout(Duration::from_millis(100), rx.recv()).await; assert!(pending.is_err(), "recv must not resolve without activity"); pump.abort(); diff --git a/rs/qmux/src/ws.rs b/rs/qmux/src/ws.rs index b880b8b358f..22549c2d9ea 100644 --- a/rs/qmux/src/ws.rs +++ b/rs/qmux/src/ws.rs @@ -522,7 +522,7 @@ mod tests { frame.extend_from_slice(&[0; 4]); client.write_all(&frame).await.unwrap(); - tokio::time::timeout(Duration::from_secs(1), session.closed()) + moq_clock::timeout(Duration::from_secs(1), session.closed()) .await .expect("the socket waited to buffer a frame larger than a record"); }