diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index df907c54492..da023d2d95b 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -239,7 +239,6 @@ jobs: - "rs/moq-archive/**" - "rs/moq-auth/**" - "rs/moq-cli/**" - - "rs/moq-clock/**" - "rs/moq-congestion/**" - "rs/moq-hls/**" - "rs/moq-ice/**" diff --git a/.oss-scanner/Dockerfile b/.oss-scanner/Dockerfile index 338e2689749..99ffd13a511 100644 --- a/.oss-scanner/Dockerfile +++ b/.oss-scanner/Dockerfile @@ -20,7 +20,7 @@ RUN rustup show active-toolchain || rustup toolchain install \ && curl -LsSf "https://get.nexte.st/latest/$nextest" | tar zxf - -C "$CARGO_HOME/bin" \ && cargo nextest --version -ARG CRATES="kio hang moq-auth moq-clock moq-e2ee moq-hls moq-ice moq-json moq-loc moq-msf moq-mux moq-net moq-pattern moq-quic moq-relay moq-rtc moq-rtmp moq-rtsp moq-sock moq-srt moq-stats moq-tokio moq-uring moq-cli" +ARG CRATES="kio hang moq-auth moq-e2ee moq-hls moq-ice moq-json moq-loc moq-msf moq-mux moq-net moq-pattern moq-quic moq-relay moq-rtc moq-rtmp moq-rtsp moq-sock moq-srt moq-stats moq-tokio moq-uring moq-cli" # Path specs, because the lockfile also has published copies of some workspace crates. # io-uring compiles the relay's io_uring QUIC workers (`--runtime-io-uring`), which the default features leave out. diff --git a/.oss-scanner/threat_model.md b/.oss-scanner/threat_model.md index 1c27212a03a..3e5c46bcceb 100644 --- a/.oss-scanner/threat_model.md +++ b/.oss-scanner/threat_model.md @@ -35,7 +35,7 @@ Most important, in this order: 2. Authorization: a session publishing, subscribing, or seeing announcements outside its grant, or reaching another root (tenant) through path tricks, revalidation, mounts, or cluster links. 3. `rs/moq-mux` and `rs/hang`: container, codec, and catalog parsing of publisher-controlled bytes. 4. The ingest gateways: `rs/moq-rtmp`, `rs/moq-rtsp`, `rs/moq-srt`, `rs/moq-rtc`, `rs/moq-ice`, `rs/moq-hls`. -5. `rs/moq-e2ee`, `rs/moq-cli`, `rs/moq-json`, `rs/moq-stats`, `rs/kio`, `rs/moq-clock`. +5. `rs/moq-e2ee`, `rs/moq-cli`, `rs/moq-json`, `rs/moq-stats`, `rs/kio`. `unsafe` is rare and worth reading closely where it appears: `rs/moq-quic`, `rs/moq-net/src/model`, `rs/moq-net/src/util/cell.rs`, `rs/moq-net/src/transport.rs`, and `rs/moq-relay/src/uring.rs`. @@ -45,7 +45,7 @@ Out of scope: `js/` and the other language bindings (`py/`, `swift/`, `kt/`, `go The image is offline, with every crate fetched and `CARGO_NET_OFFLINE` set. The debug build of the in-scope crates, their test binaries, and the `moq-relay` and `moq` binaries are already built in `/src/target/debug`. Debug builds keep overflow checks on. -- **Tests**: `cargo nextest run -p path+file:///src/rs/moq-net` (or any in-scope crate; the path spec is needed because the lockfile also has published copies of some crates). Use nextest as CI does: some tests install process-global state and fail under plain `cargo test`. Add `--features moq-relay/io-uring` for the relay and `moq-uring` so the io\_uring backend's tests run (they skip on a kernel without io\_uring support). Unit tests use the deterministic clock in `moq-clock` rather than wall time, so they are fast and reproducible. +- **Tests**: `cargo nextest run -p path+file:///src/rs/moq-net` (or any in-scope crate; the path spec is needed because the lockfile also has published copies of some crates). Use nextest as CI does: some tests install process-global state and fail under plain `cargo test`. Add `--features moq-relay/io-uring` for the relay and `moq-uring` so the io\_uring backend's tests run (they skip on a kernel without io\_uring support). Unit tests use the deterministic clock in `kio::clock` rather than wall time, so they are fast and reproducible. - **A relay to attack**: `./target/debug/moq-relay demo/relay/localhost.toml` listens on UDP and TCP `[::]:4443` with a self-signed certificate and anonymous access to every path. The binary is built with io\_uring support; pass `--runtime-io-uring` to serve QUIC from the io\_uring workers in `rs/moq-uring` and `rs/moq-relay/src/uring.rs` instead of tokio. For authorization testing, grant a narrow anonymous pattern with `[auth] public_subscribe` / `public_publish`, or run the reference auth server (`moq auth generate`, `moq auth sign`, `moq auth serve`, then `[auth] url`; see `doc/bin/cli.md`) and try to escape a signed token's root and patterns. `doc/bin/relay/` documents the config, auth, cluster, and HTTP endpoints. - **A client**: `./target/debug/moq --help` publishes, subscribes, fetches, and lists announcements against a relay. `curl http://localhost:4443/announced/` and `curl http://localhost:4443/fetch//` hit the HTTP endpoints. - **Fuzz harnesses**: `rs/moq-net/fuzz` and `rs/moq-quic/fuzz` hold cargo-fuzz targets for the wire codecs and the QUIC state machine. cargo-fuzz and a nightly toolchain are not in the image, but the targets show the parser entry points. diff --git a/Cargo.lock b/Cargo.lock index fc99949eb79..ff563cafe19 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3662,7 +3662,6 @@ dependencies = [ "derive_more 2.1.1", "hex", "kio 0.6.2", - "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4789,7 +4788,11 @@ dependencies = [ "bench-harness", "crossbeam-epoch", "futures", + "kio 0.6.2", "kio-macros", + "serde", + "serde_json", + "serde_with", "smallvec", "tokio", ] @@ -5325,7 +5328,6 @@ dependencies = [ "bytes", "futures", "kio 0.6.2", - "moq-clock", "moq-net", "object_store", "percent-encoding", @@ -5351,7 +5353,6 @@ dependencies = [ "dispatch2", "hang", "kio 0.6.2", - "moq-clock", "moq-mux", "moq-net", "objc2 0.6.5", @@ -5387,7 +5388,6 @@ dependencies = [ "kio 0.6.2", "moq-auth 0.2.1", "moq-auth 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "moq-clock", "moq-pattern 0.1.2", "moq-token", "p256", @@ -5436,7 +5436,7 @@ version = "0.0.1" dependencies = [ "anyhow", "humantime", - "moq-clock", + "kio 0.6.2", "moq-net", "moq-tokio", "moq-uring", @@ -5459,8 +5459,8 @@ dependencies = [ "boytacean", "bytes", "hang", + "kio 0.6.2", "moq-audio", - "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -5482,7 +5482,6 @@ dependencies = [ "hang", "kio 0.6.2", "moq-audio", - "moq-clock", "moq-json", "moq-loc", "moq-mux", @@ -5525,11 +5524,11 @@ dependencies = [ "futures", "hang", "humantime", + "kio 0.6.2", "libc", "moq-archive", "moq-audio", "moq-auth 0.2.1", - "moq-clock", "moq-hls", "moq-json", "moq-mux", @@ -5563,30 +5562,12 @@ dependencies = [ "winit", ] -[[package]] -name = "moq-clock" -version = "0.11.0" -dependencies = [ - "futures", - "kio 0.6.2", - "moq-clock", - "moq-clock-macros", - "serde", - "serde_json", - "serde_with", - "tokio", -] - -[[package]] -name = "moq-clock-macros" -version = "0.1.0" - [[package]] name = "moq-congestion" version = "0.1.0" dependencies = [ "cpu-time", - "moq-clock", + "kio 0.6.2", "rand 0.10.3", "rand_pcg", "stats_alloc", @@ -5601,7 +5582,6 @@ dependencies = [ "bytes", "hex", "kio 0.6.2", - "moq-clock", "moq-net", "rind", "serde_json", @@ -5619,7 +5599,6 @@ dependencies = [ "kio 0.6.2", "libc", "moq-audio", - "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -5647,8 +5626,8 @@ dependencies = [ "gstreamer", "gstreamer-audio", "hang", + "kio 0.6.2", "moq-audio", - "moq-clock", "moq-mux", "moq-net", "moq-tokio", @@ -5672,7 +5651,6 @@ dependencies = [ "kio 0.6.2", "m3u8-rs", "moq-archive", - "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -5695,7 +5673,7 @@ dependencies = [ name = "moq-ice" version = "0.1.0" dependencies = [ - "moq-clock", + "kio 0.6.2", "str0m", "stun-types", "thiserror 2.0.21", @@ -5756,7 +5734,6 @@ dependencies = [ "kio 0.6.2", "libc", "memchr", - "moq-clock", "moq-json", "moq-loc", "moq-msf", @@ -5797,7 +5774,6 @@ dependencies = [ "hashlink", "kio 0.6.2", "libc", - "moq-clock", "moq-pattern 0.1.2", "num_enum", "proptest", @@ -5827,7 +5803,7 @@ name = "moq-net-tests" version = "0.0.0" dependencies = [ "futures", - "moq-clock", + "kio 0.6.2", "moq-json", "moq-net", "serde_json", @@ -5877,7 +5853,6 @@ dependencies = [ "indexmap 2.14.2", "kio 0.6.2", "lru-slab", - "moq-clock", "moq-congestion", "moq-quic", "proptest", @@ -5925,7 +5900,6 @@ dependencies = [ "kio 0.6.2", "libc", "moq-auth 0.2.1", - "moq-clock", "moq-congestion", "moq-net", "moq-quic", @@ -5970,7 +5944,6 @@ version = "0.2.11" dependencies = [ "kio 0.6.2", "moq-auth 0.2.1", - "moq-clock", "moq-json", "moq-net", "moq-tokio", @@ -5986,7 +5959,7 @@ dependencies = [ "axum", "bytes", "hang", - "moq-clock", + "kio 0.6.2", "moq-ice", "moq-mux", "moq-net", @@ -6012,7 +5985,7 @@ dependencies = [ "futures", "hang", "hmac 0.13.0", - "moq-clock", + "kio 0.6.2", "moq-mux", "moq-net", "moq-tokio", @@ -6034,7 +6007,7 @@ dependencies = [ "base64 0.23.1", "futures", "hang", - "moq-clock", + "kio 0.6.2", "moq-mux", "moq-net", "moq-tokio", @@ -6057,7 +6030,6 @@ dependencies = [ "image", "kio 0.6.2", "moq-audio", - "moq-clock", "moq-mux", "moq-net", "moq-video", @@ -6078,7 +6050,7 @@ dependencies = [ "clap", "humantime", "humantime-serde", - "moq-clock", + "kio 0.6.2", "rand 0.10.3", "serde", "serde_json", @@ -6127,7 +6099,7 @@ dependencies = [ "bytes", "futures", "hang", - "moq-clock", + "kio 0.6.2", "moq-mux", "moq-net", "srt-protocol", @@ -6144,7 +6116,7 @@ version = "0.2.12" dependencies = [ "bench-harness", "futures", - "moq-clock", + "kio 0.6.2", "moq-json", "moq-net", "serde", @@ -6164,8 +6136,8 @@ dependencies = [ "eframe", "egui", "egui_dock", + "kio 0.6.2", "moq-audio", - "moq-clock", "moq-mux", "moq-net", "moq-relay", @@ -6218,7 +6190,6 @@ dependencies = [ "kio 0.6.2", "libc", "mdns-sd", - "moq-clock", "moq-congestion", "moq-ice", "moq-net", @@ -6273,7 +6244,6 @@ dependencies = [ "bytes", "hang", "kio 0.6.2", - "moq-clock", "moq-mux", "moq-net", "moq-tokio", @@ -6296,7 +6266,6 @@ dependencies = [ "io-uring", "kio 0.6.2", "libc", - "moq-clock", "moq-congestion", "moq-net", "moq-quic", @@ -6365,7 +6334,6 @@ dependencies = [ "libloading 0.9.0", "libvpx-native-sys", "linux-raw-sys 0.12.1", - "moq-clock", "moq-mux", "moq-net", "moq-nvenc", @@ -8544,7 +8512,6 @@ dependencies = [ "futures", "kio 0.6.2", "libc", - "moq-clock", "moq-net", "moq-quic", "qmux 0.6.5", diff --git a/Cargo.toml b/Cargo.toml index f8ae08f0858..d587e7679cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,15 +1,13 @@ [workspace] # Keep source-only members discoverable in Maturin's dependency-pruned archive, # including the separately packaged UniFFI generator. -members = ["demo/carla/bridge", "rs/*", "rs/kio/macros", "rs/moq-clock/macros", "rs/moq-net/fuzz", "rs/moq-quic/fuzz"] +members = ["demo/carla/bridge", "rs/*", "rs/kio/macros", "rs/moq-net/fuzz", "rs/moq-quic/fuzz"] default-members = [ "rs/bench-harness", "rs/kio", "rs/kio/macros", "rs/hang", # "rs/moq-c", # requires C toolchain - "rs/moq-clock", - "rs/moq-clock/macros", "rs/moq-congestion", "rs/moq-archive", "rs/moq-auth", @@ -129,8 +127,6 @@ mdns-sd = { version = "0.21", features = ["async"] } moq-archive = { version = "0.0.11", path = "rs/moq-archive" } moq-audio = { version = "0.1.10", path = "rs/moq-audio", default-features = false } moq-auth = { version = "0.2.1", path = "rs/moq-auth" } -moq-clock = { version = "0.11.0", path = "rs/moq-clock" } -moq-clock-macros = { version = "0.1.0", path = "rs/moq-clock/macros" } moq-congestion = { version = "0.1.0", path = "rs/moq-congestion" } moq-hls = { version = "0.5.11", path = "rs/moq-hls", default-features = false } moq-ice = { version = "0.1.0", path = "rs/moq-ice" } diff --git a/clippy.toml b/clippy.toml index 637b13a60bf..0585bbd9a4d 100644 --- a/clippy.toml +++ b/clippy.toml @@ -7,24 +7,24 @@ # # The wasm32 lint builds tokio without `time`, where the tokio paths do not resolve. 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::Instant::now", reason = "read the ambient clock: kio::clock::now()" }, + { path = "std::time::Instant::elapsed", reason = "read the ambient clock: kio::clock::Instant::elapsed()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: kio::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()", allow-invalid = true }, - { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()", allow-invalid = true }, - { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()", allow-invalid = true }, - { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()", allow-invalid = true }, - { path = "tokio::time::timeout_at", reason = "use the ambient clock: moq_clock::timeout_at()", allow-invalid = true }, - { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()", allow-invalid = true }, - { path = "tokio::time::interval_at", reason = "use the ambient clock: moq_clock::interval_at()", allow-invalid = true }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: kio::clock::now()", allow-invalid = true }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()", allow-invalid = true }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: kio::clock::sleep_until()", allow-invalid = true }, + { path = "tokio::time::timeout", reason = "use the ambient clock: kio::clock::timeout()", allow-invalid = true }, + { path = "tokio::time::timeout_at", reason = "use the ambient clock: kio::clock::timeout_at()", allow-invalid = true }, + { path = "tokio::time::interval", reason = "use the ambient clock: kio::clock::interval()", allow-invalid = true }, + { path = "tokio::time::interval_at", reason = "use the ambient clock: kio::clock::interval_at()", allow-invalid = true }, ] 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", allow-invalid = true }, - { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep", allow-invalid = true }, - { path = "tokio::time::Interval", reason = "use moq_clock::Interval", allow-invalid = true }, + { path = "std::time::SystemTime", reason = "use kio::clock::Wall" }, + { path = "std::time::Instant", reason = "use kio::clock::Instant" }, + { path = "tokio::time::Instant", reason = "use kio::clock::Instant", allow-invalid = true }, + { path = "tokio::time::Sleep", reason = "use kio::clock::Sleep", allow-invalid = true }, + { path = "tokio::time::Interval", reason = "use kio::clock::Interval", allow-invalid = true }, ] diff --git a/doc/.vitepress/config.ts b/doc/.vitepress/config.ts index 6d7bf74b216..cded15ad988 100644 --- a/doc/.vitepress/config.ts +++ b/doc/.vitepress/config.ts @@ -208,7 +208,7 @@ export default defineConfig({ { text: "moq-auth", link: "/lib/rs/moq-auth" }, { text: "moq-room", link: "/lib/rs/moq-room" }, { text: "moq-json", link: "/lib/rs/moq-json" }, - { text: "moq-clock", link: "/lib/rs/moq-clock" }, + { text: "kio", link: "/lib/rs/kio" }, ], }, { diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index 7293881269a..7fab9c01cc5 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -39,7 +39,7 @@ see [Applications](/bin/). [Examples](/setup/examples) links runnable consumers; | [moq-sign](https://github.com/moq-dev/moq/tree/main/rs/moq-sign) | Workspace-only per-frame Ed25519 signatures, so relays forward content they cannot forge, retime, or relocate. | | [moq-loc](https://docs.rs/moq-loc), [moq-msf](https://docs.rs/moq-msf) | The IETF LOC container and MSF catalog. | | [moq-stats](https://docs.rs/moq-stats) | Publish and consume relay traffic counters as tracks. | -| [moq-clock](/lib/rs/moq-clock) | One clock for time and timers on tokio, the browser, and a deterministic test simulator. | +| [kio](/lib/rs/kio) | The async primitives everything polls through, and one clock for time and timers on tokio and a deterministic test simulator. | | [moq-hls](https://docs.rs/moq-hls), [moq-rtmp](https://docs.rs/moq-rtmp), [moq-srt](https://docs.rs/moq-srt), [moq-rtsp](https://github.com/moq-dev/moq/tree/main/rs/moq-rtsp), [moq-rtc](https://docs.rs/moq-rtc) | The [gateways](/bin/), as libraries you can embed with your own auth. | | [moq-ffi](https://docs.rs/moq-ffi), [moq-c](/lib/c/) | The UniFFI core behind the language bindings, and the C ABI. | | [moq-relay](/bin/relay/), [moq-cli](/bin/cli) | The binaries, also usable as crates. | diff --git a/doc/lib/rs/moq-clock.md b/doc/lib/rs/kio.md similarity index 71% rename from doc/lib/rs/moq-clock.md rename to doc/lib/rs/kio.md index 24841d6e246..76063d77cc7 100644 --- a/doc/lib/rs/moq-clock.md +++ b/doc/lib/rs/kio.md @@ -1,33 +1,41 @@ --- -title: moq-clock -description: One clock for time, timers, and deterministic tests +title: kio +description: Async primitives, and one clock for time, timers, and deterministic tests --- -# moq-clock +# kio -[![crates.io](https://img.shields.io/crates/v/moq-clock)](https://crates.io/crates/moq-clock) -[![docs.rs](https://docs.rs/moq-clock/badge.svg)](https://docs.rs/moq-clock) +[![crates.io](https://img.shields.io/crates/v/kio)](https://crates.io/crates/kio) +[![docs.rs](https://docs.rs/kio/badge.svg)](https://docs.rs/kio) -One clock for reading time and arming timers, so the same code runs on tokio, -in the browser, and in a simulator that tests drive. +The "easy async" primitives the other crates poll through, and `kio::clock`: +one clock for reading time and arming timers, so the same code runs on tokio +and in a simulator that tests drive. ## The clock -`moq_clock::Instant` is a monotonic instant, counted in nanoseconds from the +`kio::clock::Instant` is a monotonic instant, counted in nanoseconds from the clock's origin, with the methods of `std::time::Instant`. `Wall` is wall time from the same clock. It is a separate type because wall time can step forward or back without any time passing, so it never measures elapsed time. Async code reads the ambient clock: `now()`, `wall()`, `sleep()`, `sleep_until()`, `timeout()`, `interval()`, and `drive()` resolve to the -current runtime's clock. That is tokio's on native, including paused tokio, -and `performance.now()` with `setTimeout` in the browser. Nothing is plumbed -through. On native, every unpaused runtime and every plain thread share one +current runtime's clock. That is tokio's, including paused tokio. Nothing is +plumbed through. Every unpaused runtime and every plain thread share one clock, so their instants compare. A paused tokio runtime has its own clock, and it pauses the instant but not wall time. The simulator is its own clock too. A runtime that reads the time itself, like a moq-uring worker, enters a `Deadlines` queue on its thread, and the ambient clock is that queue. +Host timers need the `runtime` feature, which is off by default so a kio user +that never waits on the host clock compiles no runtime backend: + +```toml +[dependencies] +kio = { version = "0.6", features = ["runtime"] } +``` + Instants from different clocks don't compare. On native, `Instant::into_std()` and `Instant::from_std()` convert at a third-party API that takes `std::time::Instant`, through the runtime clock's origin. That is exact on a @@ -51,19 +59,19 @@ for dev-dependencies only: ```toml [dev-dependencies] -moq-clock = { version = "0.11", features = ["sim"] } +kio = { version = "0.6", features = ["sim"] } ``` ```rust use std::time::Duration; -#[moq_clock::test] +#[kio::test] async fn gives_up_after_five_seconds() { - let task = moq_clock::sim::spawn(async { - moq_clock::timeout(Duration::from_secs(5), std::future::pending::<()>()).await + let task = kio::clock::sim::spawn(async { + kio::clock::timeout(Duration::from_secs(5), std::future::pending::<()>()).await }); assert!(task.await.unwrap().is_err()); - assert_eq!(moq_clock::now(), moq_clock::Instant::ZERO + Duration::from_secs(5)); + assert_eq!(kio::clock::now(), kio::clock::Instant::ZERO + Duration::from_secs(5)); } ``` @@ -88,4 +96,4 @@ reaches them, and other runtimes and threads keep the host clock. Python's Tests that do real I/O (sockets, browsers, codecs) can't use the simulator. They wait on events and use the host clock only for a watchdog. -API: [docs.rs/moq-clock](https://docs.rs/moq-clock). +API: [docs.rs/kio](https://docs.rs/kio). diff --git a/doc/setup/repository.md b/doc/setup/repository.md index 74264d780b3..444516b2d71 100644 --- a/doc/setup/repository.md +++ b/doc/setup/repository.md @@ -33,7 +33,7 @@ wrap the Rust core. [Layers](/lib/layers) maps the binding namespaces. | Rooms, chat, and application data | [`rs/moq-room`](https://github.com/moq-dev/moq/tree/main/rs/moq-room), [`js/room`](https://github.com/moq-dev/moq/tree/main/js/room), `rs/moq-json`, `js/json` | [Rooms](/lib/js/room), [JSON tracks](/lib/js/json) | | End-to-end encryption | [`rs/moq-e2ee`](https://github.com/moq-dev/moq/tree/main/rs/moq-e2ee), [`js/e2ee`](https://github.com/moq-dev/moq/tree/main/js/e2ee) | [Media encryption](/concept/hang), [E2EE draft](/draft/moq-e2ee) | | Signed content | [`rs/moq-sign`](https://github.com/moq-dev/moq/tree/main/rs/moq-sign), [`js/sign`](https://github.com/moq-dev/moq/tree/main/js/sign) | [Signing draft](/draft/moq-sign) | -| Async primitives and deterministic time | [`rs/kio`](https://github.com/moq-dev/moq/tree/main/rs/kio), [`rs/moq-clock`](https://github.com/moq-dev/moq/tree/main/rs/moq-clock), [`js/clock`](https://github.com/moq-dev/moq/tree/main/js/clock) | [Rust conventions](/lib/rs/#conventions), [clock](/lib/js/clock) | +| Async primitives and deterministic time | [`rs/kio`](https://github.com/moq-dev/moq/tree/main/rs/kio), [`js/clock`](https://github.com/moq-dev/moq/tree/main/js/clock) | [Rust conventions](/lib/rs/#conventions), [clock](/lib/js/clock) | ## Find the surrounding work diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index b4dcf1152dd..b884b90e79c 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -27,7 +27,7 @@ replaces it. - **Binaries:** [moq-relay](https://github.com/moq-dev/moq/blob/main/rs/moq-relay/MIGRATE.md), [moq-cli (`moq`)](https://github.com/moq-dev/moq/blob/main/rs/moq-cli/MIGRATE.md), [moq-gst](https://github.com/moq-dev/moq/blob/main/rs/moq-gst/MIGRATE.md), [obs-moq](https://github.com/moq-dev/moq/blob/main/cpp/obs/MIGRATE.md) - **Bindings:** [moq-ffi (UniFFI)](https://github.com/moq-dev/moq/blob/main/rs/moq-ffi/MIGRATE.md), [moq-c (C)](https://github.com/moq-dev/moq/blob/main/rs/moq-c/MIGRATE.md), [Python](https://github.com/moq-dev/moq/blob/main/py/moq-rs/MIGRATE.md), [Go](https://github.com/moq-dev/moq/blob/main/go/wrapper/MIGRATE.md), [Swift](https://github.com/moq-dev/moq/blob/main/swift/MIGRATE.md), [Kotlin](https://github.com/moq-dev/moq/blob/main/kt/moq/MIGRATE.md), [Dart](https://github.com/moq-dev/moq/blob/main/dart/moq/MIGRATE.md), [C++](https://github.com/moq-dev/moq/blob/main/cpp/moq/MIGRATE.md) -- **Rust:** [hang](https://github.com/moq-dev/moq/blob/main/rs/hang/MIGRATE.md), [kio](https://github.com/moq-dev/moq/blob/main/rs/kio/MIGRATE.md), [kio-macros](https://github.com/moq-dev/moq/blob/main/rs/kio/macros/MIGRATE.md), [moq-archive](https://github.com/moq-dev/moq/blob/main/rs/moq-archive/MIGRATE.md), [moq-audio](https://github.com/moq-dev/moq/blob/main/rs/moq-audio/MIGRATE.md), [moq-auth](https://github.com/moq-dev/moq/blob/main/rs/moq-auth/MIGRATE.md), [moq-boy](https://github.com/moq-dev/moq/blob/main/rs/moq-boy/MIGRATE.md), [moq-clock](https://github.com/moq-dev/moq/blob/main/rs/moq-clock/MIGRATE.md), [moq-clock-macros](https://github.com/moq-dev/moq/blob/main/rs/moq-clock/macros/MIGRATE.md), [moq-e2ee](https://github.com/moq-dev/moq/blob/main/rs/moq-e2ee/MIGRATE.md), [moq-hls](https://github.com/moq-dev/moq/blob/main/rs/moq-hls/MIGRATE.md), [moq-ice](https://github.com/moq-dev/moq/blob/main/rs/moq-ice/MIGRATE.md), [moq-json](https://github.com/moq-dev/moq/blob/main/rs/moq-json/MIGRATE.md), [moq-loc](https://github.com/moq-dev/moq/blob/main/rs/moq-loc/MIGRATE.md), [moq-msf](https://github.com/moq-dev/moq/blob/main/rs/moq-msf/MIGRATE.md), [moq-mux](https://github.com/moq-dev/moq/blob/main/rs/moq-mux/MIGRATE.md), [moq-net](https://github.com/moq-dev/moq/blob/main/rs/moq-net/MIGRATE.md), [moq-nvenc](https://github.com/moq-dev/moq/blob/main/rs/moq-nvenc/MIGRATE.md), [moq-pattern](https://github.com/moq-dev/moq/blob/main/rs/moq-pattern/MIGRATE.md), [moq-quic](https://github.com/moq-dev/moq/blob/main/rs/moq-quic/MIGRATE.md), [moq-room](https://github.com/moq-dev/moq/blob/main/rs/moq-room/MIGRATE.md), [moq-rtc](https://github.com/moq-dev/moq/blob/main/rs/moq-rtc/MIGRATE.md), [moq-rtmp](https://github.com/moq-dev/moq/blob/main/rs/moq-rtmp/MIGRATE.md), [moq-sock](https://github.com/moq-dev/moq/blob/main/rs/moq-sock/MIGRATE.md), [moq-srt](https://github.com/moq-dev/moq/blob/main/rs/moq-srt/MIGRATE.md), [moq-stats](https://github.com/moq-dev/moq/blob/main/rs/moq-stats/MIGRATE.md), [moq-tokio](https://github.com/moq-dev/moq/blob/main/rs/moq-tokio/MIGRATE.md), [moq-transcode](https://github.com/moq-dev/moq/blob/main/rs/moq-transcode/MIGRATE.md), [moq-uring](https://github.com/moq-dev/moq/blob/main/rs/moq-uring/MIGRATE.md), [moq-v4l](https://github.com/moq-dev/moq/blob/main/rs/moq-v4l/MIGRATE.md), [moq-video](https://github.com/moq-dev/moq/blob/main/rs/moq-video/MIGRATE.md), [qmux](https://github.com/moq-dev/moq/blob/main/rs/qmux/MIGRATE.md) +- **Rust:** [hang](https://github.com/moq-dev/moq/blob/main/rs/hang/MIGRATE.md), [kio](https://github.com/moq-dev/moq/blob/main/rs/kio/MIGRATE.md), [kio-macros](https://github.com/moq-dev/moq/blob/main/rs/kio/macros/MIGRATE.md), [moq-archive](https://github.com/moq-dev/moq/blob/main/rs/moq-archive/MIGRATE.md), [moq-audio](https://github.com/moq-dev/moq/blob/main/rs/moq-audio/MIGRATE.md), [moq-auth](https://github.com/moq-dev/moq/blob/main/rs/moq-auth/MIGRATE.md), [moq-boy](https://github.com/moq-dev/moq/blob/main/rs/moq-boy/MIGRATE.md), [moq-e2ee](https://github.com/moq-dev/moq/blob/main/rs/moq-e2ee/MIGRATE.md), [moq-hls](https://github.com/moq-dev/moq/blob/main/rs/moq-hls/MIGRATE.md), [moq-ice](https://github.com/moq-dev/moq/blob/main/rs/moq-ice/MIGRATE.md), [moq-json](https://github.com/moq-dev/moq/blob/main/rs/moq-json/MIGRATE.md), [moq-loc](https://github.com/moq-dev/moq/blob/main/rs/moq-loc/MIGRATE.md), [moq-msf](https://github.com/moq-dev/moq/blob/main/rs/moq-msf/MIGRATE.md), [moq-mux](https://github.com/moq-dev/moq/blob/main/rs/moq-mux/MIGRATE.md), [moq-net](https://github.com/moq-dev/moq/blob/main/rs/moq-net/MIGRATE.md), [moq-nvenc](https://github.com/moq-dev/moq/blob/main/rs/moq-nvenc/MIGRATE.md), [moq-pattern](https://github.com/moq-dev/moq/blob/main/rs/moq-pattern/MIGRATE.md), [moq-quic](https://github.com/moq-dev/moq/blob/main/rs/moq-quic/MIGRATE.md), [moq-room](https://github.com/moq-dev/moq/blob/main/rs/moq-room/MIGRATE.md), [moq-rtc](https://github.com/moq-dev/moq/blob/main/rs/moq-rtc/MIGRATE.md), [moq-rtmp](https://github.com/moq-dev/moq/blob/main/rs/moq-rtmp/MIGRATE.md), [moq-sock](https://github.com/moq-dev/moq/blob/main/rs/moq-sock/MIGRATE.md), [moq-srt](https://github.com/moq-dev/moq/blob/main/rs/moq-srt/MIGRATE.md), [moq-stats](https://github.com/moq-dev/moq/blob/main/rs/moq-stats/MIGRATE.md), [moq-tokio](https://github.com/moq-dev/moq/blob/main/rs/moq-tokio/MIGRATE.md), [moq-transcode](https://github.com/moq-dev/moq/blob/main/rs/moq-transcode/MIGRATE.md), [moq-uring](https://github.com/moq-dev/moq/blob/main/rs/moq-uring/MIGRATE.md), [moq-v4l](https://github.com/moq-dev/moq/blob/main/rs/moq-v4l/MIGRATE.md), [moq-video](https://github.com/moq-dev/moq/blob/main/rs/moq-video/MIGRATE.md), [qmux](https://github.com/moq-dev/moq/blob/main/rs/qmux/MIGRATE.md) - **JavaScript:** [`@moq/auth`](https://github.com/moq-dev/moq/blob/main/js/auth/MIGRATE.md), [`@moq/boy`](https://github.com/moq-dev/moq/blob/main/js/moq-boy/MIGRATE.md), [`@moq/clock`](https://github.com/moq-dev/moq/blob/main/js/clock/MIGRATE.md), [`@moq/hang`](https://github.com/moq-dev/moq/blob/main/js/hang/MIGRATE.md), [`@moq/json`](https://github.com/moq-dev/moq/blob/main/js/json/MIGRATE.md), [`@moq/loc`](https://github.com/moq-dev/moq/blob/main/js/loc/MIGRATE.md), [`@moq/msf`](https://github.com/moq-dev/moq/blob/main/js/msf/MIGRATE.md), [`@moq/net`](https://github.com/moq-dev/moq/blob/main/js/net/MIGRATE.md), [`@moq/p2p`](https://github.com/moq-dev/moq/blob/main/js/p2p/MIGRATE.md), [`@moq/pattern`](https://github.com/moq-dev/moq/blob/main/js/pattern/MIGRATE.md), [`@moq/publish`](https://github.com/moq-dev/moq/blob/main/js/publish/MIGRATE.md), [`@moq/qmux`](https://github.com/moq-dev/moq/blob/main/js/qmux/MIGRATE.md), [`@moq/room`](https://github.com/moq-dev/moq/blob/main/js/room/MIGRATE.md), [`@moq/signals`](https://github.com/moq-dev/moq/blob/main/js/signals/MIGRATE.md), [`@moq/ui`](https://github.com/moq-dev/moq/blob/main/js/ui/MIGRATE.md), [`@moq/video`](https://github.com/moq-dev/moq/blob/main/js/video/MIGRATE.md), [`@moq/watch`](https://github.com/moq-dev/moq/blob/main/js/watch/MIGRATE.md) ## Unreleased diff --git a/js/clock/src/index.ts b/js/clock/src/index.ts index 832720d1ced..54599b7718a 100644 --- a/js/clock/src/index.ts +++ b/js/clock/src/index.ts @@ -20,7 +20,7 @@ export function wall(): Wall { /** * Read the installed clock's wall time at instant zero, in Unix milliseconds. - * Rust's `moq_clock::origin()` pairs a nanosecond `Wall` with an instant instead. + * Rust's `kio::clock::origin()` pairs a nanosecond `Wall` with an instant instead. */ export function origin(): Wall { return Wall(backend().origin()); diff --git a/quest/m0/ci/slow-tests.md b/quest/m0/ci/slow-tests.md index 27135ad7aec..f2a0e504661 100644 --- a/quest/m0/ci/slow-tests.md +++ b/quest/m0/ci/slow-tests.md @@ -39,7 +39,7 @@ the tests a change touches. 137.83 s to 116.83 s with fixture-only changes: the two MPEG-TS reset tests in `container::ts::import` drain on the exporter's deadlines with a retention derived from their stimulus instead of an hour of idle output (12.98 s to 0.18 s), and the jitter -`drift` and `feed` helpers advance a `moq_clock::Deadlines` queue instead of the tokio +`drift` and `feed` helpers advance a `kio::clock::Deadlines` queue instead of the tokio paused clock (10.16 s to 6.80 s across 8 tests). About 48 s remains to cut. Tried and dropped, so don't redo them without new evidence: diff --git a/quest/m0/test-flakes-2/README.md b/quest/m0/test-flakes-2/README.md index 680bcd05bfc..98a2fc64454 100644 --- a/quest/m0/test-flakes-2/README.md +++ b/quest/m0/test-flakes-2/README.md @@ -21,8 +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, 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. + clock, drive the timers with a `kio::clock::Manual` clock or the sim (every + crate's timers run on `kio::clock`), or move the test off real sockets. - A mocked clock still flakes when the code jitters its timers with `rand` (one 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. diff --git a/quest/m1/README.md b/quest/m1/README.md index ca3762b7bd7..94843c6f595 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -164,7 +164,7 @@ removed). - [CI housekeeping](/quest/m1/ci-housekeeping.md) - remove the actionlint queue ignore once a release after 1.7.12 reaches the dev shell - [crates.io trusts the workflow](/quest/m1/crates-trusted-publisher.md) - maintainer action: every published crate gets a trusted publisher for `release-rs.yml` - [Rust releases publish through OIDC](/quest/m1/release-rs-oidc.md) - release-plz publishes with trusted publishing and `CARGO_REGISTRY_TOKEN` is revoked -- [moq-clock's tests pass under cargo test](/quest/m1/clock-test-process.md) - `paused_runtimes_own_their_anchors` stops depending on being first in its process +- [kio's clock tests pass under cargo test](/quest/m1/clock-test-process.md) - `paused_runtimes_own_their_anchors` stops depending on being first in its process - [The JS stalled-consumer eviction test ages its groups](/quest/m1/js-cache-age-test.md) - the test drives the clock the cache reads, so it can fail - [moq-transport-22 FETCH cost](/quest/m1/ietf22-fetch-poll-cost.md) - #7042's +12.8% instructions on draft-22 FETCH is fixed or attributed - [An idle track poll exits cheaply](/quest/m1/idle-poll-exit.md) - a reader's poll on a track with nothing new costs a small constant, not ~3,800 instructions @@ -177,7 +177,6 @@ removed). - [Lite track end at session death](/quest/m1/lite-track-end.md) - Rust and JS abort an ended lite track whose tail never settled, and agree on what declares the end - [Legacy lite close drain](/quest/m1/lite-legacy-close-drain.md) - a lite-01..06 graceful close never cuts a final group the subscriber has not read - [moqsrc max-delay](/quest/m1/gst-max-delay.md) - GStreamer's `moqsrc` takes a `max-delay` property instead of a hard-coded 1 s budget -- [moq-clock moves into kio::clock](/quest/m1/kio-clock.md) - moq-clock and its test macro become `kio::clock` and `#[kio::test]` before the cut publishes them - [Poll-first async](/quest/m1/poll-first/README.md) - library crates compile no coroutines by default: async wrappers are generated from `poll_*` and gated behind an `async` feature - [Binding announcements always carry captures](/quest/m1/ffi-required-captures.md) - moq-ffi and its generated bindings make `captures` a required list, as #7266 always sets it - [HLS export follows a resolution change](/quest/m1/hls-reinit-same-codec.md) - a decoder-identity change under the same codec string starts a new init and segment tag diff --git a/quest/m1/binding-timestamps.md b/quest/m1/binding-timestamps.md index 9b75e4b5baa..65a84f2c3aa 100644 --- a/quest/m1/binding-timestamps.md +++ b/quest/m1/binding-timestamps.md @@ -69,5 +69,5 @@ keep "untimed as absent" until then too. At the cut timed, and [bindings by start](/quest/m1/time-addressing/bindings.md) drops that `Option` from reads only. -Wall and monotonic times stay `moq_clock::Wall` and `moq_clock::Instant`, not +Wall and monotonic times stay `kio::clock::Wall` and `kio::clock::Instant`, not media timestamps; keep the types distinct. diff --git a/quest/m1/clock-test-process.md b/quest/m1/clock-test-process.md index f2ad4085ba5..f657b8abc63 100644 --- a/quest/m1/clock-test-process.md +++ b/quest/m1/clock-test-process.md @@ -1,8 +1,8 @@ -# [XS] moq-clock's tests pass under cargo test +# [XS] kio's clock tests pass under cargo test ## Goal -`cargo test -p moq-clock` passes, not only under nextest. +`cargo test -p kio --all-features` passes, not only under nextest. `paused_runtimes_own_their_anchors` checks the same behavior without depending on being the first test in its process to read the clock. @@ -10,7 +10,7 @@ depending on being the first test in its process to read the clock. Decided 2026-10-29 (maintainer), a follow-up of [moq-dev/moq#7161](https://github.com/moq-dev/moq/pull/7161), whose agent hit -it. The test (`rs/moq-clock/src/runtime.rs`, from +it. The test (`rs/kio/src/clock/runtime.rs`, from [moq-dev/moq#5681](https://github.com/moq-dev/moq/pull/5681)) builds its two paused runtimes before anything reads the clock, "so in a fresh process each counts from its own origin". `cargo test` runs a crate's tests in one diff --git a/quest/m1/kio-clock.md b/quest/m1/kio-clock.md deleted file mode 100644 index 816f03ec4cc..00000000000 --- a/quest/m1/kio-clock.md +++ /dev/null @@ -1,45 +0,0 @@ -# [M] moq-clock moves into kio::clock - -## Goal - -moq-clock and moq-clock-macros become `kio::clock` and kio's test attribute -(`#[kio::test]`), behind kio features that mirror moq-clock's today -(`runtime`, `sim`, `manual`, `serde`). kio's private `_sim` feature goes, every -dependent imports `kio::clock`, and both crates are deleted before the cut -publishes them. - -## Plan - -Decided with the maintainer on 2026-10-25: - -- **Why kio.** Waiting and time are the two halves of "easy async": a - `Deadlines` queue parks kio waiters, and the simulator drives kio tasks. - They're already coupled through kio's `_sim` feature, which exists only for - moq-clock's simulator. Zig's `std.Io` carries the clock with its waits for - the same reason. moq-clock is infrastructure, not a MoQ component, so the - `moq-` prefix was wrong too. -- **Now.** moq-clock is not on `release`, so the move is free before the cut - and a break after it. -- **moq-sock stays.** It is synchronous OS socket plumbing tuned for QUIC (a - quinn-udp fork, connection-id sharding, CPU pinning), not waiting, and would - pull libc and socket2 into a dependency-light crate that also targets wasm. -- **No generic I/O.** kio gets no socket or file seam: tokio's readiness model - and io_uring's completion model (the kernel owns the buffer) can't share a - zero-cost API, and moq's I/O is UDP and TCP under sans-IO cores already split - per runtime by moq-sock. - -Mechanics: keep default features lean, so a kio user that doesn't want a clock -compiles no runtime backend. The 31 dependents, the `clippy.toml` disallowed -methods that name `moq_clock::now()` and friends, and `#[moq_clock::test]` -call sites move over. Move `doc/lib/rs/moq-clock.md` to a kio page (or into -kio's), and fix `doc/lib/rs/index.md`, `doc/setup/repository.md`, and -`doc/setup/upgrade.md`. JS keeps `@moq/clock`: it has no kio, and the -`clock` name still mirrors. - -Public API: moq-clock's items move to `kio::clock` unchanged; kio gains -features. Describe the kio migration in the PR's Impact section. Wire: none. - -## Related - -- [Libraries spawn nothing](/quest/m1/poll-first/no-spawn.md) - removes web-async from the clock's browser backend after this -- [Poll-first async](/quest/m1/poll-first/README.md) - the direction kio carries diff --git a/quest/m1/poll-first/async-feature.md b/quest/m1/poll-first/async-feature.md index 766ef491fc1..34da9f18275 100644 --- a/quest/m1/poll-first/async-feature.md +++ b/quest/m1/poll-first/async-feature.md @@ -28,7 +28,7 @@ ergonomic layer, and the gating proceeds regardless of the build measurement. bodies with a loop or a branch around a wait (about 59 in moq-net) are converted by hand, since the macro stays straight-line only (decided 2026-10-28). -- **Tests:** `#[moq_clock::test]` and `#[tokio::test]` bodies stay async, so test +- **Tests:** `#[kio::test]` and `#[tokio::test]` bodies stay async, so test targets enable the feature. - **Cargo:** feature unification means one dependent enabling `async` enables it for the whole build. Make sure library-only builds, such as `cargo check -p diff --git a/quest/m1/poll-first/no-spawn.md b/quest/m1/poll-first/no-spawn.md index c9be5e86ea8..35c35d270a8 100644 --- a/quest/m1/poll-first/no-spawn.md +++ b/quest/m1/poll-first/no-spawn.md @@ -17,10 +17,11 @@ Decided with the maintainer on 2026-10-25, replacing the m2 runtime trait - **Poll everywhere, no spawn.** A spawn trait keeps `'static` detached tasks in the library, which poll-first rejects; `kio::Tasks` already gives a library structured children with no runtime. Time is - [kio::clock](/quest/m1/kio-clock.md), so nothing is left for a runtime trait. + `kio::clock`, so nothing is left for a runtime trait. `rs/AGENTS.md` already treats `tokio::spawn` in a library as a smell. - **No I/O seam.** I/O stays at moq-net's `transport::poll` traits and - moq-sock (see kio::clock's Plan). + moq-sock: tokio's readiness model and io_uring's completion model (the + kernel owns the buffer) can't share a zero-cost API. - **Blocking work is out of scope.** OS threads for blocking capture, encode, or file I/O are not async tasks and stay. @@ -32,10 +33,6 @@ Public API: constructors that spawned return a handle to poll or await instead. The PR's Impact section describes migration for the published crates whose API changes. Wire: none. -## Required - -- [moq-clock moves into kio::clock](/quest/m1/kio-clock.md) - the clock backend this rewrites, in its final place - ## Related - [The remaining spawns](/quest/m2/spawn-audit.md) - the same rule for every other library crate diff --git a/quest/m2/audit-test-coverage.md b/quest/m2/audit-test-coverage.md index 76f34c8d374..50b6d705618 100644 --- a/quest/m2/audit-test-coverage.md +++ b/quest/m2/audit-test-coverage.md @@ -45,7 +45,7 @@ which is expensive on a shared machine. binding facades below in minutes. Per-file uncovered line counts mostly point at GPU code and generated bindings instead. - When sampling `fix` commits for regression tests, count - `#[moq_clock::test]` as well as `#[test]` and `#[tokio::test]`. + `#[kio::test]` as well as `#[test]` and `#[tokio::test]`. ### m1 baselines diff --git a/quest/m2/perf/README.md b/quest/m2/perf/README.md index 5086788bc2a..23a8199d184 100644 --- a/quest/m2/perf/README.md +++ b/quest/m2/perf/README.md @@ -57,7 +57,7 @@ profile shows no pool contention. #3122's per-turn clock read landed in [#5926](https://github.com/moq-dev/moq/pull/5926): the io_uring worker is a -`moq-clock` backend that samples the clock once per turn, cutting +`kio::clock` backend that samples the clock once per turn, cutting `clock_gettime` from 44.7 to 1.05 calls per turn. `perf` was unavailable there, so [Profile the io_uring clock read](/quest/m2/perf/uring-clock-profile.md) owns the `[vdso]` share and relay CPU measurement. diff --git a/quest/m2/perf/stream/driver.md b/quest/m2/perf/stream/driver.md index 6ff72686b6a..8cce2eaa0ab 100644 --- a/quest/m2/perf/stream/driver.md +++ b/quest/m2/perf/stream/driver.md @@ -32,7 +32,7 @@ What goes, per the audit in the [epic](/quest/m2/perf/stream/README.md): - the separate `run_reader` and `run_writer` tasks - `tokio::io::split` and the `reader_loop` task on plain streams - `tokio::select!` and `tokio::time`. The WebSocket keep-alive moves to - `moq_clock` like the mux timers. + `kio::clock` like the mux timers. Buffers: parse inbound records from one reusable read buffer into `Bytes` slices, with no zeroed allocation per record. Encode outbound records and diff --git a/quest/m2/quic-sim.md b/quest/m2/quic-sim.md index bcf3ecc3509..600251f22b1 100644 --- a/quest/m2/quic-sim.md +++ b/quest/m2/quic-sim.md @@ -2,7 +2,7 @@ ## Goal -The `moq-clock` sim drives MoQ sessions and the relay over `moq-quic`, with +The `kio::clock` sim drives MoQ sessions and the relay over `moq-quic`, with configurable latency, loss, reordering, and bandwidth, so MoQ over real QUIC (the transport race, relay hops, recovery) is tested deterministically with no sockets. diff --git a/quest/m2/sim-seed.md b/quest/m2/sim-seed.md index a6e02cee0c2..ac37f573c41 100644 --- a/quest/m2/sim-seed.md +++ b/quest/m2/sim-seed.md @@ -2,7 +2,7 @@ ## Goal -Under the `moq-clock` sim, every source of randomness that affects behavior +Under the `kio::clock` sim, every source of randomness that affects behavior (moq-net's clock anchor jitter, backoff jitter, alert jitter) draws from one seeded generator the sim owns, and a failing sim test prints its seed so it replays bit-exact. diff --git a/quest/m2/webrtc/README.md b/quest/m2/webrtc/README.md index bb1a64a81f9..86bbb454ce6 100644 --- a/quest/m2/webrtc/README.md +++ b/quest/m2/webrtc/README.md @@ -8,7 +8,7 @@ Non-goals: TURN; DTLS 1.3; replacing a vendored layer before there's a reason to ## Plan -Decided 2026-10-30 with the maintainer (planning interview), after the str0m workarounds piled up: one `b=` line per SDP media section ([moq-dev/moq#7373](https://github.com/moq-dev/moq/pull/7373)), DTLS retransmits running out before ICE connects ([moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379)), no hook to charge or serve NACK resends ([rtc-pacing](/quest/m2/rtc-pacing.md)), and `std::time::Instant` in a moq-clock workspace. No upstream reports were approved; vendoring replaces them. +Decided 2026-10-30 with the maintainer (planning interview), after the str0m workarounds piled up: one `b=` line per SDP media section ([moq-dev/moq#7373](https://github.com/moq-dev/moq/pull/7373)), DTLS retransmits running out before ICE connects ([moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379)), no hook to charge or serve NACK resends ([rtc-pacing](/quest/m2/rtc-pacing.md)), and `std::time::Instant` in a `kio::clock` workspace. No upstream reports were approved; vendoring replaces them. - **Vendor, then replace.** Copy the upstream crates in, trim them, and fix them in-tree. Replacing a layer with our own (SDP, RTP/RTCP, SRTP, SCTP) is a later child once a concrete need appears; none is planned yet. - **One crate.** `moq-ice` merges into it, since its only users are `moq-rtc` and moq-tokio's data-channel transport. moq-tokio's `webrtc` feature moves into `moq-webrtc` as well, which breaks the cycle (`moq-webrtc` depends on moq-tokio; moq-tokio would otherwise need ICE and SCTP). The vendored crates become private modules, not separate published crates, keeping their MIT/Apache-2.0 notices (str0m's `packet/` carries webrtc-rs's Apache notice). @@ -24,7 +24,7 @@ Decided 2026-10-30 with the maintainer (planning interview), after the str0m wor - [Vendor and trim the stack](/quest/m2/webrtc/vendor.md) - str0m, dimpl, `is`, and sctp-proto live in moq-webrtc with unused code removed - [Several bandwidth lines per media section](/quest/m2/webrtc/sdp-bandwidth.md) - answers carry both `b=TIAS` and `b=AS` without splicing - [DTLS waits for ICE](/quest/m2/webrtc/dtls-after-ice.md) - DTLS flights start once ICE nominates a pair, so a late ICE path can't exhaust them -- [The stack takes moq-clock time](/quest/m2/webrtc/clock.md) - the vendored code takes `moq_clock::Instant`, so sim tests drive it directly +- [The stack takes kio clock time](/quest/m2/webrtc/clock.md) - the vendored code takes `kio::clock::Instant`, so sim tests drive it directly ## Related diff --git a/quest/m2/webrtc/clock.md b/quest/m2/webrtc/clock.md index 75fa6fabcdb..832da2839e2 100644 --- a/quest/m2/webrtc/clock.md +++ b/quest/m2/webrtc/clock.md @@ -1,8 +1,8 @@ -# [XS] The WebRTC stack takes moq-clock time +# [XS] The WebRTC stack takes kio clock time ## Goal -The vendored str0m and dimpl take `moq_clock::Instant` instead of `std::time::Instant`, so moq-webrtc drops its `into_std()` conversions and sim tests drive the stack's timers directly. +The vendored str0m and dimpl take `kio::clock::Instant` instead of `std::time::Instant`, so moq-webrtc drops its `into_std()` conversions and sim tests drive the stack's timers directly. ## Plan diff --git a/quest/m3/rs2ts-model-subset.md b/quest/m3/rs2ts-model-subset.md index 1ca7ba60110..3c0acf07c4e 100644 --- a/quest/m3/rs2ts-model-subset.md +++ b/quest/m3/rs2ts-model-subset.md @@ -2,7 +2,7 @@ ## Goal -moq-net's model, and the kio, moq-clock, and moq-pattern code it calls, stay inside the +moq-net's model, and the kio (clock included) and moq-pattern code it calls, stay inside the subset [rust2-ts](https://github.com/moq-dev/rust2/blob/main/ts/README.md) translates, so the [source-translator route](/quest/m2/rs2ts-wasm2js.md) can be measured on the model with no hand-written stand-ins for moq's own logic. diff --git a/rs/AGENTS.md b/rs/AGENTS.md index 742c779a4dd..4b3cd8bb03e 100644 --- a/rs/AGENTS.md +++ b/rs/AGENTS.md @@ -57,7 +57,7 @@ Prefer poll. New logic is a `poll_*` with an `async` helper, not the other way a # Testing -- Tests are inline `#[cfg(test)] mod tests`, except full Client/Server session tests over a crate's shared mock harness, which go in its `tests/integration/` module. Time-dependent async tests call `tokio::time::pause()` first (moq-net uses `#[moq_clock::test]` instead), unless they cross real networking that can't be mocked (sockets, smoke tests); those run on the wall clock and assert lower bounds. +- Tests are inline `#[cfg(test)] mod tests`, except full Client/Server session tests over a crate's shared mock harness, which go in its `tests/integration/` module. Time-dependent async tests call `tokio::time::pause()` first (moq-net uses `#[kio::test]` instead), unless they cross real networking that can't be mocked (sockets, smoke tests); those run on the wall clock and assert lower bounds. - Run tests through `just` (nextest), not `cargo test`: nextest kills a wedged test as TIMEOUT, cargo hangs forever. A test flagged SLOW is a bug to fix, not a threshold to raise. - `just check` and CI build and test the selected crates in one build at their default features, plus the off-by-default device features and, on Linux, the relay's `io-uring` feature. `just rs features` (nightly and release PRs) covers the feature matrix. Keep a feature gate around the dependency, not the logic, so the logic's tests stay in the merge gate. - Local checks compile only the host platform; Nightly and release PRs run `just rs windows` / `macos` on those hosts. diff --git a/rs/hang/Cargo.toml b/rs/hang/Cargo.toml index 3c59a1a0ddb..3370a7768dc 100644 --- a/rs/hang/Cargo.toml +++ b/rs/hang/Cargo.toml @@ -15,8 +15,7 @@ categories = ["multimedia", "network-programming", "web-programming"] [dependencies] bytes = { workspace = true } hex = { workspace = true } -kio = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-json = { workspace = true } moq-net = { workspace = true } regex = "1" diff --git a/rs/hang/examples/video.rs b/rs/hang/examples/video.rs index d61cfc54022..899b59c8807 100644 --- a/rs/hang/examples/video.rs +++ b/rs/hang/examples/video.rs @@ -103,7 +103,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> }; producer.write(frame)?; - moq_clock::sleep(tokio::time::Duration::from_secs(1)).await; + kio::clock::sleep(tokio::time::Duration::from_secs(1)).await; let frame = moq_mux::container::Frame { timestamp: moq_net::Timestamp::from_secs(2).unwrap(), @@ -113,7 +113,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> }; producer.write(frame)?; - moq_clock::sleep(tokio::time::Duration::from_secs(1)).await; + kio::clock::sleep(tokio::time::Duration::from_secs(1)).await; // Marking this frame as a keyframe closes the current group and starts a new one. let frame = moq_mux::container::Frame { @@ -125,7 +125,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> producer.write(frame)?; // Sleep before exiting and closing the broadcast. - moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; + kio::clock::sleep(tokio::time::Duration::from_secs(10)).await; Ok(()) } diff --git a/rs/hang/src/catalog/clock.rs b/rs/hang/src/catalog/clock.rs index 0f39b6118d3..85c0fafb266 100644 --- a/rs/hang/src/catalog/clock.rs +++ b/rs/hang/src/catalog/clock.rs @@ -67,7 +67,7 @@ impl Clock { /// /// Exact down to the nanosecond; an instant finer than that (a 90 kHz tick) is floored. /// Refuses a result past the JSON-safe range or the wall clock's 1970-2554 range. - pub fn wall_clock(&self, pts: moq_net::Timestamp) -> Result { + pub fn wall_clock(&self, pts: moq_net::Timestamp) -> Result { let overflow = || crate::Error::TimestampOverflow(moq_net::TimeOverflow); let wall_scale = self.wall.scale().as_u64() as u128; let pts_scale = pts.scale().as_u64() as u128; @@ -90,7 +90,7 @@ impl Clock { let nanos = (num % den).checked_mul(1_000_000_000).ok_or_else(overflow)? / den; let since_moq_epoch = std::time::Duration::new(secs, nanos as u32); // A catalog can name a wall beyond the clock's nanosecond range. - moq_clock::Wall::UNIX_EPOCH + kio::clock::Wall::UNIX_EPOCH .checked_add(std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS)) .and_then(|moq_epoch| moq_epoch.checked_add(since_moq_epoch)) .ok_or_else(overflow) @@ -187,13 +187,13 @@ mod test { #[test] fn wall_clock_converts_across_timescales() { let clock = Clock::new(moq_net::Timestamp::from_micros(1_000_000).unwrap()).unwrap(); - let epoch = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 1_000); + let epoch = kio::clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 1_000); assert_eq!( clock.wall_clock(moq_net::Timestamp::from_millis(0).unwrap()).unwrap(), epoch ); - let second = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 2_000); + let second = kio::clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 2_000); assert_eq!( clock .wall_clock(moq_net::Timestamp::from_millis(1000).unwrap()) @@ -217,7 +217,7 @@ mod test { /// Regression: the result was floored to the millisecond, dropping the sub-millisecond part. #[test] fn wall_clock_keeps_sub_millisecond_precision() { - let moq_epoch = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS); + let moq_epoch = kio::clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS); let micros = |v| moq_net::Timestamp::from_micros(v).unwrap(); let nanos = std::time::Duration::from_nanos; diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index 690bafc5c7b..2a4b0bb3fba 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -1189,7 +1189,7 @@ mod test { ); // Record PTS 2000 (ms) lands 2s after the wall epoch, whatever the track timescale. - let expected = moq_clock::Wall::UNIX_EPOCH + let expected = kio::clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS + 1_751_846_402_000); assert_eq!( clock diff --git a/rs/hang/src/echo.rs b/rs/hang/src/echo.rs index afd380bb0fe..db483066af0 100644 --- a/rs/hang/src/echo.rs +++ b/rs/hang/src/echo.rs @@ -77,12 +77,12 @@ pub struct Arrival { pub timestamp: moq_net::Timestamp, /// The arrival wall time, encoded in milliseconds since the MoQ epoch. #[serde_as(as = "crate::snapshot::Wall")] - pub wall: moq_clock::Wall, + pub wall: kio::clock::Wall, } impl Arrival { /// Pair a received media timestamp with the wall time it arrived. - pub fn new(timestamp: moq_net::Timestamp, wall: moq_clock::Wall) -> Self { + pub fn new(timestamp: moq_net::Timestamp, wall: kio::clock::Wall) -> Self { Self { timestamp, wall } } } diff --git a/rs/hang/src/snapshot.rs b/rs/hang/src/snapshot.rs index a2fed15284b..8641a094bad 100644 --- a/rs/hang/src/snapshot.rs +++ b/rs/hang/src/snapshot.rs @@ -50,19 +50,19 @@ impl<'de> DeserializeAs<'de, moq_net::Timestamp> for Millis { } pub(crate) struct Wall; -fn epoch() -> moq_clock::Wall { - moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS) +fn epoch() -> kio::clock::Wall { + kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS) } -impl SerializeAs for Wall { - fn serialize_as(value: &moq_clock::Wall, serializer: S) -> Result { +impl SerializeAs for Wall { + fn serialize_as(value: &kio::clock::Wall, serializer: S) -> Result { let duration = value .checked_duration_since(epoch()) .ok_or_else(|| serde::ser::Error::custom("snapshot wall is before the MoQ epoch"))?; Millis::serialize_as(&duration, serializer) } } -impl<'de> DeserializeAs<'de, moq_clock::Wall> for Wall { - fn deserialize_as>(deserializer: D) -> Result { +impl<'de> DeserializeAs<'de, kio::clock::Wall> for Wall { + fn deserialize_as>(deserializer: D) -> Result { epoch() .checked_add(Millis::deserialize_as(deserializer)?) .ok_or_else(|| serde::de::Error::custom("snapshot wall clock overflow")) @@ -90,7 +90,7 @@ mod tests { #[derive(Debug, Serialize, Deserialize)] struct Value { #[serde_as(as = "Wall")] - wall: moq_clock::Wall, + wall: kio::clock::Wall, } let last_millis = (u64::MAX / 1_000_000) - crate::catalog::MOQ_EPOCH_UNIX_MILLIS; let last = format!(r#"{{"wall":{last_millis}}}"#); diff --git a/rs/justfile b/rs/justfile index 889ba633b48..cfa830c2913 100644 --- a/rs/justfile +++ b/rs/justfile @@ -236,7 +236,7 @@ features: net-features *args: bash sh/rs/net-features.sh "$@" -# Prove moq-quic leaves moq-clock's dev-only runtime to its consumers, and lints without its default features; a workspace build unifies both back in. +# Prove moq-quic leaves kio's dev-only clock runtime to its consumers, and lints without its default features; a workspace build unifies both back in. [positional-arguments] quic-features *args: #!/usr/bin/env bash diff --git a/rs/kio/Cargo.toml b/rs/kio/Cargo.toml index 4c98ec5b76d..210c854a102 100644 --- a/rs/kio/Cargo.toml +++ b/rs/kio/Cargo.toml @@ -9,26 +9,52 @@ version = "0.6.2" edition = "2024" rust-version.workspace = true -keywords = ["async", "producer", "consumer", "state", "sync"] -categories = ["asynchronous", "concurrency"] +keywords = ["async", "producer", "consumer", "clock", "simulation"] +categories = ["asynchronous", "concurrency", "date-and-time", "development-tools::testing"] + +[package.metadata.docs.rs] +features = ["runtime", "manual", "sim", "serde", "macros"] + +# The self dev-dependency below only enables features; no code names it. +[package.metadata.cargo-shear] +ignored = ["kio"] [features] +# Lean by default: without `runtime`, the clock compiles no host timer backend. +default = [] +# Host timers on tokio's clock. +runtime = ["dep:tokio"] +# The deterministic single-threaded executor, `#[kio::test]`, and per-task Ready +# poll accounting. Meant for dev-dependencies, so production builds never compile it. +sim = ["dep:futures", "dep:kio-macros"] +# `clock::Manual::install`: a clock that only a test moves, as one tokio runtime's +# ambient clock. Meant for test builds, so production builds never compile it. +manual = ["runtime"] +# Numeric Unix-second JSON adapters for public wall times. +serde = ["dep:serde", "dep:serde_with"] # `#[kio::machine]`, which writes a `poll_*` state machine from straight-line code. macros = ["dep:kio-macros"] -# Per-task Ready poll accounting for deterministic simulators, never production. -_sim = [] [dependencies] # Frees a log's evicted segments once no read that could reach them is running. crossbeam-epoch = "0.9.21" +futures = { workspace = true, optional = true } kio-macros = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +serde_with = { workspace = true, optional = true } smallvec = { version = "1.15", features = ["union"] } +# The host timers, and the runtime handle that keeps a paused runtime's clock on its own origin. +tokio = { workspace = true, features = ["rt", "time"], optional = true } [dev-dependencies] # Bench-only: the FuturesUnordered comparison in benches/tasks.rs. criterion = { package = "bench-harness", path = "../bench-harness" } futures = "0.3" -tokio = { workspace = true, features = ["macros", "rt", "test-util", "time"] } +# Enable the simulator and the installed manual clock so the clock's tests run in +# the merge gate. +kio = { path = ".", features = ["manual", "sim", "serde"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread", "test-util", "time"] } [[bench]] name = "tasks" diff --git a/rs/kio/README.md b/rs/kio/README.md index cbd1dbf2e13..3cb15d5bbab 100644 --- a/rs/kio/README.md +++ b/rs/kio/README.md @@ -25,6 +25,19 @@ a channel that parks them; evicted entries are freed by epoch-based reclamation. With the `macros` feature, `#[kio::machine]` writes a `poll_*` state machine from straight-line code with explicit waits. +`clock` is the time those waits run on: logical instants, wall time, deadlines, and +timers on tokio (the `runtime` feature). The `sim` feature adds a +deterministic executor and `#[kio::test]`, which runs an `async fn` test on it: + +```rust +#[kio::test] +async fn retries_after_a_second() { + let start = kio::clock::now(); // Instant::ZERO + kio::clock::sleep(std::time::Duration::from_secs(1)).await; // returns at once + assert_eq!(kio::clock::now() - start, std::time::Duration::from_secs(1)); +} +``` + It's used internally by [moq-net](https://github.com/moq-dev/moq/tree/main/rs/moq-net) and friends, but is generic enough to be useful on its own. See the [API documentation](https://docs.rs/kio/) for details. diff --git a/rs/kio/benches/contended.rs b/rs/kio/benches/contended.rs index 6dc4039c456..550ffea718c 100644 --- a/rs/kio/benches/contended.rs +++ b/rs/kio/benches/contended.rs @@ -21,11 +21,7 @@ //! iteration, a fixed cost that matters only at a few consumers per thread. //! //! Run with `cargo bench -p kio --bench contended`. -#![expect( - clippy::disallowed_methods, - clippy::disallowed_types, - reason = "the bench measures real cross-core time on the host clock" -)] +#![expect(clippy::disallowed_methods, reason = "host time measures benchmark throughput")] use std::{ collections::VecDeque, diff --git a/rs/moq-clock/clippy.toml b/rs/kio/clippy.toml similarity index 64% rename from rs/moq-clock/clippy.toml rename to rs/kio/clippy.toml index 02e3531782f..cc37fde2264 100644 --- a/rs/moq-clock/clippy.toml +++ b/rs/kio/clippy.toml @@ -1,14 +1,14 @@ -# Only the backend modules (`runtime`, behind `#[allow]`) read a host clock or arm +# Only the clock backend modules (`runtime`, behind `#[expect]`) read a host clock or arm # a host timer; everything else goes through the ambient clock. 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::Instant::now", reason = "read the ambient clock: kio::clock::now()" }, + { path = "std::time::Instant::elapsed", reason = "read the ambient clock: kio::clock::Instant::elapsed()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: kio::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 = "std::thread::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: kio::clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: kio::clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: kio::clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: kio::clock::interval()" }, ] diff --git a/rs/kio/macros/Cargo.toml b/rs/kio/macros/Cargo.toml index fa1c926d4d5..dbc54b5e6f1 100644 --- a/rs/kio/macros/Cargo.toml +++ b/rs/kio/macros/Cargo.toml @@ -1,8 +1,9 @@ -# The `#[kio::machine]` attribute. A separate crate only because a proc macro -# must be; `kio` re-exports it behind its `macros` feature. +# The `#[kio::machine]` and `#[kio::test]` attributes. A separate crate only +# because a proc macro must be; `kio` re-exports them behind its `macros` and +# `sim` features. [package] name = "kio-macros" -description = "The #[kio::machine] attribute; use it through kio's macros feature." +description = "The #[kio::machine] and #[kio::test] attributes; use them through kio's macros and sim features." authors = ["Luke Curley"] repository = "https://github.com/moq-dev/moq" license = "MIT OR Apache-2.0" @@ -11,8 +12,8 @@ version = "0.1.0" edition = "2024" rust-version.workspace = true -keywords = ["async", "poll", "state-machine"] -categories = ["asynchronous"] +keywords = ["async", "poll", "state-machine", "test", "simulation"] +categories = ["asynchronous", "development-tools::testing"] [lib] proc-macro = true diff --git a/rs/kio/macros/src/lib.rs b/rs/kio/macros/src/lib.rs index 2838bb9352b..c0127347d67 100644 --- a/rs/kio/macros/src/lib.rs +++ b/rs/kio/macros/src/lib.rs @@ -1,7 +1,7 @@ -//! The `#[kio::machine]` attribute: a `poll_*` state machine from straight-line code. +//! The `#[kio::machine]` attribute, a `poll_*` state machine from straight-line code, +//! and the `#[kio::test]` attribute, an `async fn` test run on the simulator. //! -//! Use it through `kio`'s `macros` feature, which re-exports it and documents the -//! dialect. +//! Use them through `kio`'s `macros` and `sim` features, which re-export them. use std::collections::HashSet; @@ -88,6 +88,14 @@ pub fn machine(args: proc_macro::TokenStream, item: proc_macro::TokenStream) -> expand(args, item).unwrap_or_else(syn::Error::into_compile_error).into() } +mod sim_test; + +/// Run an `async fn` test to completion on `kio::clock::sim::run`. +#[proc_macro_attribute] +pub fn test(args: proc_macro::TokenStream, item: proc_macro::TokenStream) -> proc_macro::TokenStream { + sim_test::expand(args, item) +} + /// `self.: `. struct Args { field: Ident, diff --git a/rs/moq-clock/macros/src/lib.rs b/rs/kio/macros/src/sim_test.rs similarity index 63% rename from rs/moq-clock/macros/src/lib.rs rename to rs/kio/macros/src/sim_test.rs index 7afeb162d53..059763ce776 100644 --- a/rs/moq-clock/macros/src/lib.rs +++ b/rs/kio/macros/src/sim_test.rs @@ -1,14 +1,10 @@ -//! The `#[moq_clock::test]` attribute: an `async fn` test run on the simulator. -//! -//! Use it through `moq-clock`'s `sim` feature, which re-exports it. +//! The `#[kio::test]` expansion: the test body runs inside `kio::clock::sim::run`. use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; -/// Run an `async fn` test to completion on `moq_clock::sim::run`. -#[proc_macro_attribute] -pub fn test(args: TokenStream, item: TokenStream) -> TokenStream { +pub(crate) fn expand(args: TokenStream, item: TokenStream) -> TokenStream { if !args.is_empty() { - return error("#[moq_clock::test] takes no arguments"); + return error("#[kio::test] takes no arguments"); } let mut tokens: Vec = item.into_iter().collect(); @@ -17,17 +13,17 @@ pub fn test(args: TokenStream, item: TokenStream) -> TokenStream { .windows(2) .position(|pair| is(&pair[0], "async") && is(&pair[1], "fn")) else { - return error("#[moq_clock::test] expects an `async fn`"); + return error("#[kio::test] expects an `async fn`"); }; tokens.remove(at); let body = match tokens.pop() { Some(TokenTree::Group(body)) if body.delimiter() == Delimiter::Brace => body, - _ => return error("#[moq_clock::test] expects a function body"), + _ => return error("#[kio::test] expects a function body"), }; - // `{ ::moq_clock::sim::run(async move ) }` - let mut call: TokenStream = "::moq_clock::sim::run".parse().unwrap(); + // `{ ::kio::clock::sim::run(async move ) }` + let mut call: TokenStream = "::kio::clock::sim::run".parse().unwrap(); let block: TokenStream = [ TokenTree::Ident(Ident::new("async", Span::call_site())), TokenTree::Ident(Ident::new("move", Span::call_site())), diff --git a/rs/moq-clock/src/deadline.rs b/rs/kio/src/clock/deadline.rs similarity index 89% rename from rs/moq-clock/src/deadline.rs rename to rs/kio/src/clock/deadline.rs index c79d3da3002..da7727d7131 100644 --- a/rs/moq-clock/src/deadline.rs +++ b/rs/kio/src/clock/deadline.rs @@ -10,7 +10,7 @@ use std::{ time::Duration, }; -use crate::Instant; +use crate::clock::Instant; thread_local! { /// The queue [`Deadlines::enter`] made this thread's ambient clock. @@ -41,16 +41,16 @@ struct Queue { /// The clock installed where the queue was made, whose wall time it reads /// while entered, so its wall and instants come from one clock. #[cfg(feature = "manual")] - installed: Option, + installed: Option, } struct State { /// Orders deadlines armed for the same instant by when they were armed. next: u64, - armed: BTreeMap<(Instant, u64), Arc>>, + armed: BTreeMap<(Instant, u64), Arc>>, /// The owner's poll, woken when a deadline armed outside it becomes the earliest, /// so the owner never sleeps past a deadline it did not see. - owner: kio::WaiterList, + owner: crate::WaiterList, } impl Queue { @@ -67,10 +67,10 @@ impl Deadlines { state: Mutex::new(State { next: 0, armed: BTreeMap::new(), - owner: kio::WaiterList::new(), + owner: crate::WaiterList::new(), }), #[cfg(feature = "manual")] - installed: crate::installed::current(), + installed: crate::clock::installed::current(), })) } @@ -124,7 +124,7 @@ impl Deadlines { /// The earliest armed deadline, registering `waiter` to be woken when an earlier /// one is armed. Ends the poll [`Self::advance`] began: one lock, so a deadline /// armed elsewhere is either reported here or wakes the owner. - pub fn park(&self, waiter: &kio::Waiter) -> Option { + pub fn park(&self, waiter: &crate::Waiter) -> Option { let mut state = self.0.state.lock().unwrap(); waiter.register(&mut state.owner); state.armed.first_key_value().map(|((at, _), _)| *at) @@ -148,8 +148,8 @@ impl Deadlines { /// Make this queue the calling thread's ambient clock until the guard drops. /// - /// While entered, [`now`](crate::now) reads the instant last handed to - /// [`advance`](Self::advance), and [`sleep`](crate::sleep) and the other ambient + /// While entered, [`now`](crate::clock::now) reads the instant last handed to + /// [`advance`](Self::advance), and [`sleep`](crate::clock::sleep) and the other ambient /// timers arm [`Deadline`]s here. Wall time comes from the clock installed on the /// runtime the queue was made in, if any, and otherwise from the clock the thread /// would read. For a runtime that advances the queue from its own reading of the @@ -214,7 +214,7 @@ pub(crate) fn now() -> Option { /// The installed clock behind the queue entered on this thread, if any. #[cfg(feature = "manual")] -pub(crate) fn installed() -> Option { +pub(crate) fn installed() -> Option { ENTERED.with(|entered| entered.borrow().as_ref().and_then(|queue| queue.0.installed.clone())) } @@ -238,11 +238,11 @@ impl WeakDeadlines { } } -/// The [`Deadline`] behind an ambient [`Sleep`](crate::Sleep) on an entered queue, +/// The [`Deadline`] behind an ambient [`Sleep`](crate::clock::Sleep) on an entered queue, /// with the waiter its polls register. pub(crate) struct Timer { deadline: Deadline, - park: kio::Park, + park: crate::Park, } impl Timer { @@ -251,7 +251,7 @@ impl Timer { deadline.set(at); Self { deadline, - park: kio::Park::default(), + park: crate::Park::default(), } } @@ -275,7 +275,7 @@ pub struct Deadline { deadlines: Deadlines, key: Option<(Instant, u64)>, at: Option, - waiters: Arc>, + waiters: Arc>, } impl Deadline { @@ -285,7 +285,7 @@ impl Deadline { deadlines: deadlines.clone(), key: None, at: None, - waiters: Arc::new(Mutex::new(kio::WaiterList::new())), + waiters: Arc::new(Mutex::new(crate::WaiterList::new())), } } @@ -341,7 +341,7 @@ impl Deadline { /// `Ready` once the queue reaches the armed instant, registering `waiter` /// otherwise. Fused until re-armed; a disarmed deadline never fires. - pub fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> { + pub fn poll(&mut self, waiter: &crate::Waiter) -> Poll<()> { // Register under the queue's lock, so an `advance` past `at` either happened // first (and we see it) or wakes this registration. A disarmed deadline // registers too, so arming it for a reached instant wakes its poller. @@ -354,10 +354,10 @@ impl Deadline { } } -impl kio::Task for Deadline { +impl crate::Task for Deadline { type Output = (); - fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> { + fn poll(&mut self, waiter: &crate::Waiter) -> Poll<()> { self.poll(waiter) } } @@ -380,7 +380,7 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use super::*; - use crate::Manual; + use crate::clock::Manual; /// Counts wakes. struct Wakes { @@ -393,11 +393,11 @@ mod tests { } } - fn counter() -> (Arc, kio::Waiter) { + fn counter() -> (Arc, crate::Waiter) { let wakes = Arc::new(Wakes { count: AtomicUsize::new(0), }); - let waiter = kio::Waiter::new(std::task::Waker::from(wakes.clone())); + let waiter = crate::Waiter::new(std::task::Waker::from(wakes.clone())); (wakes, waiter) } @@ -409,13 +409,13 @@ mod tests { let mut deadline = Deadline::new(&deadlines); deadline.set(Some(at)); assert_eq!(deadlines.next(), Some(at)); - assert!(deadline.poll(&kio::Waiter::noop()).is_pending()); + assert!(deadline.poll(&crate::Waiter::noop()).is_pending()); clock.advance(Duration::from_secs(3)); deadlines.advance(clock.now()); - assert!(deadline.poll(&kio::Waiter::noop()).is_ready()); + assert!(deadline.poll(&crate::Waiter::noop()).is_ready()); assert!( - deadline.poll(&kio::Waiter::noop()).is_ready(), + deadline.poll(&crate::Waiter::noop()).is_ready(), "an elapsed deadline stays fused" ); assert_eq!(deadlines.next(), None); @@ -434,11 +434,11 @@ mod tests { clock.advance(Duration::from_secs(3600)); deadlines.advance(clock.now()); - assert!(disarmed.poll(&kio::Waiter::noop()).is_pending()); + assert!(disarmed.poll(&crate::Waiter::noop()).is_pending()); let mut unrepresentable = Deadline::after(&deadlines, Duration::MAX); assert_eq!(unrepresentable.deadline(), None); - assert!(unrepresentable.poll(&kio::Waiter::noop()).is_pending()); + assert!(unrepresentable.poll(&crate::Waiter::noop()).is_pending()); } #[test] @@ -456,17 +456,17 @@ mod tests { clock.advance(Duration::from_secs(1)); deadlines.advance(clock.now()); assert!( - deadline.poll(&kio::Waiter::noop()).is_pending(), + deadline.poll(&crate::Waiter::noop()).is_pending(), "the old instant is gone" ); clock.advance(Duration::from_secs(4)); deadlines.advance(clock.now()); - assert!(deadline.poll(&kio::Waiter::noop()).is_ready()); + assert!(deadline.poll(&crate::Waiter::noop()).is_ready()); deadline.set(Some(clock.now() + Duration::from_secs(1))); assert!( - deadline.poll(&kio::Waiter::noop()).is_pending(), + deadline.poll(&crate::Waiter::noop()).is_pending(), "an elapsed deadline re-arms" ); } @@ -479,9 +479,9 @@ mod tests { let mut deadline = Deadline::new(&deadlines); deadline.set(Some(clock.now() - Duration::from_secs(1))); - assert!(deadline.poll(&kio::Waiter::noop()).is_ready(), "in the past"); + assert!(deadline.poll(&crate::Waiter::noop()).is_ready(), "in the past"); deadline.set(Some(clock.now())); - assert!(deadline.poll(&kio::Waiter::noop()).is_ready(), "exactly now"); + assert!(deadline.poll(&crate::Waiter::noop()).is_ready(), "exactly now"); assert_eq!(deadlines.next(), None, "neither was queued"); } @@ -548,7 +548,7 @@ mod tests { } } // Kept alive: a list holds its waiters weakly. - let waiter = |name| kio::Waiter::new(std::task::Waker::from(Arc::new(Record(order.clone(), name)))); + let waiter = |name| crate::Waiter::new(std::task::Waker::from(Arc::new(Record(order.clone(), name)))); let (first_waiter, second_waiter) = (waiter("first"), waiter("second")); assert!(first.poll(&first_waiter).is_pending()); assert!(second.poll(&second_waiter).is_pending()); @@ -582,10 +582,10 @@ mod tests { let deadlines = Deadlines::new(start); // A child that re-arms its deadline every time it fires, like a periodic probe. - let mut tasks = kio::Tasks::new(); + let mut tasks = crate::Tasks::new(); let mut tick = Deadline::after(&deadlines, PERIOD); let ticking = deadlines.clone(); - tasks.push(move |waiter: &kio::Waiter| { + tasks.push(move |waiter: &crate::Waiter| { while tick.poll(waiter).is_ready() { tick.set(Some(ticking.now() + PERIOD)); } @@ -595,7 +595,7 @@ mod tests { // `poll(now, waiter)`, minus the protocol. let now = std::cell::Cell::new(start); let next = std::cell::Cell::new(None); - let mut owner = std::pin::pin!(kio::wait(|waiter: &kio::Waiter| { + let mut owner = std::pin::pin!(crate::wait(|waiter: &crate::Waiter| { waiter.batch(|| { deadlines.advance(now.get()); let _ = tasks.poll(waiter); @@ -649,9 +649,9 @@ mod tests { let start = Instant::ZERO + Duration::from_secs(10); let deadlines = Deadlines::new(start); let entered = deadlines.enter(); - assert_eq!(crate::now(), start); + assert_eq!(crate::clock::now(), start); - let mut sleep = std::pin::pin!(crate::sleep(Duration::from_secs(1))); + let mut sleep = std::pin::pin!(crate::clock::sleep(Duration::from_secs(1))); assert_eq!(deadlines.next(), Some(start + Duration::from_secs(1))); let (wakes, waiter) = counter(); let waker = waiter.waker().clone(); @@ -659,14 +659,17 @@ mod tests { assert!(sleep.as_mut().poll(&mut cx).is_pending()); deadlines.advance(start + Duration::from_millis(999)); - assert_eq!(crate::now(), start + Duration::from_millis(999)); + assert_eq!(crate::clock::now(), start + Duration::from_millis(999)); assert_eq!(wakes.count.load(Ordering::SeqCst), 0); deadlines.advance(start + Duration::from_secs(1)); assert_eq!(wakes.count.load(Ordering::SeqCst), 1, "the sleep was not woken"); assert!(sleep.as_mut().poll(&mut cx).is_ready()); drop(entered); - assert!(crate::now() > start + Duration::from_secs(1), "the host clock is back"); + assert!( + crate::clock::now() > start + Duration::from_secs(1), + "the host clock is back" + ); } /// A sleep that never fires leaves nothing armed for the queue's owner to park on. @@ -674,7 +677,7 @@ mod tests { fn a_never_firing_sleep_arms_nothing() { let deadlines = Deadlines::new(Instant::ZERO); let _entered = deadlines.enter(); - let mut sleep = crate::sleep(Duration::MAX); + let mut sleep = crate::clock::sleep(Duration::MAX); assert_eq!(deadlines.next(), None); sleep.reset(Instant::ZERO + Duration::from_secs(1)); assert_eq!(deadlines.next(), Some(Instant::ZERO + Duration::from_secs(1))); @@ -688,12 +691,12 @@ mod tests { let _outer = outer.enter(); { let _inner = inner.enter(); - assert_eq!(crate::now(), Instant::ZERO + Duration::from_secs(2)); + assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(2)); } - assert_eq!(crate::now(), Instant::ZERO + Duration::from_secs(1)); + assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(1)); std::thread::spawn(|| { assert!( - crate::now() > Instant::ZERO + Duration::from_secs(2), + crate::clock::now() > Instant::ZERO + Duration::from_secs(2), "other threads keep their own clock" ) }) @@ -727,7 +730,7 @@ mod tests { assert!(result.is_err(), "the out-of-order drop did not panic"); assert!(super::entered().is_none(), "a dropped queue is still the ambient clock"); assert!( - crate::now() > Instant::ZERO + Duration::from_secs(2), + crate::clock::now() > Instant::ZERO + Duration::from_secs(2), "the host clock is back" ); } diff --git a/rs/moq-clock/src/installed.rs b/rs/kio/src/clock/installed.rs similarity index 89% rename from rs/moq-clock/src/installed.rs rename to rs/kio/src/clock/installed.rs index ceefe1f535b..f4757354e44 100644 --- a/rs/moq-clock/src/installed.rs +++ b/rs/kio/src/clock/installed.rs @@ -14,7 +14,7 @@ use std::{ time::Duration, }; -use crate::{Instant, Manual, Wall}; +use crate::clock::{Instant, Manual, Wall}; /// Installed clocks by runtime. Never pruned: one entry per runtime a test installs on. static CLOCKS: LazyLock>> = LazyLock::new(Default::default); @@ -23,8 +23,8 @@ static ANY: AtomicBool = AtomicBool::new(false); /// A [`Manual`] clock that one tokio runtime reads as its ambient clock. /// -/// Inside that runtime, or a thread that entered it, [`now`](crate::now) and -/// [`wall`](crate::wall) read this clock and timers fire only once +/// Inside that runtime, or a thread that entered it, [`now`](crate::clock::now) and +/// [`wall`](crate::clock::wall) read this clock and timers fire only once /// [`advance`](Self::advance) reaches them. Clones share the clock. #[derive(Clone)] pub struct Installed(Arc>); @@ -77,8 +77,8 @@ impl Installed { } /// Complete once this clock reaches `at`, whichever thread polls it. - pub fn sleep_until(&self, at: Instant) -> crate::Sleep { - crate::Sleep::installed(self.clone(), at) + pub fn sleep_until(&self, at: Instant) -> crate::clock::Sleep { + crate::clock::Sleep::installed(self.clone(), at) } /// The current instant. @@ -225,9 +225,9 @@ mod tests { let runtime = runtime(true); let clock = Manual::new().install(runtime.handle()); runtime.block_on(async { - let start = crate::now(); + let start = crate::clock::now(); assert_eq!(start, Instant::ZERO); - let mut sleep = pin!(crate::sleep(Duration::from_secs(1))); + let mut sleep = pin!(crate::clock::sleep(Duration::from_secs(1))); assert!(poll_once(&mut sleep).is_pending()); // Idle on tokio's paused clock for an hour: the installed clock stays put. @@ -236,14 +236,14 @@ mod tests { reason = "the test idles on tokio's clock, not the installed one" )] tokio::time::sleep(Duration::from_secs(3_600)).await; - assert_eq!(crate::now(), start); + assert_eq!(crate::clock::now(), start); assert!(poll_once(&mut sleep).is_pending()); clock.advance(Duration::from_millis(999)); assert!(poll_once(&mut sleep).is_pending()); clock.advance(Duration::from_millis(1)); sleep.await; - assert_eq!(crate::now(), start + Duration::from_secs(1)); + assert_eq!(crate::clock::now(), start + Duration::from_secs(1)); }); } @@ -258,10 +258,10 @@ mod tests { let clock = Manual::new().install(runtime.handle()); let (armed, armed_rx) = std::sync::mpsc::channel(); let task = runtime.spawn(async move { - let sleep = crate::sleep(Duration::from_secs(5)); + let sleep = crate::clock::sleep(Duration::from_secs(5)); armed.send(()).unwrap(); sleep.await; - crate::now() + crate::clock::now() }); armed_rx.recv().unwrap(); clock.advance(Duration::from_secs(5)); @@ -274,7 +274,7 @@ mod tests { let runtime = runtime(false); let clock = Manual::new().install(runtime.handle()); runtime.block_on(async { - let mut sleep = pin!(crate::sleep(Duration::from_secs(1))); + let mut sleep = pin!(crate::clock::sleep(Duration::from_secs(1))); assert!(poll_once(&mut sleep).is_pending()); sleep.as_mut().reset(Instant::ZERO + Duration::from_secs(2)); clock.advance(Duration::from_secs(1)); @@ -290,16 +290,16 @@ mod tests { let runtime = runtime(false); let clock = Manual::new().install(runtime.handle()); let _entered = runtime.enter(); - assert_eq!(crate::wall(), Manual::WALL_START); - assert_eq!(crate::origin(), (Instant::ZERO, Manual::WALL_START)); + assert_eq!(crate::clock::wall(), Manual::WALL_START); + assert_eq!(crate::clock::origin(), (Instant::ZERO, Manual::WALL_START)); clock.advance(Duration::from_secs(5)); - assert_eq!(crate::wall(), Manual::WALL_START + Duration::from_secs(5)); + assert_eq!(crate::clock::wall(), Manual::WALL_START + Duration::from_secs(5)); clock.step_wall(Manual::WALL_START); - assert_eq!(crate::wall(), Manual::WALL_START); - assert_eq!(crate::now(), Instant::ZERO + Duration::from_secs(5)); + assert_eq!(crate::clock::wall(), Manual::WALL_START); + assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(5)); assert_eq!( - crate::origin(), + crate::clock::origin(), (Instant::ZERO, Manual::WALL_START), "the origin is fixed at its first read" ); @@ -313,9 +313,9 @@ mod tests { let other = runtime(false); // The host clock reads far past zero from its first instant. let host = Instant::ZERO + Duration::from_secs(1 << 31); - assert!(other.block_on(async { crate::now() }) > host); - assert!(crate::now() > host); - assert_eq!(installed.block_on(async { crate::now() }), Instant::ZERO); + assert!(other.block_on(async { crate::clock::now() }) > host); + assert!(crate::clock::now() > host); + assert_eq!(installed.block_on(async { crate::clock::now() }), Instant::ZERO); } /// An advance past the range is refused whole, leaving the clock where it was. diff --git a/rs/moq-clock/src/instant.rs b/rs/kio/src/clock/instant.rs similarity index 97% rename from rs/moq-clock/src/instant.rs rename to rs/kio/src/clock/instant.rs index 4da7389b6e6..61da59cc88b 100644 --- a/rs/moq-clock/src/instant.rs +++ b/rs/kio/src/clock/instant.rs @@ -24,7 +24,7 @@ impl Instant { /// The current instant on the ambient clock. pub fn now() -> Self { - crate::now() + crate::clock::now() } /// The time elapsed since this instant on the ambient clock, zero if it is in the future. @@ -90,14 +90,14 @@ impl Instant { /// When std's clock cannot represent it, as with a simulated instant near zero /// on a platform whose std clock starts at boot. pub fn into_std(self) -> std::time::Instant { - crate::runtime::into_std(self).expect("instant outside std's clock range") + crate::clock::runtime::into_std(self).expect("instant outside std's clock range") } /// The instant `at` names on std's clock, the inverse of [`Instant::into_std`]. /// /// Saturates at the clock's range, like a deadline past it. pub fn from_std(at: std::time::Instant) -> Self { - crate::runtime::from_std(at) + crate::clock::runtime::from_std(at) } } diff --git a/rs/moq-clock/src/manual.rs b/rs/kio/src/clock/manual.rs similarity index 98% rename from rs/moq-clock/src/manual.rs rename to rs/kio/src/clock/manual.rs index bd770d33636..5985f0e6311 100644 --- a/rs/moq-clock/src/manual.rs +++ b/rs/kio/src/clock/manual.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use crate::{Instant, Wall}; +use crate::clock::{Instant, Wall}; /// A clock that moves only when a test moves it. /// diff --git a/rs/moq-clock/src/lib.rs b/rs/kio/src/clock/mod.rs similarity index 83% rename from rs/moq-clock/src/lib.rs rename to rs/kio/src/clock/mod.rs index 05789aabef4..aa89aa7a60b 100644 --- a/rs/moq-clock/src/lib.rs +++ b/rs/kio/src/clock/mod.rs @@ -1,4 +1,4 @@ -//! One clock for Media over QUIC. +//! One clock: logical instants, wall time, deadlines, timers, and a deterministic simulator. //! //! - [`Instant`] is a logical point on the monotonic clock, in nanoseconds from //! the clock's origin, with [`std::time::Instant`]'s methods. [`Wall`] is @@ -9,25 +9,25 @@ //! [`Manual`] clock. //! - Async code reads the ambient clock: [`now`], [`wall`], [`sleep`], //! [`sleep_until`], [`timeout`], [`interval`], and [`drive`] resolve to the -//! current runtime's clock. That is tokio's (paused tokio included) on native, -//! `performance.now()` and `setTimeout` in the browser, the simulator inside -//! `sim::run`, and a [`Deadlines`] queue on a thread that [entered](Deadlines::enter) -//! it, which is how a runtime that reads the host clock itself (an io_uring -//! worker) becomes a backend. +//! current runtime's clock. That is tokio's (paused tokio included), the +//! simulator inside `sim::run`, and a [`Deadlines`] queue on a thread that +//! [entered](Deadlines::enter) it, which is how a runtime that reads the host +//! clock itself (an io_uring worker) becomes a backend. +//! +//! The `runtime` feature arms timers on tokio's clock. Without it, reads fall back +//! to std, and waiting on the host clock panics. //! //! The `manual` feature adds `Manual::install`, which makes a [`Manual`] clock //! the ambient clock of one tokio runtime. It moves only when told to, never on //! idle, so a test harness outside the runtime decides when native time passes. //! //! The `sim` feature adds the `sim` module, a deterministic executor whose clock -//! starts at [`Instant::ZERO`], and the `#[moq_clock::test]` attribute that runs an +//! starts at [`Instant::ZERO`], and the `#[kio::test]` attribute that runs an //! `async fn` test on it. Enable it for dev-dependencies only. //! //! The `serde` feature adds `serde::UnixSeconds`, matching existing integer //! Unix-second JSON encodings for wall times. -#![warn(missing_docs)] - mod deadline; #[cfg(feature = "manual")] mod installed; @@ -52,14 +52,6 @@ pub use timer::{ }; pub use wall::{OutOfRange, Wall}; -/// Run an `async fn` test to completion on [`sim::run`]. -#[cfg(feature = "sim")] -pub use moq_clock_macros::test; - -// So `#[moq_clock::test]` resolves inside this crate's own tests. -#[cfg(test)] -extern crate self as moq_clock; - /// The current instant on the ambient clock. pub fn now() -> Instant { if let Some(now) = deadline::now() { diff --git a/rs/moq-clock/src/runtime.rs b/rs/kio/src/clock/runtime.rs similarity index 86% rename from rs/moq-clock/src/runtime.rs rename to rs/kio/src/clock/runtime.rs index 10a63bb8632..a4fc3fb7144 100644 --- a/rs/moq-clock/src/runtime.rs +++ b/rs/kio/src/clock/runtime.rs @@ -14,7 +14,7 @@ use std::{ #[cfg(feature = "runtime")] use tokio::time as host; -use crate::{Instant, Wall}; +use crate::clock::{Instant, Wall}; /// How far past [`Instant::ZERO`] a runtime clock reads at its origin. /// @@ -160,15 +160,15 @@ pub(crate) struct Timer; #[cfg(not(feature = "runtime"))] impl Timer { pub(crate) fn new(_: Instant) -> Self { - panic!("moq-clock runtime support is disabled") + panic!("the kio `runtime` feature is disabled") } pub(crate) fn reset(&mut self, _: Instant) { - panic!("moq-clock runtime support is disabled") + panic!("the kio `runtime` feature is disabled") } pub(crate) fn poll(&mut self, _: &mut Context<'_>) -> Poll<()> { - panic!("moq-clock runtime support is disabled") + panic!("the kio `runtime` feature is disabled") } } @@ -183,7 +183,7 @@ mod paused { }; use super::host; - use crate::{Instant, Wall}; + use crate::clock::{Instant, Wall}; /// A paused runtime counting from its own origin. struct Own { @@ -255,17 +255,17 @@ mod tests { .start_paused(true) .build() .unwrap(); - let _ = crate::now(); + let _ = crate::clock::now(); runtime.block_on(async { - let start = crate::now(); - crate::sleep(Duration::from_secs(5)).await; - assert_eq!(crate::now(), start + Duration::from_secs(5)); + let start = crate::clock::now(); + crate::clock::sleep(Duration::from_secs(5)).await; + assert_eq!(crate::clock::now(), start + Duration::from_secs(5)); tokio::time::advance(Duration::from_secs(60)).await; - assert_eq!(crate::now(), start + Duration::from_secs(65)); - let at = crate::sleep_until(start + Duration::from_secs(70)); + assert_eq!(crate::clock::now(), start + Duration::from_secs(65)); + let at = crate::clock::sleep_until(start + Duration::from_secs(70)); assert_eq!(at.deadline(), start + Duration::from_secs(70)); at.await; - assert_eq!(crate::now(), start + Duration::from_secs(70)); + assert_eq!(crate::clock::now(), start + Duration::from_secs(70)); }); } @@ -284,15 +284,15 @@ mod tests { // from its own origin. let first = paused(); let second = paused(); - let _ = crate::now(); + let _ = crate::clock::now(); first.block_on(async { - let _ = crate::now(); + let _ = crate::clock::now(); tokio::time::advance(Duration::from_secs(60)).await; - let _ = crate::origin(); + let _ = crate::clock::origin(); }); second.block_on(async { - let (instant, _) = crate::origin(); - assert_eq!(instant, crate::now()); + let (instant, _) = crate::clock::origin(); + assert_eq!(instant, crate::clock::now()); }); } @@ -300,7 +300,7 @@ mod tests { /// callers by advancing its clock before the anchor is first taken. #[test] fn a_later_paused_runtime_does_not_skew_the_anchor() { - let _ = crate::now(); + let _ = crate::clock::now(); // Built after the origin, so it counts from the shared origin. let runtime = tokio::runtime::Builder::new_current_thread() .enable_time() @@ -308,12 +308,16 @@ mod tests { .build() .unwrap(); runtime.block_on(async { - let _ = crate::now(); + let _ = crate::clock::now(); tokio::time::advance(Duration::from_secs(3_600)).await; - let _ = crate::origin(); + let _ = crate::clock::origin(); }); - let (instant, _) = crate::origin(); - assert!(instant <= crate::now(), "{instant:?} > {:?}", crate::now()); + let (instant, _) = crate::clock::origin(); + assert!( + instant <= crate::clock::now(), + "{instant:?} > {:?}", + crate::clock::now() + ); } /// On a running clock, a converted instant is the same moment on std's clock. @@ -321,13 +325,13 @@ mod tests { #[expect(clippy::disallowed_methods, reason = "the test compares against std's clock")] fn std_conversion_is_exact_on_a_running_clock() { let before = std::time::Instant::now(); - let now = crate::now(); + let now = crate::clock::now(); let after = std::time::Instant::now(); let host = now.into_std(); assert!(before <= host && host <= after, "{before:?} <= {host:?} <= {after:?}"); - assert_eq!(crate::Instant::from_std(host), now); + assert_eq!(crate::clock::Instant::from_std(host), now); let earlier = now - Duration::from_secs(3_600); - assert_eq!(crate::Instant::from_std(earlier.into_std()), earlier); + assert_eq!(crate::clock::Instant::from_std(earlier.into_std()), earlier); } /// On paused tokio, converted instants keep the time between them. @@ -339,13 +343,13 @@ mod tests { .build() .unwrap(); runtime.block_on(async { - let start = crate::now(); + let start = crate::clock::now(); let host = start.into_std(); tokio::time::advance(Duration::from_secs(60)).await; - let later = crate::now(); + let later = crate::clock::now(); assert_eq!(later.into_std() - host, Duration::from_secs(60)); assert_eq!( - crate::Instant::from_std(host + Duration::from_secs(5)), + crate::clock::Instant::from_std(host + Duration::from_secs(5)), start + Duration::from_secs(5) ); }); @@ -354,9 +358,9 @@ mod tests { /// A std instant past the clock's range saturates instead of wrapping. #[test] fn std_conversion_saturates() { - let now = crate::now(); + let now = crate::clock::now(); let far = now.into_std() + Duration::from_secs(1 << 40); - assert!(crate::Instant::from_std(far) > now + Duration::from_secs(1 << 33)); + assert!(crate::clock::Instant::from_std(far) > now + Duration::from_secs(1 << 33)); } /// A fresh clock names moments before the process started, as std's does, so @@ -369,10 +373,10 @@ mod tests { .build() .unwrap(); runtime.block_on(async { - let now = crate::now(); + let now = crate::clock::now(); assert!(now.checked_sub(Duration::from_secs(3_600)).is_some(), "{now:?}"); }); - assert!(crate::now().checked_sub(Duration::from_secs(3_600)).is_some()); + assert!(crate::clock::now().checked_sub(Duration::from_secs(3_600)).is_some()); } /// Every worker of a multi-thread runtime, and a thread outside any runtime, @@ -384,16 +388,16 @@ mod tests { .enable_time() .build() .unwrap(); - let before = crate::now(); + let before = crate::clock::now(); let reads = runtime.block_on(async { - let tasks: Vec<_> = (0..16).map(|_| tokio::spawn(async { crate::now() })).collect(); + let tasks: Vec<_> = (0..16).map(|_| tokio::spawn(async { crate::clock::now() })).collect(); let mut reads = Vec::new(); for task in tasks { reads.push(task.await.unwrap()); } reads }); - let after = crate::now(); + let after = crate::clock::now(); for read in reads { assert!(before <= read && read <= after, "{before:?} <= {read:?} <= {after:?}"); } diff --git a/rs/moq-clock/src/serde.rs b/rs/kio/src/clock/serde.rs similarity index 99% rename from rs/moq-clock/src/serde.rs rename to rs/kio/src/clock/serde.rs index e46487a2279..61dc3bf8bbd 100644 --- a/rs/moq-clock/src/serde.rs +++ b/rs/kio/src/clock/serde.rs @@ -1,6 +1,6 @@ //! JSON adapters that preserve existing wall-time encodings. -use crate::Wall; +use crate::clock::Wall; use ::serde::{Deserialize, Deserializer, Serializer}; use serde_with::{DeserializeAs, SerializeAs, TimestampSeconds}; diff --git a/rs/moq-clock/src/sim.rs b/rs/kio/src/clock/sim.rs similarity index 83% rename from rs/moq-clock/src/sim.rs rename to rs/kio/src/clock/sim.rs index de84bb0d84b..abe3374d67c 100644 --- a/rs/moq-clock/src/sim.rs +++ b/rs/kio/src/clock/sim.rs @@ -1,9 +1,9 @@ //! A single-threaded, deterministic executor with simulated time. //! -//! Inside [`run`], the ambient clock is the simulator's: [`now`](crate::now) starts -//! at [`Instant::ZERO`], [`wall`](crate::wall) at [`Manual::WALL_START`], and -//! [`sleep`](crate::sleep), [`timeout`](crate::timeout), and -//! [`interval`](crate::interval) arm simulated timers. Time never moves on its own: +//! Inside [`run`], the ambient clock is the simulator's: [`now`](crate::clock::now) starts +//! at [`Instant::ZERO`], [`wall`](crate::clock::wall) at [`Manual::WALL_START`], and +//! [`sleep`](crate::clock::sleep), [`timeout`](crate::clock::timeout), and +//! [`interval`](crate::clock::interval) arm simulated timers. Time never moves on its own: //! once every task has stalled, [`run`] jumps the clock to the earliest armed //! timer and wakes it, like tokio's paused clock, so a test never waits on the //! host clock. A run whose tasks are all parked with nothing armed can never @@ -12,10 +12,10 @@ //! //! A task poll that makes more than 4096 ready kio polls panics with the caller's //! source location, so a loop that forgets to yield fails instead of starving its siblings. -//! Each `kio::Tasks` child poll counts on its own, like a spawned task. +//! Each `crate::Tasks` child poll counts on its own, like a spawned task. //! //! Caller-driven state machines take time from their caller: -//! [`drive`](crate::drive) polls one with the simulated instant, and [`attach`] +//! [`drive`](crate::clock::drive) polls one with the simulated instant, and [`attach`] //! keeps a [`Deadlines`] queue in step. use std::{ @@ -34,7 +34,7 @@ use std::{ use futures::{FutureExt, StreamExt, stream::FuturesUnordered}; -use crate::{Deadlines, Instant, Manual, Wall, deadline::WeakDeadlines}; +use crate::clock::{Deadlines, Instant, Manual, Wall, deadline::WeakDeadlines}; thread_local! { static CURRENT: RefCell>> = const { RefCell::new(None) }; @@ -43,7 +43,7 @@ thread_local! { type Task = Pin>>; fn poll(future: Pin<&mut F>, cx: &mut Context<'_>) -> Poll { - let _scope = kio::coop::scope(); + let _scope = crate::coop::scope(); future.poll(cx) } @@ -84,7 +84,7 @@ impl Runtime { }); CURRENT.with(|current| { let mut current = current.borrow_mut(); - assert!(current.is_none(), "moq_clock::sim::run cannot nest"); + assert!(current.is_none(), "kio::clock::sim::run cannot nest"); *current = Some(runtime.clone()); }); runtime @@ -161,7 +161,7 @@ fn current() -> Option> { } fn expect_current() -> Rc { - current().expect("not inside moq_clock::sim::run") + current().expect("not inside kio::clock::sim::run") } /// The simulated instant, when the calling thread is inside [`run`]. @@ -344,10 +344,10 @@ pub fn yield_now() -> impl Future { }) } -/// A simulated timer behind [`Sleep`](crate::Sleep). +/// A simulated timer behind [`Sleep`](crate::clock::Sleep). /// /// Holds plain data rather than the runtime, so enabling `sim` in a test build -/// leaves [`Sleep`](crate::Sleep) `Send`. It finds its run as the thread's current one. +/// leaves [`Sleep`](crate::clock::Sleep) `Send`. It finds its run as the thread's current one. pub(crate) struct Timer { run: u64, at: Instant, @@ -388,7 +388,7 @@ impl Timer { pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<()> { let runtime = self .runtime() - .expect("a simulated sleep polled outside its moq_clock::sim::run"); + .expect("a simulated sleep polled outside its kio::clock::sim::run"); let mut time = runtime.time.borrow_mut(); if time.clock.now() >= self.at { if let Some(key) = self.key.take() { @@ -594,12 +594,12 @@ impl Drop for Cancel { #[cfg(test)] mod tests { use super::*; - use crate::{Deadline, Deadlines, Elapsed, MissedTickBehavior}; + use crate::clock::{Deadline, Deadlines, Elapsed, MissedTickBehavior}; fn spin() { - let producer = kio::Producer::new(()); + let producer = crate::Producer::new(()); let consumer = producer.consume(); - let waiter = kio::Waiter::noop(); + let waiter = crate::Waiter::noop(); for _ in 0..10_000 { assert!(consumer.poll(&waiter, |_| Poll::Ready(())).is_ready()); } @@ -629,13 +629,13 @@ mod tests { turns.set(turns.get() + 1); } }); - let producer = kio::Producer::new(()); + let producer = crate::Producer::new(()); let consumer = producer.consume(); - let mut budget = kio::coop::Budget::new(32); + let mut budget = crate::coop::Budget::new(32); for _ in 0..10_000 { - kio::wait(|waiter| budget.poll_yield(waiter)).await; + crate::wait(|waiter| budget.poll_yield(waiter)).await; assert!( - kio::wait(|waiter| consumer.poll(waiter, |_| Poll::Ready(()))) + crate::wait(|waiter| consumer.poll(waiter, |_| Poll::Ready(()))) .await .is_ok() ); @@ -646,9 +646,9 @@ mod tests { #[crate::test] async fn pending_polls_do_not_count_as_work() { - let producer = kio::Producer::new(()); + let producer = crate::Producer::new(()); let consumer = producer.consume(); - let waiter = kio::Waiter::noop(); + let waiter = crate::Waiter::noop(); for _ in 0..10_000 { assert!(consumer.poll(&waiter, |_| Poll::<()>::Pending).is_pending()); } @@ -663,36 +663,36 @@ mod tests { #[crate::test] async fn a_large_task_set_counts_each_child_alone() { - let producer = kio::Producer::new(()); - let mut tasks = kio::Tasks::new(); + let producer = crate::Producer::new(()); + let mut tasks = crate::Tasks::new(); for _ in 0..10_000 { let consumer = producer.consume(); - tasks.push(move |waiter: &kio::Waiter| consumer.poll(waiter, |_| Poll::Ready(())).map(drop)); + tasks.push(move |waiter: &crate::Waiter| consumer.poll(waiter, |_| Poll::Ready(())).map(drop)); } - kio::wait(|waiter| tasks.poll(waiter)).await; + crate::wait(|waiter| tasks.poll(waiter)).await; } #[test] #[should_panic(expected = "kio Ready poll limit")] fn a_spinning_task_set_child_fails() { run(async { - let mut tasks = kio::Tasks::new(); - tasks.push(|_: &kio::Waiter| { + let mut tasks = crate::Tasks::new(); + tasks.push(|_: &crate::Waiter| { spin(); Poll::Ready(()) }); - kio::wait(|waiter| tasks.poll(waiter)).await; + crate::wait(|waiter| tasks.poll(waiter)).await; }); } #[test] fn a_task_set_outside_the_simulator_counts_nothing() { - let mut tasks = kio::Tasks::new(); - tasks.push(|_: &kio::Waiter| { + let mut tasks = crate::Tasks::new(); + tasks.push(|_: &crate::Waiter| { spin(); Poll::Ready(()) }); - assert!(tasks.poll(&kio::Waiter::noop()).is_ready()); + assert!(tasks.poll(&crate::Waiter::noop()).is_ready()); } fn at(secs: u64) -> Instant { @@ -739,8 +739,8 @@ mod tests { #[crate::test] async fn starts_at_zero() { - assert_eq!(crate::now(), Instant::ZERO); - assert_eq!(crate::wall(), Manual::WALL_START); + assert_eq!(crate::clock::now(), Instant::ZERO); + assert_eq!(crate::clock::wall(), Manual::WALL_START); } #[test] @@ -750,13 +750,13 @@ mod tests { for secs in [1, 5, 3] { let fired = fired.clone(); drop(spawn(async move { - crate::sleep(Duration::from_secs(secs)).await; + crate::clock::sleep(Duration::from_secs(secs)).await; fired.set(fired.get() + 1); })); } idle().await; assert_eq!(fired.get(), 3); - assert_eq!(crate::now(), at(5)); + assert_eq!(crate::clock::now(), at(5)); }); } @@ -764,18 +764,18 @@ mod tests { fn time_moves_only_when_every_task_stalls() { run(async { let a = spawn(async { - crate::sleep(Duration::from_secs(5)).await; - crate::now() + crate::clock::sleep(Duration::from_secs(5)).await; + crate::clock::now() }); let b = spawn(async { - crate::sleep(Duration::from_secs(2)).await; - crate::now() + crate::clock::sleep(Duration::from_secs(2)).await; + crate::clock::now() }); - assert_eq!(crate::now(), Instant::ZERO, "spawning does not move time"); + assert_eq!(crate::clock::now(), Instant::ZERO, "spawning does not move time"); assert_eq!(b.await.unwrap(), at(2)); assert_eq!(a.await.unwrap(), at(5)); assert_eq!( - crate::wall(), + crate::clock::wall(), Manual::WALL_START + Duration::from_secs(5), "wall time moved too" ); @@ -784,39 +784,39 @@ mod tests { #[crate::test] async fn timeout_uses_simulated_time() { - let slow = crate::timeout(Duration::from_secs(1), crate::sleep(Duration::from_secs(60))).await; + let slow = crate::clock::timeout(Duration::from_secs(1), crate::clock::sleep(Duration::from_secs(60))).await; assert_eq!(slow.unwrap_err(), Elapsed); - assert_eq!(crate::now(), at(1)); - let fast = crate::timeout(Duration::from_secs(60), async { 7 }).await; + assert_eq!(crate::clock::now(), at(1)); + let fast = crate::clock::timeout(Duration::from_secs(60), async { 7 }).await; assert_eq!(fast, Ok(7)); } #[crate::test] async fn timeout_at_ends_at_the_deadline() { - let slow = crate::timeout_at(at(2), crate::sleep(Duration::from_secs(60))).await; + let slow = crate::clock::timeout_at(at(2), crate::clock::sleep(Duration::from_secs(60))).await; assert_eq!(slow.unwrap_err(), Elapsed); - assert_eq!(crate::now(), at(2)); - let late = crate::timeout_at(at(1), async { 7 }).await; + assert_eq!(crate::clock::now(), at(2)); + let late = crate::clock::timeout_at(at(1), async { 7 }).await; assert_eq!(late, Ok(7), "a ready future wins even past the deadline"); } #[crate::test] async fn advance_wakes_due_timers() { - let timer = spawn(crate::sleep(Duration::from_secs(3))); + let timer = spawn(crate::clock::sleep(Duration::from_secs(3))); yield_now().await; advance(Duration::from_secs(3)).await; assert!(timer.is_finished()); - assert_eq!(crate::now(), at(3)); + assert_eq!(crate::clock::now(), at(3)); } #[crate::test] async fn a_wall_step_passes_no_time() { advance(Duration::from_secs(10)).await; step_wall(Manual::WALL_START + Duration::from_secs(4)); - assert_eq!(crate::now(), at(10), "a step back passes no time"); - assert_eq!(crate::wall(), Manual::WALL_START + Duration::from_secs(4)); + assert_eq!(crate::clock::now(), at(10), "a step back passes no time"); + assert_eq!(crate::clock::wall(), Manual::WALL_START + Duration::from_secs(4)); advance(Duration::from_secs(1)).await; - assert_eq!(crate::wall(), Manual::WALL_START + Duration::from_secs(5)); + assert_eq!(crate::clock::wall(), Manual::WALL_START + Duration::from_secs(5)); } #[crate::test] @@ -825,7 +825,7 @@ mod tests { let task = spawn({ let fired = fired.clone(); async move { - crate::sleep(Duration::from_secs(1)).await; + crate::clock::sleep(Duration::from_secs(1)).await; fired.set(true); } }); @@ -833,29 +833,29 @@ mod tests { task.abort(); assert!(task.await.unwrap_err().is_cancelled()); // Nothing else is armed: a dropped sleep left no timer behind, so time jumps here. - crate::sleep(Duration::from_secs(5)).await; + crate::clock::sleep(Duration::from_secs(5)).await; assert!(!fired.get()); - assert_eq!(crate::now(), at(5)); + assert_eq!(crate::clock::now(), at(5)); } #[crate::test] async fn rearming() { - let mut sleep = crate::sleep(Duration::from_secs(1)); + let mut sleep = crate::clock::sleep(Duration::from_secs(1)); sleep.reset(at(3)); (&mut sleep).await; - assert_eq!(crate::now(), at(3), "the old instant is gone"); + assert_eq!(crate::clock::now(), at(3), "the old instant is gone"); sleep.reset(at(4)); sleep.await; - assert_eq!(crate::now(), at(4), "a completed sleep re-arms"); + assert_eq!(crate::clock::now(), at(4), "a completed sleep re-arms"); } #[crate::test] async fn an_expired_deadline_fires_at_once() { advance(Duration::from_secs(10)).await; - crate::sleep_until(at(5)).await; - crate::sleep_until(at(10)).await; - crate::sleep(Duration::ZERO).await; - assert_eq!(crate::now(), at(10)); + crate::clock::sleep_until(at(5)).await; + crate::clock::sleep_until(at(10)).await; + crate::clock::sleep(Duration::ZERO).await; + assert_eq!(crate::clock::now(), at(10)); } #[crate::test] @@ -863,9 +863,9 @@ mod tests { let order = Rc::new(RefCell::new(Vec::new())); // Created in one order; a sleep arms on its first poll, so spawning them in // the other order arms them in that order. - let first = crate::sleep_until(at(1)); - let second = crate::sleep_until(at(1)); - let record = |name: &'static str, sleep: crate::Sleep| { + let first = crate::clock::sleep_until(at(1)); + let second = crate::clock::sleep_until(at(1)); + let record = |name: &'static str, sleep: crate::clock::Sleep| { let order = order.clone(); spawn(async move { sleep.await; @@ -881,32 +881,32 @@ mod tests { #[crate::test] async fn interval_bursts_missed_ticks_by_default() { - let mut ticks = crate::interval(Duration::from_secs(1)); + let mut ticks = crate::clock::interval(Duration::from_secs(1)); assert_eq!(ticks.tick().await, at(0), "the first tick is immediate"); advance(Duration::from_millis(3500)).await; assert_eq!(ticks.tick().await, at(1)); assert_eq!(ticks.tick().await, at(2)); assert_eq!(ticks.tick().await, at(3)); assert_eq!( - crate::now(), + crate::clock::now(), Instant::ZERO + Duration::from_millis(3500), "caught up at once" ); assert_eq!(ticks.tick().await, at(4)); - assert_eq!(crate::now(), at(4)); + assert_eq!(crate::clock::now(), at(4)); } #[crate::test] async fn interval_at_starts_at_its_first_tick() { - let mut ticks = crate::interval_at(at(2), Duration::from_secs(1)); + let mut ticks = crate::clock::interval_at(at(2), Duration::from_secs(1)); assert_eq!(ticks.tick().await, at(2)); - assert_eq!(crate::now(), at(2), "nothing ticks before the start"); + assert_eq!(crate::clock::now(), at(2), "nothing ticks before the start"); assert_eq!(ticks.tick().await, at(3)); } #[crate::test] async fn interval_delay_restarts_from_the_late_tick() { - let mut ticks = crate::interval(Duration::from_secs(1)); + let mut ticks = crate::clock::interval(Duration::from_secs(1)); ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); ticks.tick().await; advance(Duration::from_millis(3500)).await; @@ -916,7 +916,7 @@ mod tests { #[crate::test] async fn interval_skip_resumes_the_schedule() { - let mut ticks = crate::interval(Duration::from_secs(1)); + let mut ticks = crate::clock::interval(Duration::from_secs(1)); ticks.set_missed_tick_behavior(MissedTickBehavior::Skip); ticks.tick().await; advance(Duration::from_millis(3500)).await; @@ -986,7 +986,7 @@ mod tests { #[test] #[should_panic(expected = "deadlock")] fn a_sleep_past_the_range_never_fires() { - run(async { crate::sleep(Duration::MAX).await }); + run(async { crate::clock::sleep(Duration::MAX).await }); } /// The last instant is a real deadline, not the never-firing overflow. @@ -994,7 +994,7 @@ mod tests { async fn the_last_instant_is_reachable() { // From the epoch, so the wall clock has room to reach it too. step_wall(Wall::UNIX_EPOCH); - let task = spawn(crate::sleep_until(Instant::MAX)); + let task = spawn(crate::clock::sleep_until(Instant::MAX)); yield_now().await; advance(Duration::from_nanos(u64::MAX)).await; task.await.unwrap(); @@ -1007,7 +1007,7 @@ mod tests { run(async { // From the epoch, so the wall clock could reach the last instant. step_wall(Wall::UNIX_EPOCH); - let mut interval = crate::interval(Duration::MAX); + let mut interval = crate::clock::interval(Duration::MAX); interval.tick().await; interval.tick().await; }); @@ -1016,22 +1016,22 @@ mod tests { /// A queue attached behind the clock catches up before the run decides it stalled. #[crate::test] async fn a_queue_attached_behind_the_clock_wakes_at_once() { - let deadlines = Deadlines::new(crate::now()); + let deadlines = Deadlines::new(crate::clock::now()); let mut deadline = Deadline::after(&deadlines, Duration::from_secs(5)); advance(Duration::from_secs(10)).await; - let task = spawn(async move { kio::wait(|waiter| deadline.poll(waiter)).await }); + let task = spawn(async move { crate::wait(|waiter| deadline.poll(waiter)).await }); yield_now().await; attach(&deadlines); task.await.unwrap(); - assert_eq!(crate::now(), at(10)); + assert_eq!(crate::clock::now(), at(10)); } /// Attaching brings the queue to the simulated instant at once, so a deadline /// armed right after counts from it. #[crate::test] async fn attaching_syncs_the_queue() { - let deadlines = Deadlines::new(crate::now()); + let deadlines = Deadlines::new(crate::clock::now()); advance(Duration::from_secs(10)).await; attach(&deadlines); assert_eq!(deadlines.now(), at(10)); @@ -1048,16 +1048,16 @@ mod tests { async fn a_sleep_reset_by_another_task_rearms() { // Armed, and past the clock's range so never firing. for duration in [Duration::from_secs(10), Duration::MAX] { - let sleep = Rc::new(RefCell::new(crate::sleep(duration))); + let sleep = Rc::new(RefCell::new(crate::clock::sleep(duration))); let polled = sleep.clone(); let task = spawn(std::future::poll_fn(move |cx| { Pin::new(&mut *polled.borrow_mut()).poll(cx) })); yield_now().await; - let target = crate::now() + Duration::from_secs(3); + let target = crate::clock::now() + Duration::from_secs(3); sleep.borrow_mut().reset(target); task.await.unwrap(); - assert_eq!(crate::now(), target); + assert_eq!(crate::clock::now(), target); } } @@ -1072,26 +1072,26 @@ mod tests { } } let count = Arc::new(Count(Default::default())); - let owner = kio::Waiter::new(Waker::from(count.clone())); + let owner = crate::Waiter::new(Waker::from(count.clone())); - let deadlines = Deadlines::new(crate::now()); + let deadlines = Deadlines::new(crate::clock::now()); attach(&deadlines); - deadlines.advance(crate::now()); + deadlines.advance(crate::clock::now()); deadlines.park(&owner); - crate::sleep(Duration::from_secs(1)).await; + crate::clock::sleep(Duration::from_secs(1)).await; let mut deadline = Deadline::new(&deadlines); - deadline.set(Some(crate::now() + Duration::from_secs(1))); + deadline.set(Some(crate::clock::now() + Duration::from_secs(1))); assert_eq!(count.0.load(Ordering::SeqCst), 1, "the parked owner was not woken"); } /// The run holds an attached queue weakly and forgets it once its owner drops it. #[crate::test] async fn an_attached_queue_detaches_once_dropped() { - let deadlines = Deadlines::new(crate::now()); + let deadlines = Deadlines::new(crate::clock::now()); attach(&deadlines); drop(deadlines); - crate::sleep(Duration::from_secs(1)).await; + crate::clock::sleep(Duration::from_secs(1)).await; assert!(expect_current().queues.borrow().is_empty()); } @@ -1106,10 +1106,10 @@ mod tests { /// A sleep answers to the clock it was created on, not to the poller's. #[test] - #[should_panic(expected = "polled outside its moq_clock::sim::run")] + #[should_panic(expected = "polled outside its kio::clock::sim::run")] #[expect(clippy::async_yields_async, reason = "the sleep escapes the run on purpose")] fn a_sleep_polled_in_another_run_panics() { - let mut sleep = run(async { crate::sleep(Duration::from_secs(1)) }); + let mut sleep = run(async { crate::clock::sleep(Duration::from_secs(1)) }); run(async move { advance(Duration::from_secs(2)).await; (&mut sleep).await; @@ -1118,18 +1118,18 @@ mod tests { #[crate::test] async fn attached_deadlines_advance_with_time() { - let deadlines = Deadlines::new(crate::now()); + let deadlines = Deadlines::new(crate::clock::now()); attach(&deadlines); let mut deadline = Deadline::after(&deadlines, Duration::from_secs(4)); // Nothing else is armed, so the stall jumps straight to the queue's deadline. - kio::wait(|waiter| deadline.poll(waiter)).await; - assert_eq!(crate::now(), at(4)); + crate::wait(|waiter| deadline.poll(waiter)).await; + assert_eq!(crate::clock::now(), at(4)); } #[crate::test] async fn drive_polls_at_each_requested_instant() { let mut polls = Vec::new(); - let err = crate::drive(|now, _waiter| { + let err = crate::clock::drive(|now, _waiter| { polls.push(now); match polls.len() { 3 => Err("done"), diff --git a/rs/moq-clock/src/timer.rs b/rs/kio/src/clock/timer.rs similarity index 88% rename from rs/moq-clock/src/timer.rs rename to rs/kio/src/clock/timer.rs index 39e4c42c48c..8cadf58ef66 100644 --- a/rs/moq-clock/src/timer.rs +++ b/rs/kio/src/clock/timer.rs @@ -6,7 +6,7 @@ use std::{ time::Duration, }; -use crate::Instant; +use crate::clock::Instant; /// A future that completes once the ambient clock reaches an instant. /// @@ -21,25 +21,25 @@ pub struct Sleep { } enum Timer { - Queue(crate::deadline::Timer), - Host(crate::runtime::Timer), + Queue(crate::clock::deadline::Timer), + Host(crate::clock::runtime::Timer), #[cfg(feature = "sim")] - Sim(crate::sim::Timer), + Sim(crate::clock::sim::Timer), #[cfg(feature = "manual")] - Installed(crate::installed::Timer), + Installed(crate::clock::installed::Timer), } /// Complete once the ambient clock reaches `at`; at once if it already has. pub fn sleep_until(at: Instant) -> Sleep { - if let Some(deadlines) = crate::deadline::entered() { + if let Some(deadlines) = crate::clock::deadline::entered() { return Sleep { at: Some(at), - timer: Timer::Queue(crate::deadline::Timer::new(&deadlines, Some(at))), + timer: Timer::Queue(crate::clock::deadline::Timer::new(&deadlines, Some(at))), parked: None, }; } #[cfg(feature = "sim")] - if let Some(timer) = crate::sim::Timer::new(at) { + if let Some(timer) = crate::clock::sim::Timer::new(at) { return Sleep { at: Some(at), timer: Timer::Sim(timer), @@ -47,12 +47,12 @@ pub fn sleep_until(at: Instant) -> Sleep { }; } #[cfg(feature = "manual")] - if let Some(clock) = crate::installed::current() { + if let Some(clock) = crate::clock::installed::current() { return Sleep::installed(clock, at); } Sleep { at: Some(at), - timer: Timer::Host(crate::runtime::Timer::new(at)), + timer: Timer::Host(crate::clock::runtime::Timer::new(at)), parked: None, } } @@ -61,7 +61,7 @@ pub fn sleep_until(at: Instant) -> Sleep { /// /// A duration past the clock's range never completes. pub fn sleep(duration: Duration) -> Sleep { - let now = crate::now(); + let now = crate::clock::now(); let mut sleep = sleep_until(now); sleep.set(now.checked_add(duration)); sleep @@ -70,10 +70,10 @@ pub fn sleep(duration: Duration) -> Sleep { impl Sleep { /// A sleep on an installed clock, whichever thread polls it. #[cfg(feature = "manual")] - pub(crate) fn installed(clock: crate::Installed, at: Instant) -> Self { + pub(crate) fn installed(clock: crate::clock::Installed, at: Instant) -> Self { Self { at: Some(at), - timer: Timer::Installed(crate::installed::Timer::new(clock, at)), + timer: Timer::Installed(crate::clock::installed::Timer::new(clock, at)), parked: None, } } @@ -210,7 +210,7 @@ pub struct Interval { /// /// When `period` is zero. pub fn interval(period: Duration) -> Interval { - interval_at(crate::now(), period) + interval_at(crate::clock::now(), period) } /// Tick every `period` on the ambient clock, the first tick at `start`. @@ -239,7 +239,7 @@ impl Interval { return Poll::Pending; } let scheduled = self.sleep.deadline(); - let now = crate::now(); + let now = crate::clock::now(); // A tick past the clock's range never comes. let next = scheduled.checked_add(self.period).and_then(|next| { if next > now { @@ -275,11 +275,11 @@ impl Interval { /// /// `poll` is called with the current instant and returns when it next wants to be /// polled: `Ok(Some(at))` by `at` or on a wake, `Ok(None)` only on a wake. -pub async fn drive(mut poll: impl FnMut(Instant, &kio::Waiter) -> Result, E> + Unpin) -> E { +pub async fn drive(mut poll: impl FnMut(Instant, &crate::Waiter) -> Result, E> + Unpin) -> E { let mut timer: Option = None; - kio::wait(move |waiter| { + crate::wait(move |waiter| { loop { - let at = match poll(crate::now(), waiter) { + let at = match poll(crate::clock::now(), waiter) { Ok(Some(at)) => at, Ok(None) => { timer = None; @@ -323,7 +323,8 @@ mod tests { .start_paused(true) .build() .unwrap(); - let (mut sleep, at) = runtime.block_on(async { (sleep(Duration::MAX), crate::now() + Duration::from_secs(1)) }); + let (mut sleep, at) = + runtime.block_on(async { (sleep(Duration::MAX), crate::clock::now() + Duration::from_secs(1)) }); sleep.reset(at); runtime.block_on(sleep); } diff --git a/rs/moq-clock/src/wall.rs b/rs/kio/src/clock/wall.rs similarity index 97% rename from rs/moq-clock/src/wall.rs rename to rs/kio/src/clock/wall.rs index 313871c259f..a2912fe0f5a 100644 --- a/rs/moq-clock/src/wall.rs +++ b/rs/kio/src/clock/wall.rs @@ -6,7 +6,7 @@ use std::{ /// A wall-clock time, in nanoseconds since the Unix epoch. /// -/// Read from the same clock as [`Instant`](crate::Instant) but kept apart from it: +/// Read from the same clock as [`Instant`](crate::clock::Instant) but kept apart from it: /// wall time can be stepped, forward or back, without any monotonic time passing, /// so it never measures elapsed time. Times before 1970 are unrepresentable. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -23,7 +23,7 @@ impl Wall { /// The current wall time on the ambient clock. pub fn now() -> Self { - crate::wall() + crate::clock::wall() } /// The time from `earlier` to this one, or `None` if `earlier` is later. diff --git a/rs/kio/src/consumer.rs b/rs/kio/src/consumer.rs index 744d81fd74e..8d47ad38bec 100644 --- a/rs/kio/src/consumer.rs +++ b/rs/kio/src/consumer.rs @@ -75,7 +75,7 @@ impl Consumer { /// channel is still open, registers the [`Waiter`] for notification. /// Returns `Err(`[`Ref`]`)` if the channel has been closed while the /// condition returned by `f` is still pending. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll(&self, waiter: &Waiter, f: F) -> Poll>> where F: FnOnce(&Ref<'_, T>) -> Poll, @@ -99,7 +99,7 @@ impl Consumer { } /// Poll for channel closure, registering the waiter if still open. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> { let mut state = self.state.lock(); if state.closed { diff --git a/rs/kio/src/coop.rs b/rs/kio/src/coop.rs index 99c6d0d4f54..3b04ac7f69b 100644 --- a/rs/kio/src/coop.rs +++ b/rs/kio/src/coop.rs @@ -9,17 +9,17 @@ use std::task::Poll; use crate::Waiter; -#[cfg(feature = "_sim")] +#[cfg(feature = "sim")] thread_local! { static READY: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Restores the enclosing count, even when a spawned task panics and its executor /// catches the panic. -#[cfg(feature = "_sim")] +#[cfg(feature = "sim")] struct Reset(Option); -#[cfg(feature = "_sim")] +#[cfg(feature = "sim")] impl Drop for Reset { fn drop(&mut self) { READY.set(self.0); @@ -27,22 +27,22 @@ impl Drop for Reset { } /// Count ready kio polls until the returned guard drops, panicking if the task spins. -#[cfg(feature = "_sim")] +#[cfg(feature = "sim")] #[must_use = "keep the guard until the task poll returns"] -pub fn scope() -> impl Drop { +pub(crate) fn scope() -> impl Drop { Reset(READY.replace(Some(0))) } /// Give a [`Tasks`](crate::Tasks) child's poll its own count, but only inside a counting scope. -#[cfg(feature = "_sim")] +#[cfg(feature = "sim")] pub(crate) fn child() -> impl Drop { Reset(READY.replace(READY.get().map(|_| 0))) } #[inline] -#[cfg_attr(feature = "_sim", track_caller)] +#[cfg_attr(feature = "sim", track_caller)] pub(crate) fn ready(value: T) -> Poll { - #[cfg(feature = "_sim")] + #[cfg(feature = "sim")] { let count = READY.get().map(|count| count + 1); READY.set(count); @@ -75,7 +75,7 @@ impl Budget { /// The yield refills the budget for the next poll. Call it only where `Pending` goes /// straight up to the task: a caller that reads `Pending` as "nothing now" would /// mistake the yield for an answer. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_yield(&mut self, waiter: &Waiter) -> Poll<()> { match self.left.checked_sub(1) { Some(left) => { diff --git a/rs/kio/src/lib.rs b/rs/kio/src/lib.rs index 2464989c9d9..734fac1f482 100644 --- a/rs/kio/src/lib.rs +++ b/rs/kio/src/lib.rs @@ -21,6 +21,9 @@ //! [`coop`] bounds the passes a loop makes per poll, so one that always finds //! work ready still yields. //! +//! [`clock`] is the time those waits run on: logical instants, wall time, +//! deadlines, timers, and a deterministic simulator for tests. +//! //! With the `macros` feature, `#[kio::machine]` writes a `poll_*` state machine from //! straight-line code with explicit waits. @@ -35,6 +38,7 @@ use std::{ mod lock; mod waiter; +pub mod clock; pub mod coop; pub mod log; @@ -64,6 +68,14 @@ pub use task::{Task, TaskKey, Tasks}; pub use waiter::{Park, Waiter, WaiterList, wait}; pub use weak::{ConsumerWeak, ProducerWeak, Weak}; +/// Run an `async fn` test to completion on [`clock::sim::run`]. +#[cfg(feature = "sim")] +pub use kio_macros::test; + +// So `#[kio::test]` resolves inside this crate's own tests. +#[cfg(test)] +extern crate self as kio; + /// Bytes an `Arc` allocation occupies: `T` behind two reference counts, padded to /// `T`'s alignment and rounded up to the whole layout's. /// @@ -84,7 +96,8 @@ const fn arc_heap() -> usize { mod heap { use std::alloc::Layout; - use super::*; + // Not a glob: it would import `test`, kio's attribute, over the built-in one. + use super::{State, arc_heap}; /// [`arc_heap`] hand-rolls what `Layout` does, because `Layout` isn't `const`. Hold /// it to the real thing, including a `T` aligned past the reference counts. diff --git a/rs/kio/src/producer.rs b/rs/kio/src/producer.rs index 3e4c39aa46a..8784fd153c1 100644 --- a/rs/kio/src/producer.rs +++ b/rs/kio/src/producer.rs @@ -123,7 +123,7 @@ impl Producer { /// while pending. /// /// Returns `Poll::Ready(Err(`[`Ref`]`))` if the channel is closed. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll(&self, waiter: &Waiter, f: F) -> Poll, Ref<'_, T>>> where F: FnOnce(&Ref<'_, T>) -> Poll<()>, @@ -150,7 +150,7 @@ impl Producer { /// [`Mut`], so it never flags the state modified and never wakes consumers. /// Use it to wait on a read condition from the producer side without creating /// a [`Consumer`]. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_ref(&self, waiter: &Waiter, f: F) -> Poll>> where F: FnOnce(&Ref<'_, T>) -> Poll, @@ -192,7 +192,7 @@ impl Producer { /// Poll for channel closure (an explicit [`Mut::close`], e.g. an abort), /// registering the waiter if still open. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> { let mut state = self.state.lock(); if state.closed { @@ -219,7 +219,7 @@ impl Producer { /// Poll for [`Self::wanted`] to differ from `last`: `Ready(Ok)` with the new value once /// it does, [`Closed`] if the channel closed first, else `Pending`. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_wanted_changed(&self, waiter: &Waiter, last: bool) -> Poll> { // Closure is checked first, so a closed channel reports `Closed` from every handle // rather than a consumer count that only dropped because it's dead. diff --git a/rs/kio/src/queue.rs b/rs/kio/src/queue.rs index fc322f40375..d750affbddb 100644 --- a/rs/kio/src/queue.rs +++ b/rs/kio/src/queue.rs @@ -130,7 +130,7 @@ impl Queue { /// (or anything that does). /// /// Registers `waiter` while full; a pop or close re-polls it. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_push_with T>(&self, waiter: &Waiter, make: F) -> Poll> { let mut waiters = { let mut state = self.state.lock(); @@ -181,7 +181,7 @@ impl Queue { /// /// Queued items drain before closure is reported, so [`Closed`] means empty /// *and* closed. Registers `waiter` while empty; a push or close re-polls it. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_pop(&self, waiter: &Waiter) -> Poll> { let (item, mut waiters) = { let mut state = self.state.lock(); diff --git a/rs/kio/src/shared.rs b/rs/kio/src/shared.rs index 9027d4fb8f9..dfb850a4e0b 100644 --- a/rs/kio/src/shared.rs +++ b/rs/kio/src/shared.rs @@ -61,7 +61,7 @@ impl Shared { /// [`Ref`], so it can't flag the state modified and spuriously wake this poll's own /// waiter. Registers `waiter` while pending; any mutation through a [`lock`](Self::lock) /// guard re-polls it. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll(&self, waiter: &Waiter, f: F) -> Poll> where F: FnOnce(&Ref<'_, T>) -> Poll<()>, diff --git a/rs/kio/src/task.rs b/rs/kio/src/task.rs index 67da55b2e94..6c3e583baf7 100644 --- a/rs/kio/src/task.rs +++ b/rs/kio/src/task.rs @@ -375,7 +375,7 @@ impl> Tasks { /// such an arm with [`is_empty`](Self::is_empty). /// `waiter` is registered for the next task wake or push; the tasks /// themselves park on their own wakers. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll(&mut self, waiter: &Waiter) -> Poll<()> { self.poll_each(waiter, |_, ()| {}) } @@ -384,7 +384,7 @@ impl> Tasks { impl Tasks { /// [`poll`](Self::poll) a set whose tasks resolve to a value: `done` takes /// each task that returned `Ready`, with its output, as it retires. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_each(&mut self, waiter: &Waiter, mut done: impl FnMut(T, T::Output)) -> Poll<()> { { let mut parent = self.shared.parent.lock().unwrap(); @@ -447,7 +447,7 @@ impl Tasks { let child_waiter = occupant.park.hold(&cx); // Each child is its own task, so a large sweep of finite children is not // one spinning poll. - #[cfg(feature = "_sim")] + #[cfg(feature = "sim")] let _scope = crate::coop::child(); if let Poll::Ready(output) = occupant.task.poll(child_waiter) { let occupant = self.children[index].take().expect("polled slot is occupied"); diff --git a/rs/kio/src/waiter.rs b/rs/kio/src/waiter.rs index 27ea9769ae5..1faf324ee90 100644 --- a/rs/kio/src/waiter.rs +++ b/rs/kio/src/waiter.rs @@ -155,7 +155,7 @@ impl Waiter { /// Poll a foreign [`Future`] against this waiter, so it re-wakes the enclosing /// `poll_*` step when it is ready. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_future(&self, future: Pin<&mut F>) -> Poll { match future.poll(&mut self.context()) { Poll::Ready(value) => crate::coop::ready(value), diff --git a/rs/kio/src/weak.rs b/rs/kio/src/weak.rs index 0b1680fff9e..097db7bc0f3 100644 --- a/rs/kio/src/weak.rs +++ b/rs/kio/src/weak.rs @@ -156,7 +156,7 @@ impl ProducerWeak { } /// Poll for channel closure, registering the waiter if still open. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> { let mut state = self.state.lock(); if state.closed { @@ -177,7 +177,7 @@ impl ProducerWeak { /// Poll for [`Self::wanted`] to differ from `last`: `Ready(Ok)` with the new value once /// it does, [`Closed`] if the channel closed first, else `Pending`. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_wanted_changed(&self, waiter: &Waiter, last: bool) -> Poll> { // Closure is checked first, so a closed channel reports `Closed` from every handle // rather than a consumer count that only dropped because it's dead. @@ -244,7 +244,7 @@ impl ConsumerWeak { /// Available here so a watcher can register for changes without joining the /// consumer count, which is what [`Producer::wanted_changed`](crate::Producer::wanted_changed) /// keys off. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll(&self, waiter: &Waiter, f: F) -> Poll>> where F: FnOnce(&Ref<'_, T>) -> Poll, @@ -277,7 +277,7 @@ impl ConsumerWeak { } /// Poll for channel closure, registering the waiter if still open. - #[cfg_attr(feature = "_sim", track_caller)] + #[cfg_attr(feature = "sim", track_caller)] pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> { let mut state = self.state.lock(); if state.closed { diff --git a/rs/moq-archive/Cargo.toml b/rs/moq-archive/Cargo.toml index cbcca7fe4f4..06e2585c95c 100644 --- a/rs/moq-archive/Cargo.toml +++ b/rs/moq-archive/Cargo.toml @@ -15,8 +15,7 @@ categories = ["multimedia", "filesystem"] [dependencies] bytes = { workspace = true } futures = { workspace = true } -kio = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-net = { workspace = true } object_store = { workspace = true } percent-encoding = { workspace = true } diff --git a/rs/moq-archive/src/consumer/mod.rs b/rs/moq-archive/src/consumer/mod.rs index 4e6e709c39b..9e1125a01a1 100644 --- a/rs/moq-archive/src/consumer/mod.rs +++ b/rs/moq-archive/src/consumer/mod.rs @@ -182,7 +182,7 @@ impl Consumer { let (shared, period) = (self.shared.clone(), self.refresh); refreshing = Some( async move { - moq_clock::sleep(period).await; + kio::clock::sleep(period).await; refresh(shared, snapshots).await } .boxed(), diff --git a/rs/moq-archive/src/consumer/tests.rs b/rs/moq-archive/src/consumer/tests.rs index 5d23e6b4af8..a0785df0d56 100644 --- a/rs/moq-archive/src/consumer/tests.rs +++ b/rs/moq-archive/src/consumer/tests.rs @@ -1,7 +1,7 @@ use std::time::Duration; use bytes::Bytes; -use moq_clock::{sleep, timeout}; +use kio::clock::{sleep, timeout}; use moq_net::track::{Order, Position, Subscription}; use moq_net::{Timescale, Timestamp, broadcast, group, track}; use object_store::ObjectStoreExt; diff --git a/rs/moq-archive/src/producer/backends.rs b/rs/moq-archive/src/producer/backends.rs index 0a2218d83a6..9e6674709a1 100644 --- a/rs/moq-archive/src/producer/backends.rs +++ b/rs/moq-archive/src/producer/backends.rs @@ -64,10 +64,10 @@ fn path(store: &Store, track: &str, name: &str) -> Path { /// Wait until every one of `paths` is stored. async fn stored(store: &Store, paths: &[Path]) { - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { for path in paths { while store.inner().head(path).await.is_err() { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } } }) @@ -104,12 +104,12 @@ async fn record(store: &Store) { let run = tokio::spawn(Producer::new(store.clone(), second.consume(), config()).run()); for track in &tracks { while track.subscription().is_none() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } track.finish().unwrap(); } second.close(); - moq_clock::timeout(Duration::from_secs(10), run) + kio::clock::timeout(Duration::from_secs(10), run) .await .expect("the producer ends with its broadcast") .unwrap() diff --git a/rs/moq-archive/src/producer/ordered.rs b/rs/moq-archive/src/producer/ordered.rs index 2d706c73402..770ae8d036e 100644 --- a/rs/moq-archive/src/producer/ordered.rs +++ b/rs/moq-archive/src/producer/ordered.rs @@ -8,7 +8,7 @@ use std::pin::Pin; use std::task::{Poll, ready}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::track::{Position, Subscriber}; use moq_net::{Datagram, group}; @@ -35,7 +35,7 @@ pub(super) struct Ordered { /// and the ones handed out behind it go once it does, so this holds at most what arrived /// within a max delay. The oldest dates the gap, so a later, lower arrival never extends it. arrivals: VecDeque<(u64, Instant)>, - timer: Option>>, + timer: Option>>, groups_done: bool, datagrams_done: bool, /// The first error a channel ended with: an end declared with an error, or an abort. @@ -62,7 +62,7 @@ impl Ordered { /// Take every arrival so far, registering `waiter` for the next. pub(super) fn poll_arrivals(&mut self, waiter: &kio::Waiter) { - let now = moq_clock::now(); + let now = kio::clock::now(); while !self.groups_done { match self.subscriber.poll_recv_group(waiter) { Poll::Ready(Ok(Some(group))) => self.arrive(group.sequence, Item::Group(Box::new(group)), now), @@ -124,10 +124,10 @@ impl Ordered { // The oldest arrival still pending is when this gap was first seen. let (_, since) = self.arrivals.front().expect("a pending sequence arrived"); let deadline = *since + self.max_delay; - if moq_clock::now() < deadline { + if kio::clock::now() < deadline { let timer = self .timer - .get_or_insert_with(|| Box::pin(moq_clock::sleep_until(deadline))); + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(deadline))); timer.as_mut().reset(deadline); if waiter.poll_future(timer.as_mut()).is_pending() { return Poll::Pending; @@ -219,9 +219,9 @@ mod tests { group(&track, 4); assert_eq!(next(&mut ordered), None); - moq_clock::sleep(MAX_DELAY - Duration::from_millis(1)).await; + kio::clock::sleep(MAX_DELAY - Duration::from_millis(1)).await; assert_eq!(next(&mut ordered), None); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert_eq!(next(&mut ordered), Some(4)); // Too late for its turn. @@ -239,10 +239,10 @@ mod tests { group(&track, 10); assert_eq!(next(&mut ordered), None); - moq_clock::sleep(MAX_DELAY - Duration::from_millis(1)).await; + kio::clock::sleep(MAX_DELAY - Duration::from_millis(1)).await; group(&track, 9); assert_eq!(next(&mut ordered), None); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert_eq!(next(&mut ordered), Some(9)); assert_eq!(next(&mut ordered), Some(10)); } diff --git a/rs/moq-archive/src/producer/tests.rs b/rs/moq-archive/src/producer/tests.rs index 840bdfd5480..c560de61c1d 100644 --- a/rs/moq-archive/src/producer/tests.rs +++ b/rs/moq-archive/src/producer/tests.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use bytes::Bytes; use futures::TryStreamExt; -use moq_clock::sleep; +use kio::clock::sleep; use moq_net::track::Position; use moq_net::{Timescale, Timestamp, broadcast, group, track}; use object_store::ObjectStoreExt; @@ -63,7 +63,7 @@ async fn subscribed(track: &track::Producer) { } async fn finished(task: JoinHandle>) { - moq_clock::timeout(Duration::from_secs(1000), task) + kio::clock::timeout(Duration::from_secs(1000), task) .await .expect("the producer ends with its broadcast") .unwrap() @@ -831,7 +831,7 @@ async fn a_re_added_track_is_stored_under_its_own_properties() { second.finish().unwrap(); broadcast.close(); - let err = moq_clock::timeout(Duration::from_secs(1000), task) + let err = kio::clock::timeout(Duration::from_secs(1000), task) .await .unwrap() .unwrap() diff --git a/rs/moq-archive/src/producer/track.rs b/rs/moq-archive/src/producer/track.rs index e92d338601d..ca1a153cfe2 100644 --- a/rs/moq-archive/src/producer/track.rs +++ b/rs/moq-archive/src/producer/track.rs @@ -7,7 +7,7 @@ use std::task::Poll; use std::time::Duration; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::track::{Anchor, Order, Position, Range, Subscription}; use moq_net::{StreamError, Timescale, group}; use object_store::path::Path; @@ -104,7 +104,7 @@ impl Track { track.newest = objects.pop(); if track.shared.config.dvr.is_some() { // Their age is unknown, so their window starts now. - let now = moq_clock::now(); + let now = kio::clock::now(); track.superseded = objects.into_iter().map(|path| (now, path)).collect(); } Ok(track) @@ -114,7 +114,7 @@ impl Track { /// to the newest, or `None` once the listing ended. async fn idle(&mut self, queue: &kio::Queue) -> Result> { loop { - let mut timer = self.prune_at().map(|at| Box::pin(moq_clock::sleep_until(at))); + let mut timer = self.prune_at().map(|at| Box::pin(kio::clock::sleep_until(at))); let popped = kio::wait(|waiter| { if let Poll::Ready(popped) = queue.poll_pop(waiter) { return Poll::Ready(Some(popped)); @@ -195,7 +195,7 @@ impl Track { // The group being stored, frame by frame. let mut current: Option> = None; loop { - self.flush_due(moq_clock::now())?; + self.flush_due(kio::clock::now())?; self.write().await?; self.prune().await?; @@ -203,7 +203,7 @@ impl Track { .into_iter() .flatten() .min() - .map(|at| Box::pin(moq_clock::sleep_until(at))); + .map(|at| Box::pin(kio::clock::sleep_until(at))); let event = kio::wait(|waiter| { match current.as_mut() { Some(current) => { @@ -224,7 +224,7 @@ impl Track { }) .await; - let now = moq_clock::now(); + let now = kio::clock::now(); match event { Event::Frame(index, read) => self.frame(&mut current, index, read, now)?, Event::Next(Some((sequence, Item::Datagram(datagram)))) => { @@ -391,7 +391,7 @@ impl Track { if let Some(superseded) = self.newest.replace(path.clone()) && self.shared.config.dvr.is_some() { - self.superseded.push_back((moq_clock::now(), superseded)); + self.superseded.push_back((kio::clock::now(), superseded)); } self.puts.push((path, bytes)); Ok(()) @@ -425,7 +425,7 @@ impl Track { /// Delete the superseded objects whose window and grace have passed. async fn prune(&mut self) -> Result<()> { - let now = moq_clock::now(); + let now = kio::clock::now(); while self.prune_at().is_some_and(|at| at <= now) { let (_, path) = self.superseded.pop_front().expect("a superseded object is due"); match self.shared.store.inner().delete(&path).await { @@ -463,7 +463,7 @@ fn error(err: &moq_net::Error) -> End { } /// Poll an optional timer, pending forever without one. -fn ready_at(timer: &mut Option>>, waiter: &kio::Waiter) -> Poll<()> { +fn ready_at(timer: &mut Option>>, waiter: &kio::Waiter) -> Poll<()> { match timer.as_mut() { Some(timer) => waiter.poll_future(timer.as_mut()), None => Poll::Pending, diff --git a/rs/moq-audio/Cargo.toml b/rs/moq-audio/Cargo.toml index fa928ba7037..61504477c24 100644 --- a/rs/moq-audio/Cargo.toml +++ b/rs/moq-audio/Cargo.toml @@ -41,7 +41,6 @@ bus = ["dep:ringbuf"] # are target-gated, so this is a no-op elsewhere). capture = [ "dep:cpal", - "dep:kio", "dep:ringbuf", "dep:tokio", "dep:tracing", @@ -57,7 +56,7 @@ capture = [ # Device playback. Mixes any number of `playback::Sink`s into one cpal output # stream (CoreAudio / WASAPI / ALSA). Same libasound build dependency on Linux # as `capture`. -playback = ["dep:cpal", "dep:kio", "dep:ringbuf", "dep:tokio", "dep:tracing"] +playback = ["dep:cpal", "dep:ringbuf", "dep:tokio", "dep:tracing"] # Reach devices through the Linux sound server rather than its ALSA plugin, for # the server's own device names and routing. These customize cpal only when # `capture` or `playback` activates it, so a host flag alone pulls no audio I/O. @@ -75,8 +74,7 @@ bytes = { workspace = true } # without either pulls no new dependency. cpal = { version = "0.18", optional = true } hang = { workspace = true } -kio = { workspace = true, optional = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-mux = { workspace = true } moq-net = { workspace = true } rand = { workspace = true } diff --git a/rs/moq-audio/src/aec.rs b/rs/moq-audio/src/aec.rs index 6dbcb6eedbb..45310c3c7a5 100644 --- a/rs/moq-audio/src/aec.rs +++ b/rs/moq-audio/src/aec.rs @@ -1146,10 +1146,10 @@ mod tests { // Until the tap hears it rather than for a fixed count: writes are dropped // until the device first reads, and a device can take seconds to start // (PulseAudio's idle null sink renders two seconds ahead). - let deadline = moq_clock::Instant::now() + std::time::Duration::from_secs(10); - while energy <= 1.0 && moq_clock::Instant::now() < deadline { + let deadline = kio::clock::Instant::now() + std::time::Duration::from_secs(10); + while energy <= 1.0 && kio::clock::Instant::now() < deadline { let _ = sink.write(&tone).expect("write"); - moq_clock::sleep(std::time::Duration::from_millis(100)).await; + kio::clock::sleep(std::time::Duration::from_millis(100)).await; // Drain the tap the way the microphone callback would, and add up // what the speaker was given. diff --git a/rs/moq-audio/src/capture.rs b/rs/moq-audio/src/capture.rs index cf9c2876ec8..e42643f6cd2 100644 --- a/rs/moq-audio/src/capture.rs +++ b/rs/moq-audio/src/capture.rs @@ -464,7 +464,7 @@ impl Microphone { // Await the first buffer to surface a permission failure (or dead device) // as an error rather than a silent hang in the capture loop. - let pending = match moq_clock::timeout(FIRST_BUFFER_TIMEOUT, reader.read()).await { + let pending = match kio::clock::timeout(FIRST_BUFFER_TIMEOUT, reader.read()).await { Ok(Ok(Some(samples))) => samples, Ok(Ok(None)) => { return Err(Failure::retry(Error::Capture(format!( diff --git a/rs/moq-audio/src/capture/channel.rs b/rs/moq-audio/src/capture/channel.rs index e336c81d6c1..cec8f33fd5e 100644 --- a/rs/moq-audio/src/capture/channel.rs +++ b/rs/moq-audio/src/capture/channel.rs @@ -12,7 +12,7 @@ use std::sync::{ }; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use tokio::sync::mpsc; diff --git a/rs/moq-audio/src/capture/permission.rs b/rs/moq-audio/src/capture/permission.rs index 07493fbd815..e70e75e5740 100644 --- a/rs/moq-audio/src/capture/permission.rs +++ b/rs/moq-audio/src/capture/permission.rs @@ -67,7 +67,7 @@ async fn request_access(media: &objc2_av_foundation::AVMediaType) -> Result<(), unsafe { AVCaptureDevice::requestAccessForMediaType_completionHandler(media, &handler) }; - match moq_clock::timeout(PROMPT_TIMEOUT, rx).await { + match kio::clock::timeout(PROMPT_TIMEOUT, rx).await { Ok(Ok(true)) => Ok(()), Ok(Ok(false)) => Err(denied()), // Prompt dismissed without a decision, or the callback never fired within diff --git a/rs/moq-audio/src/capture/screencapture.rs b/rs/moq-audio/src/capture/screencapture.rs index e15da5f403a..3068c34c247 100644 --- a/rs/moq-audio/src/capture/screencapture.rs +++ b/rs/moq-audio/src/capture/screencapture.rs @@ -124,7 +124,7 @@ impl SystemAudio { _dispatch: dispatch, }; - let pending = match moq_clock::timeout(FIRST_BUFFER_TIMEOUT, rx.recv()).await { + let pending = match kio::clock::timeout(FIRST_BUFFER_TIMEOUT, rx.recv()).await { Ok(Some(buffer)) => buffer, Ok(None) => { return Err(Error::Capture("system audio stopped before any samples".into())); @@ -352,7 +352,7 @@ async fn shareable_content() -> Result, Error> { }); unsafe { SCShareableContent::getShareableContentWithCompletionHandler(&handler) }; - match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { + match kio::clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(Ok(content))) => Ok(content.0), Ok(Ok(Err(msg))) => Err(Error::Capture(format!("shareable content: {msg}"))), Ok(Err(_)) => Err(Error::Capture("shareable content handler dropped".into())), @@ -374,7 +374,7 @@ async fn start_capture(stream: &SCStream) -> Result<(), Error> { }); unsafe { stream.startCaptureWithCompletionHandler(Some(&handler)) }; - match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { + match kio::clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(None)) => Ok(()), Ok(Ok(Some(msg))) => Err(Error::Capture(format!("start system audio: {msg}"))), Ok(Err(_)) => Err(Error::Capture("start-capture handler dropped".into())), diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index fffd28b3aac..9e071c7ee8c 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; -use moq_clock::Instant; +use kio::clock::Instant; use moq_mux::container::Read as Encoded; use std::time::Duration; diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index 8a04f4aa0b7..0daea2cc8c7 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -1055,7 +1055,7 @@ impl Supervisor { }; tracing::warn!(error = %failure, "audio capture format unavailable"); - moq_clock::sleep(self.advance()).await; + kio::clock::sleep(self.advance()).await; } } @@ -1184,7 +1184,7 @@ impl Supervisor { } continue 'demand; } - _ = moq_clock::sleep(wait) => {} + _ = kio::clock::sleep(wait) => {} } } } @@ -1511,7 +1511,7 @@ mod tests { } async fn wait_for(control: &mut Control, status: Status) -> State { - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { loop { let state = control.state(); if state.status() == status { @@ -1588,7 +1588,7 @@ mod tests { events .try_push(Ok(capture::Samples::plain(vec![0.25, -0.5, 1.0, -1.0], false))) .unwrap(); - let level = moq_clock::timeout(Duration::from_secs(1), async { + let level = kio::clock::timeout(Duration::from_secs(1), async { loop { let level = control.level(); if level != Level::default() { @@ -1619,7 +1619,7 @@ mod tests { .try_push(Ok(capture::Samples::plain(vec![0.25, -0.5, 1.0, -1.0], false))) .unwrap(); } - moq_clock::timeout(Duration::from_millis(100), control.changed()) + kio::clock::timeout(Duration::from_millis(100), control.changed()) .await .expect_err("a level change woke a state waiter"); @@ -1638,7 +1638,7 @@ mod tests { ..driver }; - let err = moq_clock::timeout(Duration::from_secs(1), driver.run_with(source)) + let err = kio::clock::timeout(Duration::from_secs(1), driver.run_with(source)) .await .expect("a terminal failure parked instead of returning") .expect_err("the terminal failure was swallowed"); @@ -1674,7 +1674,7 @@ mod tests { events .try_push(Ok(capture::Samples::plain(vec![0.5, -0.5], false))) .unwrap(); - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { while control.level() == Level::default() { tokio::task::yield_now().await; } @@ -1724,7 +1724,7 @@ mod tests { let task = tokio::spawn(driver.run_with(source)); assert_eq!(control.track_name(), "audio"); - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { while attempts.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; } @@ -2085,7 +2085,7 @@ mod tests { poll_pending(run.as_mut()).await; assert_eq!(attempts.load(Ordering::SeqCst), 1); drop(control); - moq_clock::timeout(Duration::from_secs(1), run) + kio::clock::timeout(Duration::from_secs(1), run) .await .expect("dropping the controls ends the driver") .unwrap(); @@ -2103,7 +2103,7 @@ mod tests { poll_pending(run.as_mut()).await; } drop(control); - moq_clock::timeout(Duration::from_secs(1), run) + kio::clock::timeout(Duration::from_secs(1), run) .await .expect("dropping the controls ends the driver") .unwrap(); @@ -2116,7 +2116,7 @@ mod tests { /// the broadcast clock's own correlation, so the published timestamp is exactly that /// instant however late the read happens. mod clock { - use moq_clock::Wall; + use kio::clock::Wall; use std::time::Duration; use super::*; @@ -2246,7 +2246,7 @@ mod tests { #[tokio::test] async fn a_late_first_buffer_publishes_its_capture() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(5), kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let published = fixture.deliver(&samples, &mut track, &[]).await; @@ -2259,7 +2259,7 @@ mod tests { #[tokio::test] async fn a_queued_buffer_publishes_its_capture_instant() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(5), kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let captured = Instant::now() - Duration::from_millis(40); @@ -2277,7 +2277,7 @@ mod tests { #[tokio::test] async fn a_buffer_before_the_clock_began_clamps_to_zero() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::ZERO, moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::ZERO, kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; samples @@ -2300,7 +2300,7 @@ mod tests { #[tokio::test] async fn a_buffer_captured_after_now_clamps_to_the_read() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let pushed = fixture.at(Instant::now()); @@ -2325,7 +2325,7 @@ mod tests { #[tokio::test] async fn a_buffer_without_a_capture_instant_publishes_its_read() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let pushed = fixture.at(Instant::now()); @@ -2346,7 +2346,7 @@ mod tests { #[tokio::test] async fn a_gap_reanchors_to_the_next_capture_instant() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let second_at = Instant::now() - Duration::from_millis(20); @@ -2372,7 +2372,7 @@ mod tests { let (second, reopened) = stream(None); let mut fixture = Fixture::start( Duration::from_secs(1), - moq_clock::wall(), + kio::clock::wall(), [Open::Stream(failing), Open::Stream(reopened)], ); let mut track = fixture.subscribe().await; @@ -2399,7 +2399,7 @@ mod tests { #[tokio::test] async fn captures_without_a_subscriber() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall(), [Open::Stream(input)]); wait_for(&mut fixture.publication, Status::Live).await; let captured = Instant::now(); @@ -2408,7 +2408,7 @@ mod tests { .unwrap(); // Published before anyone subscribes: the largest location is read without asking for it. let mut probe = fixture.consumer.track("audio").unwrap(); - moq_clock::timeout(Duration::from_secs(1), probe.largest()) + kio::clock::timeout(Duration::from_secs(1), probe.largest()) .await .expect("a group published with nobody listening") .expect("the track is still open"); @@ -2423,7 +2423,7 @@ mod tests { #[tokio::test] async fn on_demand_waits_for_a_subscriber() { let (samples, input) = stream(None); - let mut fixture = Fixture::on_demand(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); + let mut fixture = Fixture::on_demand(Duration::from_secs(1), kio::clock::wall(), [Open::Stream(input)]); // `Waiting` is announced right before the demand gate, so nothing opens past it unsubscribed. wait_for(&mut fixture.publication, Status::Waiting).await; assert_eq!(fixture.opens.load(Ordering::SeqCst), 0, "opened with nobody listening"); @@ -2443,7 +2443,7 @@ mod tests { let (second, resumed) = stream(None); let mut fixture = Fixture::on_demand( Duration::from_secs(1), - moq_clock::wall(), + kio::clock::wall(), [Open::Stream(input), Open::Stream(resumed)], ); @@ -2452,7 +2452,7 @@ mod tests { drop(track); wait_for(&mut fixture.publication, Status::Waiting).await; - moq_clock::sleep(idle).await; + kio::clock::sleep(idle).await; let mut track = fixture.subscribe().await; let after = fixture.deliver(&second, &mut track, &[before]).await; @@ -2469,7 +2469,7 @@ mod tests { #[tokio::test] async fn a_system_wall_adjustment_retimes_nothing() { // Whole seconds, so the advertised mapping holds it exactly. - let now = moq_clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); + let now = kio::clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); let wall = Wall::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); let (samples, input) = stream(None); let mut fixture = Fixture::start(Duration::from_secs(1), wall, [Open::Stream(input)]); @@ -2496,7 +2496,7 @@ mod tests { let (second, resumed) = stream(None); let mut fixture = Fixture::on_demand( Duration::from_secs(1), - moq_clock::wall(), + kio::clock::wall(), [Open::Stream(input), Open::Stream(resumed)], ); let mut live = Vec::new(); @@ -2518,7 +2518,7 @@ mod tests { } wait_for(&mut fixture.publication, Status::Waiting).await; // Idle past the minimum segment, so each run is listed as its own segment. - moq_clock::sleep(moq_mux::hls::DEFAULT_DURATION + Duration::from_millis(100)).await; + kio::clock::sleep(moq_mux::hls::DEFAULT_DURATION + Duration::from_millis(100)).await; } let (mut catalog, consumer) = fixture.finish().await; diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index c7888f029aa..b7de46d10a2 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -618,7 +618,7 @@ mod tests { while demand.wanted_changed().await?.is_none() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(Duration::from_secs(1), wanted) + kio::clock::timeout(Duration::from_secs(1), wanted) .await .expect("subscription demand") .unwrap(); @@ -630,7 +630,7 @@ mod tests { while demand.wanted_changed().await?.is_some() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(Duration::from_secs(1), unwanted) + kio::clock::timeout(Duration::from_secs(1), unwanted) .await .expect("subscription released") .unwrap(); @@ -638,7 +638,7 @@ mod tests { producer.finish().unwrap(); drop(producer); - let closed = moq_clock::timeout(Duration::from_secs(1), demand.closed()) + let closed = kio::clock::timeout(Duration::from_secs(1), demand.closed()) .await .expect("producer closed"); assert!(closed.is_ok(), "{closed:?}"); diff --git a/rs/moq-audio/src/playback/driver.rs b/rs/moq-audio/src/playback/driver.rs index f2fa47e4717..f605a963828 100644 --- a/rs/moq-audio/src/playback/driver.rs +++ b/rs/moq-audio/src/playback/driver.rs @@ -5,7 +5,7 @@ //! the hot path; they register themselves in [`Shared`] and hand their consumer //! straight to the mixer. -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering}; #[cfg(feature = "aec")] diff --git a/rs/moq-audio/src/resample.rs b/rs/moq-audio/src/resample.rs index ba1c5ccf578..04f6eabf4a2 100644 --- a/rs/moq-audio/src/resample.rs +++ b/rs/moq-audio/src/resample.rs @@ -550,7 +550,7 @@ mod tests { let mut resampler = Resampler::new(input_rate, output_rate, channels, chunk).unwrap(); let mut elapsed = std::time::Duration::ZERO; for _ in 0..10 { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut count = 0; for (index, samples) in input.chunks(packet * channels as usize).enumerate() { let at = at((index * packet) as u64, input_rate as u64); diff --git a/rs/moq-audio/tests/integration/import.rs b/rs/moq-audio/tests/integration/import.rs index 8d7543afec9..9d2a52df539 100644 --- a/rs/moq-audio/tests/integration/import.rs +++ b/rs/moq-audio/tests/integration/import.rs @@ -34,7 +34,7 @@ async fn ts_surround_opus_decodes() { // Canonical 5.1 order: FL, FR, FC, LFE, SL, SR. let mut energy = [0.0f64; 6]; let mut frames = 0; - while let Some(frame) = moq_clock::timeout(Duration::from_secs(5), next_frame(&mut consumer)) + while let Some(frame) = kio::clock::timeout(Duration::from_secs(5), next_frame(&mut consumer)) .await .expect("decoded frame timed out") .unwrap() diff --git a/rs/moq-audio/tests/integration/playback.rs b/rs/moq-audio/tests/integration/playback.rs index 3acad1854c9..a7b484ac14b 100644 --- a/rs/moq-audio/tests/integration/playback.rs +++ b/rs/moq-audio/tests/integration/playback.rs @@ -54,15 +54,18 @@ async fn open() -> playback::Engine { // The first pull fills the device's buffer at once, so only a clock that // keeps moving after it shows the device is playing. - let deadline = moq_clock::Instant::now() + Duration::from_secs(10); + let deadline = kio::clock::Instant::now() + Duration::from_secs(10); let mut first = None; loop { let clock = observer.read().expect("an observation").clock; if !clock.is_zero() && clock >= *first.get_or_insert(clock) + Duration::from_millis(100) { return engine; } - assert!(moq_clock::Instant::now() < deadline, "the device never started pulling"); - moq_clock::sleep(Duration::from_millis(10)).await; + assert!( + kio::clock::Instant::now() < deadline, + "the device never started pulling" + ); + kio::clock::sleep(Duration::from_millis(10)).await; } } @@ -114,7 +117,7 @@ async fn plays_a_tone_through_the_default_device() { for _ in 0..10 { let _ = sink.write(&tone).expect("write"); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; peaked |= sink.peak() > 0.4; // The device is consuming if the queue stays near the target latency @@ -139,7 +142,7 @@ async fn the_device_buffers_periods_not_seconds() { let mut latency = None; for _ in 0..20 { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; latency = observer.read().expect("an observation").latency; if latency.is_some() { break; @@ -171,7 +174,7 @@ async fn mixes_two_sinks_and_honors_volume() { for _ in 0..10 { let _ = loud.write(&tone).expect("write"); let _ = quiet.write(&tone).expect("write"); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; loud_peak = loud_peak.max(loud.peak()); quiet_peak = quiet_peak.max(quiet.peak()); } @@ -211,7 +214,7 @@ async fn switches_devices_without_dropping_sinks() { switched += 1; let _ = sink.write(&tone).expect("write"); - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; assert!( sink.buffered() < Duration::from_secs(1), "{} did not drain after the switch", @@ -238,7 +241,7 @@ async fn sink_outlives_its_engine() { let mut peaked = false; for _ in 0..5 { let _ = sink.write(&tone).expect("write"); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; peaked |= sink.peak() > 0.4; } diff --git a/rs/moq-auth/Cargo.toml b/rs/moq-auth/Cargo.toml index c281ea3378a..ccfe2f04a03 100644 --- a/rs/moq-auth/Cargo.toml +++ b/rs/moq-auth/Cargo.toml @@ -12,7 +12,7 @@ rust-version.workspace = true [features] default = ["client"] # The HTTP client that drives a lease against an auth server. -client = ["dep:reqwest", "dep:rustls", "dep:tokio", "moq-clock/runtime", "dep:tracing", "dep:rand"] +client = ["dep:reqwest", "dep:rustls", "dep:tokio", "kio/runtime", "dep:tracing", "dep:rand"] # The reference auth server behind `moq auth serve`: the policy a relay held, on axum. serve = ["dep:axum", "dep:tokio", "dep:tracing", "tokio/net"] @@ -22,8 +22,7 @@ axum = { workspace = true, optional = true } base64 = { workspace = true } data-encoding = { workspace = true } jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] } -kio = { workspace = true } -moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false, features = ["serde"] } +kio = { workspace = true, features = ["serde"] } moq-pattern = { workspace = true, features = ["serde"] } p256 = "0.14.0" p384 = "0.14.0" @@ -42,9 +41,9 @@ url = { workspace = true, features = ["serde"] } [dev-dependencies] anyhow = { workspace = true } +kio = { path = "../kio", features = ["runtime", "sim"] } moq-auth = { path = ".", features = ["client", "serve"] } moq-auth-published = { package = "moq-auth", version = "=0.2.1", default-features = false } -moq-clock = { path = "../moq-clock", features = ["sim"] } moq-token = "0.7" tempfile = { workspace = true } tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] } diff --git a/rs/moq-auth/MIGRATE.md b/rs/moq-auth/MIGRATE.md index c33155335a0..bbe34b364c6 100644 --- a/rs/moq-auth/MIGRATE.md +++ b/rs/moq-auth/MIGRATE.md @@ -41,9 +41,9 @@ HTTP auth servers can return that JSON shape with 403; legacy plain-text 401/403 ### `Grant` reads the ambient clock -`Grant::deadline` returns a `moq_clock::Instant` instead of a `tokio::time::Instant`, and no longer needs the `tokio` feature. -Wait on it with `moq_clock::sleep_until`, which runs on tokio's clock in production. -`deadline` and `validate` read wall time from `moq_clock::wall()`, so a test on `moq_clock::sim` or a `moq_clock::Manual` clock decides when a grant expires; stamp `expires` from that clock too. +`Grant::deadline` returns a `kio::clock::Instant` instead of a `tokio::time::Instant`, and no longer needs the `tokio` feature. +Wait on it with `kio::clock::sleep_until`, which runs on tokio's clock in production. +`deadline` and `validate` read wall time from `kio::clock::wall()`, so a test on `kio::clock::sim` or a `kio::clock::Manual` clock decides when a grant expires; stamp `expires` from that clock too. `Key::verify` and the reference server's default expiry use that wall clock too. Session `End` durations and the server's idle-session accounting use its monotonic clock, so advancing controlled time advances those durations without a host-clock wait. diff --git a/rs/moq-auth/examples/asymmetric.rs b/rs/moq-auth/examples/asymmetric.rs index 830080abada..83c001e03cd 100644 --- a/rs/moq-auth/examples/asymmetric.rs +++ b/rs/moq-auth/examples/asymmetric.rs @@ -20,8 +20,8 @@ fn main() -> anyhow::Result<()> { .with_root("rooms/meeting-123") .with_publish(["alice/**".parse()?]) .with_subscribe(["**".parse()?]) - .with_expires(moq_clock::wall() + Duration::from_secs(3600)) - .with_issued(moq_clock::wall()); + .with_expires(kio::clock::wall() + Duration::from_secs(3600)) + .with_issued(kio::clock::wall()); let token = private_key.sign(&claims)?; println!("Signed token:\n{token}\n"); diff --git a/rs/moq-auth/examples/basic.rs b/rs/moq-auth/examples/basic.rs index 225756a83f8..a875799eeee 100644 --- a/rs/moq-auth/examples/basic.rs +++ b/rs/moq-auth/examples/basic.rs @@ -15,8 +15,8 @@ fn main() -> anyhow::Result<()> { .with_root("demo") .with_publish(["my-stream/**".parse()?]) // Can publish to demo/my-stream and below .with_subscribe(["**".parse()?]) // Can subscribe to anything under demo/ - .with_expires(moq_clock::wall() + Duration::from_secs(3600)) - .with_issued(moq_clock::wall()); + .with_expires(kio::clock::wall() + Duration::from_secs(3600)) + .with_issued(kio::clock::wall()); // Validate the claims (ensures at least one publish or subscribe path). claims.validate()?; diff --git a/rs/moq-auth/src/claims.rs b/rs/moq-auth/src/claims.rs index 867c0fb191b..54d7f478827 100644 --- a/rs/moq-auth/src/claims.rs +++ b/rs/moq-auth/src/claims.rs @@ -126,14 +126,14 @@ pub struct Claims { pub subscribe: Patterns, /// The expiration time of the token as a unix timestamp (`exp`). - pub expires: Option, + pub expires: Option, /// The issued time of the token as a unix timestamp (`iat`). - pub issued: Option, + pub issued: Option, /// The time before which the token is refused, as a unix timestamp (`nbf`). /// Enforced by [`Key::verify`](crate::Key::verify). - pub not_before: Option, + pub not_before: Option, } impl Claims { @@ -158,7 +158,7 @@ impl Claims { /// Expire the token at this time. Enforced by [`Key::verify`](crate::Key::verify). /// /// Accepts an `Option` so a caller can pass one through without unwrapping it. - pub fn with_expires(mut self, at: impl Into>) -> Self { + pub fn with_expires(mut self, at: impl Into>) -> Self { self.expires = at.into(); self } @@ -166,7 +166,7 @@ impl Claims { /// Record when the token was issued. Purely informational; nothing enforces it. /// /// Accepts an `Option` so a caller can pass one through without unwrapping it. - pub fn with_issued(mut self, at: impl Into>) -> Self { + pub fn with_issued(mut self, at: impl Into>) -> Self { self.issued = at.into(); self } @@ -251,8 +251,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(moq_clock::wall() + Duration::from_secs(3600)), - issued: Some(moq_clock::wall()), + expires: Some(kio::clock::wall() + Duration::from_secs(3600)), + issued: Some(kio::clock::wall()), not_before: None, } } diff --git a/rs/moq-auth/src/client.rs b/rs/moq-auth/src/client.rs index f5a42245936..3e68ad29e4c 100644 --- a/rs/moq-auth/src/client.rs +++ b/rs/moq-auth/src/client.rs @@ -3,7 +3,7 @@ use std::pin::Pin; use std::sync::Arc; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use url::Url; use crate::lease::{self, Due, Reason}; @@ -369,7 +369,7 @@ async fn ask(server: &S, request: &Request) -> crate::Result { /// Finish a request that nothing else bounds within [`TIMEOUT`], or report the /// server as unavailable, so a stalled server cannot pile up requests. async fn bounded(request: impl Future>) -> crate::Result { - moq_clock::timeout(TIMEOUT, request).await.unwrap_or_else(|_| { + kio::clock::timeout(TIMEOUT, request).await.unwrap_or_else(|_| { Err(Error::Unavailable(format!( "the auth server did not answer within {TIMEOUT:?}" ))) @@ -614,7 +614,7 @@ mod tests { /// as zero and be refused; these tests run on a one-second cadence. fn grant(expires_in: Option, revalidate: Option) -> Grant { let mut grant = Grant::new(patterns(&["**"]), Patterns::new()); - grant.expires = expires_in.map(|d| moq_clock::wall() + d); + grant.expires = expires_in.map(|d| kio::clock::wall() + d); grant.revalidate = revalidate; grant } @@ -797,7 +797,7 @@ mod tests { struct Slow(Script); impl Post for Slow { async fn post(&self, request: &Request) -> crate::Result { - moq_clock::sleep(TIMEOUT + Duration::from_secs(1)).await; + kio::clock::sleep(TIMEOUT + Duration::from_secs(1)).await; self.0.post(request).await } async fn post_end(&self, request: &Request) -> crate::Result<()> { @@ -807,7 +807,7 @@ mod tests { let script = Script::new(Log::default(), |_| Some(Ok(grant(None, None)))); let server = Slow(script.clone()); - let start = moq_clock::now(); + let start = kio::clock::now(); let owner = match admit( server.clone(), request(), @@ -823,7 +823,7 @@ mod tests { let mut attached = request(); attached.query = Some("jwt=replacement".into()); let context = owner.context().unwrap().attach(&attached, &script.identity).unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); let Err(err) = admit(server, attached, context).await else { panic!("an attached credential waited past its bound"); }; @@ -1194,7 +1194,7 @@ mod tests { }); let mut consumer = script.connect().await.unwrap(); - let fresh = moq_clock::timeout(Duration::from_secs(3), consumer.changed()) + let fresh = kio::clock::timeout(Duration::from_secs(3), consumer.changed()) .await .expect("a re-check within the cadence") .unwrap(); @@ -1217,7 +1217,7 @@ mod tests { }); let consumer = script.connect().await.unwrap(); - let reason = moq_clock::timeout(Duration::from_secs(3), consumer.closed()) + let reason = kio::clock::timeout(Duration::from_secs(3), consumer.closed()) .await .expect("revoked within the cadence"); assert_eq!(reason, Reason::Refused); @@ -1234,7 +1234,7 @@ mod tests { }); let consumer = script.connect().await.unwrap(); - let reason = moq_clock::timeout(Duration::from_secs(3), consumer.closed()) + let reason = kio::clock::timeout(Duration::from_secs(3), consumer.closed()) .await .expect("revoked within the cadence"); assert_eq!(reason, Reason::Invalid); @@ -1244,7 +1244,7 @@ mod tests { async fn an_expired_grant_is_refused() { tokio::time::pause(); let mut grant = Grant::new(patterns(&["**"]), Patterns::new()); - grant.expires = Some(moq_clock::wall() - Duration::from_secs(1)); + grant.expires = Some(kio::clock::wall() - Duration::from_secs(1)); let script = Script::new(Log::default(), move |_| Some(Ok(grant.clone()))); assert!(matches!(script.connect().await, Err(Error::GrantExpired))); } @@ -1265,7 +1265,7 @@ mod tests { let consumer = script.connect().await.unwrap(); // A nudge's reply schedules the next re-check the same way. consumer.revalidate(); - let reason = moq_clock::timeout(Duration::from_secs(4), consumer.closed()) + let reason = kio::clock::timeout(Duration::from_secs(4), consumer.closed()) .await .expect("closed at expires"); assert_eq!(reason, Reason::Expired); @@ -1277,7 +1277,7 @@ mod tests { #[tokio::test] async fn an_outage_keeps_the_grant_until_expires() { tokio::time::pause(); - let expires = moq_clock::wall() + Duration::from_secs(3); + let expires = kio::clock::wall() + Duration::from_secs(3); let log = Log::default(); let script = Script::new(log.clone(), move |request| { Some(match request.event { @@ -1292,15 +1292,15 @@ mod tests { // `expires` is wall-clock time, which the client maps onto Tokio's clock // somewhere inside `connect`, so bracket it: the bounds hold however long it takes. - let (wall, tick) = (moq_clock::wall(), moq_clock::now()); + let (wall, tick) = (kio::clock::wall(), kio::clock::now()); let consumer = script.connect().await.unwrap(); - let earliest = tick + expires.checked_duration_since(moq_clock::wall()).unwrap(); - let latest = moq_clock::now() + expires.checked_duration_since(wall).unwrap(); + let earliest = tick + expires.checked_duration_since(kio::clock::wall()).unwrap(); + let latest = kio::clock::now() + expires.checked_duration_since(wall).unwrap(); // A millisecond either side for Tokio's timer resolution. let tolerance = Duration::from_millis(1); assert!( - moq_clock::timeout_at(earliest - tolerance, consumer.closed()) + kio::clock::timeout_at(earliest - tolerance, consumer.closed()) .await .is_err(), "an outage must not close before expires" @@ -1311,7 +1311,7 @@ mod tests { patterns(&["**"]), "the grant stands through the outage" ); - let reason = moq_clock::timeout_at(latest + tolerance, consumer.closed()) + let reason = kio::clock::timeout_at(latest + tolerance, consumer.closed()) .await .expect("closed at expires, not later"); assert_eq!(reason, Reason::Expired); @@ -1334,7 +1334,7 @@ mod tests { }); let consumer = script.connect().await.unwrap(); - let reason = moq_clock::timeout(Duration::from_secs(5), consumer.closed()) + let reason = kio::clock::timeout(Duration::from_secs(5), consumer.closed()) .await .expect("expired while the re-check was in flight"); assert_eq!(reason, Reason::Expired); @@ -1405,7 +1405,7 @@ mod tests { let consumer = client(&server).connect(request()).await.unwrap(); assert_eq!(log.events(), [Event::Connect]); consumer.revalidate(); - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(2), log.until(|log| log.iter().any(|r| r.event == Event::Revalidate)), ) @@ -1428,7 +1428,7 @@ mod tests { let consumer = client(&server).connect(request()).await.unwrap(); consumer.revalidate(); - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(2), log.until(|log| log.iter().any(|r| r.event == Event::Revalidate)), ) @@ -1439,7 +1439,7 @@ mod tests { consumer.revalidate(); // `changed` jumps to the latest grant epoch, so two replies can arrive as one // observation. The request log does not coalesce. - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(3), log.until(|log| log.iter().filter(|r| r.event == Event::Revalidate).count() >= 2), ) diff --git a/rs/moq-auth/src/grant.rs b/rs/moq-auth/src/grant.rs index 28615b51502..3ad16c15820 100644 --- a/rs/moq-auth/src/grant.rs +++ b/rs/moq-auth/src/grant.rs @@ -1,4 +1,4 @@ -use moq_clock::Wall; +use kio::clock::Wall; use moq_pattern::Patterns; use serde::{Deserialize, Serialize}; use serde_with::{DurationSeconds, serde_as}; @@ -36,7 +36,7 @@ pub struct Grant { pub mounts: BTreeMap, /// When the session closes, as unix seconds. - #[serde_as(as = "Option")] + #[serde_as(as = "Option")] pub expires: Option, /// How long until the relay asks again, in seconds. @@ -75,11 +75,11 @@ impl Grant { /// Snapshot the expiry on the ambient clock; one already past is now, and one beyond /// the clock's range is never. - pub fn deadline(&self) -> Option { + pub fn deadline(&self) -> Option { // Read the instant first, so a pause between the two reads shortens the grant // instead of extending it. - let start = moq_clock::now(); - let now = moq_clock::wall(); + let start = kio::clock::now(); + let now = kio::clock::wall(); let remaining = self.expires?.checked_duration_since(now).unwrap_or_default(); start.checked_add(remaining) } @@ -107,7 +107,7 @@ impl Grant { if let Some(label) = &self.label { moq_pattern::Pattern::literal(label).map_err(crate::Error::InvalidLabel)?; } - if self.expires.is_some_and(|expires| expires <= moq_clock::wall()) { + if self.expires.is_some_and(|expires| expires <= kio::clock::wall()) { return Err(crate::Error::GrantExpired); } Ok(()) @@ -183,7 +183,7 @@ mod tests { assert_eq!(serde_json::from_str::(r#"{"publish":["**"]}"#).unwrap(), grant); } - #[moq_clock::test] + #[kio::test] async fn validate_refuses_nothing_unbounded_and_expired() { assert!(matches!(Grant::default().validate(), Err(crate::Error::UselessGrant))); @@ -194,7 +194,7 @@ mod tests { assert!(matches!(grant.validate(), Err(crate::Error::UnboundedRevalidate))); // Exact: no grace for an auth server whose clock runs behind. - let now = moq_clock::wall(); + let now = kio::clock::wall(); grant.expires = Some(now); assert!(matches!(grant.validate(), Err(crate::Error::GrantExpired))); @@ -203,7 +203,7 @@ mod tests { grant.expires = Some(now + Duration::from_secs(60)); grant.validate().unwrap(); - moq_clock::sim::advance(Duration::from_secs(60)).await; + kio::clock::sim::advance(Duration::from_secs(60)).await; assert!( matches!(grant.validate(), Err(crate::Error::GrantExpired)), "expiry follows the ambient clock, not the host's" @@ -246,15 +246,15 @@ mod tests { /// The expiry and the instant come from one clock, so time passing before the /// snapshot never shortens the grant. - #[moq_clock::test] + #[kio::test] async fn deadline_is_the_exact_expiry() { - let start = moq_clock::now(); - let now = moq_clock::wall(); + let start = kio::clock::now(); + let now = kio::clock::wall(); let mut grant = Grant::new(patterns(&["**"]), Patterns::default()); assert_eq!(grant.deadline(), None); grant.expires = Some(now + Duration::from_secs(10)); - moq_clock::sim::advance(Duration::from_secs(4)).await; + kio::clock::sim::advance(Duration::from_secs(4)).await; assert_eq!(grant.deadline(), Some(start + Duration::from_secs(10))); grant.expires = Some(now - Duration::from_secs(1)); @@ -265,7 +265,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn expiry_saturates_to_the_wall_range() { let parse = |expires: i64| { serde_json::from_value::(serde_json::json!({"publish":["**"],"expires":expires})).unwrap() diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index ef2b3dd5ee0..6586f42f87c 100644 --- a/rs/moq-auth/src/key.rs +++ b/rs/moq-auth/src/key.rs @@ -603,7 +603,7 @@ impl Key { /// [`Claims::authorize`]. pub fn verify(&self, token: &str) -> crate::Result { let claims = self.verify_claims(token)?; - validate_times(&claims, moq_clock::wall())?; + validate_times(&claims, kio::clock::wall())?; Ok(claims) } @@ -693,7 +693,7 @@ impl Key { } /// Refuse claims expired at `now` (`exp <= now`) or not yet valid (`nbf > now`), as `jose` does. -pub(crate) fn validate_times(claims: &Claims, now: moq_clock::Wall) -> crate::Result<()> { +pub(crate) fn validate_times(claims: &Claims, now: kio::clock::Wall) -> crate::Result<()> { if claims.expires.is_some_and(|exp| exp <= now) { return Err(crate::Error::TokenExpired); } @@ -763,7 +763,7 @@ mod tests { fn patterns(texts: &[&str]) -> crate::Patterns { texts.iter().map(|text| text.parse().unwrap()).collect() } - use moq_clock::Wall; + use kio::clock::Wall; use std::time::Duration; fn create_test_key() -> Key { @@ -782,8 +782,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(moq_clock::wall() + Duration::from_secs(3600)), - issued: Some(moq_clock::wall()), + expires: Some(kio::clock::wall() + Duration::from_secs(3600)), + issued: Some(kio::clock::wall()), not_before: None, } } @@ -1133,7 +1133,7 @@ mod tests { #[test] fn test_key_verify_only_registered_claims() { let key = create_test_key(); - let now = moq_clock::wall() + let now = kio::clock::wall() .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_secs(); @@ -1171,7 +1171,7 @@ mod tests { fn test_key_verify_enforces_not_before() { let key = create_test_key(); let at = |offset: i64| { - let now = moq_clock::wall() + let now = kio::clock::wall() .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_secs() as i64; @@ -1213,22 +1213,22 @@ mod tests { fn test_key_verify_expired_token() { let key = create_test_key(); let mut claims = create_test_claims(); - claims.expires = Some(moq_clock::wall() - Duration::from_secs(3600)); // 1 hour ago + claims.expires = Some(kio::clock::wall() - Duration::from_secs(3600)); // 1 hour ago let token = key.sign(&claims).unwrap(); let result = key.verify(&token); assert!(result.is_err()); } - #[moq_clock::test] + #[kio::test] async fn token_validity_uses_the_ambient_wall() { let key = create_test_key(); let mut claims = create_test_claims(); - claims.issued = Some(moq_clock::wall()); - claims.expires = Some(moq_clock::wall() + Duration::from_secs(10)); + claims.issued = Some(kio::clock::wall()); + claims.expires = Some(kio::clock::wall() + Duration::from_secs(10)); let token = key.sign(&claims).unwrap(); key.verify(&token).unwrap(); - moq_clock::sleep(Duration::from_secs(10)).await; + kio::clock::sleep(Duration::from_secs(10)).await; assert!(matches!(key.verify(&token), Err(crate::Error::TokenExpired))); } @@ -1259,8 +1259,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(moq_clock::wall() + Duration::from_secs(3600)), - issued: Some(moq_clock::wall()), + expires: Some(kio::clock::wall() + Duration::from_secs(3600)), + issued: Some(kio::clock::wall()), not_before: None, }; @@ -2015,7 +2015,7 @@ mod tests { use std::os::unix::fs::PermissionsExt; fn temp_path(name: &str) -> std::path::PathBuf { - let unique = moq_clock::wall() + let unique = kio::clock::wall() .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos(); diff --git a/rs/moq-auth/src/lease.rs b/rs/moq-auth/src/lease.rs index fde7c48b87b..5caf903910e 100644 --- a/rs/moq-auth/src/lease.rs +++ b/rs/moq-auth/src/lease.rs @@ -118,8 +118,8 @@ pub(crate) enum Due { #[cfg(feature = "client")] #[derive(Debug)] struct Clock { - next: Option, - expires: Option, + next: Option, + expires: Option, cadence: Option, failures: u32, revision: u64, @@ -132,7 +132,7 @@ impl Clock { // A cadence too far out to schedule is no scheduled re-check; `expires` still bounds the grant. next: grant .revalidate - .and_then(|cadence| moq_clock::now().checked_add(cadence)), + .and_then(|cadence| kio::clock::now().checked_add(cadence)), expires: grant.deadline(), cadence: grant.revalidate, failures: 0, @@ -210,13 +210,13 @@ impl Producer { }; let revalidate = async { match next { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } }; let expire = async { match expires { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } }; @@ -253,7 +253,7 @@ impl Producer { let base = Duration::from_secs(1) * 2u32.saturating_pow(clock.failures.saturating_sub(1).min(16)); let base = base.min(clock.cadence.unwrap_or(BACKOFF_MAX)).min(BACKOFF_MAX); let delay = base.mul_f64(rand::rng().random_range(0.75..=1.25)); - clock.next = Some(moq_clock::now() + delay); + clock.next = Some(kio::clock::now() + delay); clock.revision = clock.revision.wrapping_add(1); drop(clock); self.clock_changed.notify_waiters(); @@ -593,12 +593,12 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(10)); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(60)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(60)); let (producer, consumer) = Producer::new(grant.clone()); - assert!(moq_clock::timeout(Duration::ZERO, producer.due()).await.is_err()); + assert!(kio::clock::timeout(Duration::ZERO, producer.due()).await.is_err()); tokio::time::advance(Duration::from_secs(10)).await; assert_eq!(producer.due().await, Due::Revalidate); - assert!(moq_clock::timeout(Duration::ZERO, producer.due()).await.is_err()); + assert!(kio::clock::timeout(Duration::ZERO, producer.due()).await.is_err()); let delay = producer.failed(); assert!(delay >= Duration::from_millis(750) && delay <= Duration::from_millis(1250)); @@ -609,7 +609,7 @@ mod tests { producer.update(grant); consumer.revalidate(); assert_eq!(producer.due().await, Due::Revalidate); - assert!(moq_clock::timeout(Duration::ZERO, producer.due()).await.is_err()); + assert!(kio::clock::timeout(Duration::ZERO, producer.due()).await.is_err()); } #[cfg(feature = "client")] @@ -618,7 +618,7 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(30)); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(3600)); let (producer, _consumer) = Producer::new(grant.clone()); let producer = std::sync::Arc::new(producer); let waiter = tokio::spawn({ @@ -638,7 +638,7 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(30)); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(3600)); let (producer, _consumer) = Producer::new(grant); let first = producer.failed(); assert!(first >= Duration::from_millis(750) && first <= Duration::from_millis(1250)); @@ -657,7 +657,7 @@ mod tests { grant.revalidate = Some(Duration::MAX); let (producer, _consumer) = Producer::new(grant); tokio::time::advance(Duration::from_secs(3600)).await; - assert!(moq_clock::timeout(Duration::ZERO, producer.due()).await.is_err()); + assert!(kio::clock::timeout(Duration::ZERO, producer.due()).await.is_err()); } #[cfg(feature = "client")] @@ -665,7 +665,7 @@ mod tests { async fn due_expires_even_without_a_recheck() { tokio::time::pause(); let mut grant = grant("a/**"); - grant.expires = Some(moq_clock::wall() - Duration::from_secs(4)); + grant.expires = Some(kio::clock::wall() - Duration::from_secs(4)); let (producer, _consumer) = Producer::new(grant); let task = tokio::spawn(async move { producer.due().await }); tokio::task::yield_now().await; diff --git a/rs/moq-auth/src/mesh/client.rs b/rs/moq-auth/src/mesh/client.rs index ef9fbdfc54d..861a298e873 100644 --- a/rs/moq-auth/src/mesh/client.rs +++ b/rs/moq-auth/src/mesh/client.rs @@ -89,10 +89,10 @@ impl Client { let remaining = || { current .expires - .checked_duration_since(moq_clock::wall()) + .checked_duration_since(kio::clock::wall()) .unwrap_or_default() }; - moq_clock::sleep(remaining() * 2 / 3).await; + kio::clock::sleep(remaining() * 2 / 3).await; let mut backoff = Duration::from_secs(1); loop { @@ -109,7 +109,7 @@ impl Client { Err(err) if remaining().is_zero() => return Err(err), Err(err) => { tracing::warn!(%err, "mesh refresh failed; retrying"); - moq_clock::sleep(backoff.min(remaining())).await; + kio::clock::sleep(backoff.min(remaining())).await; backoff = (backoff * 2).min(MAX_BACKOFF); } } diff --git a/rs/moq-auth/src/mesh/contract_tests.rs b/rs/moq-auth/src/mesh/contract_tests.rs index f63b7e6cd5b..d8c3c13a521 100644 --- a/rs/moq-auth/src/mesh/contract_tests.rs +++ b/rs/moq-auth/src/mesh/contract_tests.rs @@ -187,7 +187,7 @@ async fn renew_refreshes_before_expiry() { let device = mesh.device(); let enrollment = device.enroll(&mesh.key(true), None).await.unwrap(); let renewed = device.renew(&enrollment).await.unwrap(); - assert!(moq_clock::wall() < enrollment.expires); + assert!(kio::clock::wall() < enrollment.expires); assert!(renewed.expires > enrollment.expires); } diff --git a/rs/moq-auth/src/mesh/coordinator.rs b/rs/moq-auth/src/mesh/coordinator.rs index 9c48418242d..3c07a78146e 100644 --- a/rs/moq-auth/src/mesh/coordinator.rs +++ b/rs/moq-auth/src/mesh/coordinator.rs @@ -87,9 +87,9 @@ struct StoredKey { hash: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] tags: Vec, - #[serde_as(as = "Option")] + #[serde_as(as = "Option")] #[serde(default, skip_serializing_if = "Option::is_none")] - expires: Option, + expires: Option, reusable: bool, #[serde(default)] used: bool, @@ -110,8 +110,8 @@ pub struct Device { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tags: Vec, /// When it first enrolled, unix seconds. - #[serde_as(as = "moq_clock::serde::UnixSeconds")] - pub enrolled: moq_clock::Wall, + #[serde_as(as = "kio::clock::serde::UnixSeconds")] + pub enrolled: kio::clock::Wall, /// Whether the owner revoked it; its next refresh fails. #[serde(default)] pub revoked: bool, @@ -128,9 +128,9 @@ pub struct KeyInfo { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tags: Vec, /// When it stops enrolling, unix seconds. - #[serde_as(as = "Option")] + #[serde_as(as = "Option")] #[serde(default, skip_serializing_if = "Option::is_none")] - pub expires: Option, + pub expires: Option, /// Whether it enrolls more than one device. pub reusable: bool, /// Whether a single-use key has enrolled its device. @@ -208,7 +208,7 @@ impl Coordinator { // than after an enrollment key is spent. config .key - .sign(&claims(EndpointId::from_bytes([0; 32]), moq_clock::wall(), None))?; + .sign(&claims(EndpointId::from_bytes([0; 32]), kio::clock::wall(), None))?; Ok(Self { config: Arc::new(config), secret: Arc::new(aws_lc_rs::hmac::Key::new(aws_lc_rs::hmac::HMAC_SHA256, &random(32))), @@ -223,9 +223,9 @@ impl Coordinator { /// Issue a fresh challenge. It holds no state until a proof uses it, so no number of /// requests can crowd out one a device is still signing. pub fn challenge(&self) -> Challenge { - let now = moq_clock::wall(); + let now = kio::clock::wall(); let expires = - now.checked_duration_since(moq_clock::Wall::UNIX_EPOCH) + now.checked_duration_since(kio::clock::Wall::UNIX_EPOCH) .unwrap_or_default() .as_secs() + CHALLENGE_TTL.as_secs(); let mut challenge = expires.to_be_bytes().to_vec(); @@ -234,7 +234,7 @@ impl Coordinator { challenge.extend_from_slice(&tag); Challenge { challenge, - expires: moq_clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(expires)), + expires: kio::clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(expires)), } } @@ -248,7 +248,7 @@ impl Coordinator { .split_once('.') .ok_or_else(|| ErrorReply::new(ErrorCode::InvalidGrant, "unknown enrollment key"))?; let hash = hex(&sha256(secret.as_bytes())); - let now = moq_clock::wall(); + let now = kio::clock::wall(); let key = inner .store .keys @@ -316,7 +316,7 @@ impl Coordinator { id: id.clone(), hash: hex(&sha256(secret.as_bytes())), tags: new.tags.clone(), - expires: new.expires_in.map(|ttl| moq_clock::wall().saturating_add(ttl)), + expires: new.expires_in.map(|ttl| kio::clock::wall().saturating_add(ttl)), reusable: new.reusable, used: false, revoked: false, @@ -413,8 +413,8 @@ impl Coordinator { return Err(invalid("unknown challenge")); } let expires = u64::from_be_bytes(challenge[..8].try_into().expect("8 bytes")); - let expires = moq_clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(expires)); - if expires <= moq_clock::wall() { + let expires = kio::clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(expires)); + if expires <= kio::clock::wall() { return Err(invalid("the challenge expired")); } if !proof.verify(&self.config.url) { @@ -463,7 +463,7 @@ impl Coordinator { endpoint, name, tags, - enrolled: moq_clock::wall(), + enrolled: kio::clock::wall(), revoked: false, }), } @@ -473,13 +473,13 @@ impl Coordinator { /// Sign a token for an enrolled `endpoint` and list the mesh. fn issue(&self, store: &Store, endpoint: EndpointId) -> Reply { let internal = |err: crate::Error| ErrorReply::new(ErrorCode::ServerError, err.to_string()); - let now = moq_clock::wall(); + let now = kio::clock::wall(); // `exp` is whole seconds on the wire; truncate so the reply matches the token. let secs = now - .checked_duration_since(moq_clock::Wall::UNIX_EPOCH) + .checked_duration_since(kio::clock::Wall::UNIX_EPOCH) .unwrap_or_default() .as_secs(); - let expires = moq_clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(secs) + self.config.token_ttl); + let expires = kio::clock::Wall::UNIX_EPOCH.saturating_add(Duration::from_secs(secs) + self.config.token_ttl); let token = self .config .key @@ -536,7 +536,7 @@ fn refuse_revoked(store: &Store, endpoint: EndpointId) -> Reply<()> { } /// The grant every mesh token carries: publish under its own ID, subscribe to the mesh. -fn claims(endpoint: EndpointId, issued: moq_clock::Wall, expires: Option) -> Claims { +fn claims(endpoint: EndpointId, issued: kio::clock::Wall, expires: Option) -> Claims { Claims::default() .with_publish([endpoint.publish()]) .with_subscribe([Pattern::subtree("mesh").expect("a valid path")]) @@ -704,7 +704,7 @@ mod tests { endpoint: EndpointId::from_bytes([byte; 32]), name: name.into(), tags: Vec::new(), - enrolled: moq_clock::wall(), + enrolled: kio::clock::wall(), revoked: false, }; let devices = vec![device(1, "robot"), device(2, "robot-2")]; diff --git a/rs/moq-auth/src/mesh/mod.rs b/rs/moq-auth/src/mesh/mod.rs index cd00171ce93..137cb25b006 100644 --- a/rs/moq-auth/src/mesh/mod.rs +++ b/rs/moq-auth/src/mesh/mod.rs @@ -165,8 +165,8 @@ pub struct Challenge { #[serde_as(as = "serde_with::base64::Base64")] pub challenge: Vec, /// When the coordinator stops accepting a proof over it, unix seconds. - #[serde_as(as = "moq_clock::serde::UnixSeconds")] - pub expires: moq_clock::Wall, + #[serde_as(as = "kio::clock::serde::UnixSeconds")] + pub expires: kio::clock::Wall, } /// Proof that the caller holds `endpoint`'s secret key: its signature over @@ -256,8 +256,8 @@ pub struct Enrollment { /// A JWT granting publish on `mesh//**` and subscribe on `mesh/**`, rooted at `/`. pub token: String, /// When the token expires, unix seconds. Refresh before then. - #[serde_as(as = "moq_clock::serde::UnixSeconds")] - pub expires: moq_clock::Wall, + #[serde_as(as = "kio::clock::serde::UnixSeconds")] + pub expires: kio::clock::Wall, /// The relays to dial, presenting the token. pub relays: Vec, /// The name the coordinator assigned this device. diff --git a/rs/moq-auth/src/peer.rs b/rs/moq-auth/src/peer.rs index 593a39f579a..6b88fdbf8f1 100644 --- a/rs/moq-auth/src/peer.rs +++ b/rs/moq-auth/src/peer.rs @@ -39,17 +39,17 @@ pub struct PeerGrant { pub presenter: Key, /// When the relay issued the grant (`iat`). - pub issued: moq_clock::Wall, + pub issued: kio::clock::Wall, /// When the grant lapses (`exp`). - pub expires: moq_clock::Wall, + pub expires: kio::clock::Wall, } impl PeerGrant { /// A grant bound to `presenter`, valid from `issued` until `expires`, granting nothing yet. /// /// Fails unless `presenter` is a public asymmetric key. - pub fn new(presenter: Key, issued: moq_clock::Wall, expires: moq_clock::Wall) -> crate::Result { + pub fn new(presenter: Key, issued: kio::clock::Wall, expires: kio::clock::Wall) -> crate::Result { validate_presenter(&presenter)?; Ok(Self { root: String::new(), @@ -181,7 +181,7 @@ impl Key { grant.validate()?; self.validate_scope(&grant.as_claims())?; - if grant.expires <= moq_clock::wall() { + if grant.expires <= kio::clock::wall() { return Err(crate::Error::TokenExpired); } Ok(grant) @@ -256,10 +256,10 @@ mod wire { pub subscribe: Patterns, /// RFC 7800 confirmation: the presenter's public key. pub cnf: Confirmation, - #[serde_as(as = "moq_clock::serde::UnixSeconds")] - pub iat: moq_clock::Wall, - #[serde_as(as = "moq_clock::serde::UnixSeconds")] - pub exp: moq_clock::Wall, + #[serde_as(as = "kio::clock::serde::UnixSeconds")] + pub iat: kio::clock::Wall, + #[serde_as(as = "kio::clock::serde::UnixSeconds")] + pub exp: kio::clock::Wall, } #[derive(Serialize, Deserialize)] @@ -294,7 +294,7 @@ mod tests { } fn grant(presenter: &Key) -> PeerGrant { - let now = moq_clock::wall(); + let now = kio::clock::wall(); PeerGrant::new(presenter.to_public().unwrap(), now, now + Duration::from_secs(60)) .unwrap() .with_root("room") @@ -403,7 +403,7 @@ mod tests { fn expired_grant_is_refused() { let relay = relay(Algorithm::EdDSA); let presenter = presenter(); - let now = moq_clock::wall(); + let now = kio::clock::wall(); let mut expired = grant(&presenter); expired.issued = now.checked_sub(Duration::from_secs(120)).unwrap(); expired.expires = now.checked_sub(Duration::from_secs(60)).unwrap(); @@ -423,7 +423,7 @@ mod tests { #[test] fn presenter_must_be_public_and_asymmetric() { - let now = moq_clock::wall(); + let now = kio::clock::wall(); let later = now + Duration::from_secs(60); assert!(PeerGrant::new(presenter(), now, later).is_err()); assert!(PeerGrant::new(Key::generate(Algorithm::HS256, None).unwrap(), now, later).is_err()); @@ -449,7 +449,7 @@ mod tests { #[test] fn useless_grant_is_refused() { let relay = relay(Algorithm::ES256); - let now = moq_clock::wall(); + let now = kio::clock::wall(); let empty = PeerGrant::new(presenter().to_public().unwrap(), now, now + Duration::from_secs(60)).unwrap(); assert!(relay.sign_peer(&empty).is_err()); } diff --git a/rs/moq-auth/src/request.rs b/rs/moq-auth/src/request.rs index 2709f48aac8..1fec61ce6bf 100644 --- a/rs/moq-auth/src/request.rs +++ b/rs/moq-auth/src/request.rs @@ -1,4 +1,4 @@ -use moq_clock::Wall; +use kio::clock::Wall; use serde::{Deserialize, Serialize}; use serde_with::base64::{Base64, UrlSafe}; use serde_with::formats::Unpadded; @@ -241,7 +241,7 @@ pub struct Peer { /// SHA-256 of the leaf certificate, hex. pub fingerprint: String, /// The certificate's notAfter. - #[serde_as(as = "Option")] + #[serde_as(as = "Option")] pub expires: Option, /// The issuer's distinguished name. pub issuer: String, diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index 452383a1aa6..b59a4832ebf 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -19,7 +19,7 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::post; use axum::{Json, Router}; -use moq_clock::Instant; +use kio::clock::Instant; use crate::{Event, Grant, Key, KeyId, KeySet, Permissions, Request, Token}; @@ -262,7 +262,7 @@ impl Policy { let mut grant = Grant::new(permissions.publish, permissions.subscribe); grant.expires = match (expires, self.expires) { (Some(expires), _) => Some(expires), - (None, Some(bound)) => Some(moq_clock::wall().checked_add(bound).ok_or(Denial::ExpiresOutOfRange)?), + (None, Some(bound)) => Some(kio::clock::wall().checked_add(bound).ok_or(Denial::ExpiresOutOfRange)?), (None, None) => None, }; grant.revalidate = self.revalidate; @@ -303,7 +303,7 @@ impl Policy { crate::Error::Key(crate::KeyError::KeyNotFound(_)) => Denial::UnknownKey, other => Denial::InvalidToken(other.to_string()), })?; - crate::key::validate_times(&claims, moq_clock::wall()).map_err(|err| match err { + crate::key::validate_times(&claims, kio::clock::wall()).map_err(|err| match err { crate::Error::TokenExpired => Denial::Expired { root: claims.root.clone(), }, @@ -471,7 +471,7 @@ impl Server { } if policy .expires - .is_some_and(|bound| moq_clock::wall().checked_add(bound).is_none()) + .is_some_and(|bound| kio::clock::wall().checked_add(bound).is_none()) { return Err(crate::Error::ExpiresOutOfRange); } @@ -638,7 +638,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn default_expiry_uses_the_ambient_wall() { let policy = Policy { public: rules(&["**"], &[]), @@ -646,7 +646,7 @@ mod tests { ..Default::default() }; let grant = policy.decide(&request("/demo")).await.unwrap(); - assert_eq!(grant.expires, Some(moq_clock::wall() + Duration::from_secs(30))); + assert_eq!(grant.expires, Some(kio::clock::wall() + Duration::from_secs(30))); } fn with_token(mut request: Request, jwt: &str) -> Request { @@ -654,7 +654,7 @@ mod tests { request } - fn with_peer(mut request: Request, expires: Option) -> Request { + fn with_peer(mut request: Request, expires: Option) -> Request { request.tls = Some(Peer { name: "edge0".into(), fingerprint: "ab".repeat(32), @@ -672,7 +672,7 @@ mod tests { (dir, key) } - fn sign(key: &Key, root: &str, publish: &[&str], subscribe: &[&str], expires: Option) -> String { + fn sign(key: &Key, root: &str, publish: &[&str], subscribe: &[&str], expires: Option) -> String { let claims = Claims::default() .with_root(root) .with_publish(patterns(publish)) @@ -716,12 +716,12 @@ mod tests { ..Default::default() }; // `exp` is whole seconds on the wire. - let secs = moq_clock::wall() - .checked_duration_since(moq_clock::Wall::UNIX_EPOCH) + let secs = kio::clock::wall() + .checked_duration_since(kio::clock::Wall::UNIX_EPOCH) .unwrap() .as_secs() + 600; - let exp = moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(secs); + let exp = kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(secs); let jwt = sign(&key, "demo/room", &["alice/**"], &["**"], Some(exp)); let grant = policy.decide(&with_token(request("/demo/room/"), &jwt)).await.unwrap(); @@ -742,11 +742,11 @@ mod tests { ..Default::default() }; let jwt = sign(&key, "demo", &["**"], &[], None); - let before = moq_clock::wall(); + let before = kio::clock::wall(); let grant = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap(); let expires = grant.expires.unwrap(); assert!(expires >= before + Duration::from_secs(3600)); - assert!(expires <= moq_clock::wall() + Duration::from_secs(3600)); + assert!(expires <= kio::clock::wall() + Duration::from_secs(3600)); } #[tokio::test] @@ -784,7 +784,7 @@ mod tests { "demo", &["**"], &[], - Some(moq_clock::wall() - Duration::from_secs(1)), + Some(kio::clock::wall() - Duration::from_secs(1)), ); let err = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(); assert!(matches!(err, Denial::Expired { .. }), "{err}"); @@ -1051,7 +1051,7 @@ mod tests { mtls: rules(&["**"], &["**"]), ..Default::default() }; - let not_after = moq_clock::wall() + Duration::from_secs(86400 * 30); + let not_after = kio::clock::wall() + Duration::from_secs(86400 * 30); let grant = policy.decide(&with_peer(request("/"), Some(not_after))).await.unwrap(); assert_eq!(grant.publish, patterns(&["**"])); assert_eq!(grant.expires, Some(not_after)); @@ -1366,7 +1366,7 @@ mod tests { "demo", &["**"], &[], - Some(moq_clock::wall() + Duration::from_secs(60)), + Some(kio::clock::wall() + Duration::from_secs(60)), ); let mut same_host = with_token(request("/demo"), &other); same_host.remote = Some("[::ffff:203.0.113.9]:9".parse().unwrap()); @@ -1392,7 +1392,7 @@ mod tests { ..limited() }) .unwrap(); - let exp = Some(moq_clock::wall() + Duration::from_secs(60)); + let exp = Some(kio::clock::wall() + Duration::from_secs(60)); let a = sign(&key, "demo", &["**"], &[], None); let b = sign(&key, "demo", &["**"], &[], exp); let c = sign( @@ -1400,7 +1400,7 @@ mod tests { "demo", &["**"], &[], - Some(moq_clock::wall() + Duration::from_secs(61)), + Some(kio::clock::wall() + Duration::from_secs(61)), ); let mut first = with_token(request("/demo"), &a); @@ -1456,7 +1456,7 @@ mod tests { use crate::refusal::Reason; let (dir, key) = key_dir(); let stranger = Key::generate(Algorithm::HS256, key.kid.clone()).unwrap(); - let expired = Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); + let expired = Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); for tier in [None, Some("edge")] { let (client, _) = serve(Policy { keys: Some(Keys::Dir(dir.path().into())), @@ -1526,7 +1526,7 @@ mod tests { "attacker", &["**"], &[], - Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)), + Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1)), ); let Error::Refused(refusal) = client .connect(with_token(request("/attacker"), &token)) diff --git a/rs/moq-auth/src/set.rs b/rs/moq-auth/src/set.rs index 0999e831cea..3c3cd6d99e5 100644 --- a/rs/moq-auth/src/set.rs +++ b/rs/moq-auth/src/set.rs @@ -144,7 +144,7 @@ mod tests { texts.iter().map(|text| text.parse().unwrap()).collect() } use crate::Algorithm; - use moq_clock::Wall; + use kio::clock::Wall; use std::time::Duration; fn create_test_claims() -> Claims { @@ -152,8 +152,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(moq_clock::wall() + Duration::from_secs(3600)), - issued: Some(moq_clock::wall()), + expires: Some(kio::clock::wall() + Duration::from_secs(3600)), + issued: Some(kio::clock::wall()), not_before: None, } } @@ -370,7 +370,7 @@ mod tests { // Use a random-ish name to avoid collisions let filename = format!( "test_keyset_{}.json", - moq_clock::wall() + kio::clock::wall() .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos() @@ -392,7 +392,7 @@ mod tests { fn test_file_io_permissions() { use std::os::unix::fs::PermissionsExt; - let unique = moq_clock::wall() + let unique = kio::clock::wall() .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos(); diff --git a/rs/moq-auth/src/wire.rs b/rs/moq-auth/src/wire.rs index 61c4896e117..8309bdb5b8d 100644 --- a/rs/moq-auth/src/wire.rs +++ b/rs/moq-auth/src/wire.rs @@ -27,12 +27,12 @@ pub(crate) struct Claims { publish: Option, #[serde(deserialize_with = "present")] subscribe: Option, - #[serde_as(as = "Option")] - exp: Option, - #[serde_as(as = "Option")] - iat: Option, - #[serde_as(as = "Option")] - nbf: Option, + #[serde_as(as = "Option")] + exp: Option, + #[serde_as(as = "Option")] + iat: Option, + #[serde_as(as = "Option")] + nbf: Option, // Registered claims that narrow nothing: an issuer's bookkeeping, read and dropped. // Every other claim is refused, since an unknown one may narrow the grant, and a // misspelled `root` would otherwise widen it to everything. diff --git a/rs/moq-bench/Cargo.toml b/rs/moq-bench/Cargo.toml index 146dfc159dc..2cdcb12f2b5 100644 --- a/rs/moq-bench/Cargo.toml +++ b/rs/moq-bench/Cargo.toml @@ -46,7 +46,7 @@ websocket = ["moq-tokio/websocket"] [dependencies] anyhow = { workspace = true, features = ["backtrace"] } humantime = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-net = { workspace = true } moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "net"] } rand = { workspace = true } diff --git a/rs/moq-bench/src/config.rs b/rs/moq-bench/src/config.rs index 2fcece1acbe..53926786eb6 100644 --- a/rs/moq-bench/src/config.rs +++ b/rs/moq-bench/src/config.rs @@ -225,7 +225,7 @@ impl Config { deprecated.extend(config.deprecated()); anyhow::ensure!(deprecated.is_empty(), "{deprecated}"); config.origins = Some(resolved); - // `Stats::report` feeds this into `moq_clock::interval`, which panics on a + // `Stats::report` feeds this into `kio::clock::interval`, which panics on a // zero period. Reject it up front with a clear message. anyhow::ensure!(!config.report().is_zero(), "--report must be greater than 0s"); if let Some(fanout) = &config.fanout { @@ -485,7 +485,7 @@ url = "https://example.com" #[test] fn zero_report_is_rejected() { - // A zero report interval would panic `moq_clock::interval`; reject it early. + // A zero report interval would panic `kio::clock::interval`; reject it early. let err = Config::parse_and_merge(["moq-bench", "--report", "0s"]).unwrap_err(); assert!(err.to_string().contains("report"), "unexpected error: {err}"); } diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index 84ff24c907b..3026ccdad9b 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -1,4 +1,4 @@ -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::HashSet; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -244,8 +244,8 @@ async fn produce( let zeros = Bytes::from(vec![0u8; rolled.frame_size as usize]); let period = Duration::from_secs_f64(1.0 / rolled.fps as f64); - let mut ticker = moq_clock::interval(period); - ticker.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); + let mut ticker = kio::clock::interval(period); + ticker.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Delay); let mut sequence = 0u64; loop { @@ -262,7 +262,7 @@ async fn produce( group_size: rolled.group_size, broadcasts: rolled.broadcasts, subscribe: rolled.subscribe, - timestamp_ms: moq_clock::wall() + timestamp_ms: kio::clock::wall() .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(), pad: String::new(), @@ -346,7 +346,7 @@ async fn subscribe( let mut eligible = 0; // Gather candidates until the startup window closes (or the announce stream ends). - let deadline = moq_clock::sleep(startup); + let deadline = kio::clock::sleep(startup); tokio::pin!(deadline); loop { tokio::select! { diff --git a/rs/moq-bench/src/host.rs b/rs/moq-bench/src/host.rs index 439ba50e1c8..86490577573 100644 --- a/rs/moq-bench/src/host.rs +++ b/rs/moq-bench/src/host.rs @@ -16,7 +16,7 @@ #[cfg(target_os = "linux")] mod linux { - use moq_clock::Wall; + use kio::clock::Wall; use std::collections::HashMap; use std::io::Write; use std::time::Duration; @@ -231,7 +231,7 @@ mod linux { target.ctx.retain(|tid| live.contains(&tid)); Ok(Sample { - timestamp_ms: moq_clock::wall() + timestamp_ms: kio::clock::wall() .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(), pid: target.proc.pid, @@ -277,7 +277,7 @@ mod linux { .join(", ") ); - let start = moq_clock::now(); + let start = kio::clock::now(); loop { // Host-wide once per round: unlike the per-target reads inside `sample`, // a failure here is not a target exiting, so it fails the run. diff --git a/rs/moq-bench/src/main.rs b/rs/moq-bench/src/main.rs index c176871ab64..28e59fee506 100644 --- a/rs/moq-bench/src/main.rs +++ b/rs/moq-bench/src/main.rs @@ -83,7 +83,7 @@ async fn main() -> anyhow::Result<()> { stats: stats.clone(), }; tasks.spawn(async move { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; connection::run(ctx).await; }); } @@ -91,7 +91,7 @@ async fn main() -> anyhow::Result<()> { let duration = config.duration.map(Into::into); let stop = async move { match duration { - Some(d) => moq_clock::sleep(d).await, + Some(d) => kio::clock::sleep(d).await, None => std::future::pending::<()>().await, } }; diff --git a/rs/moq-bench/src/stats.rs b/rs/moq-bench/src/stats.rs index ec4382ec12a..92433bd3bff 100644 --- a/rs/moq-bench/src/stats.rs +++ b/rs/moq-bench/src/stats.rs @@ -1,4 +1,4 @@ -use moq_clock::Wall; +use kio::clock::Wall; use std::io::Write; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -106,7 +106,7 @@ impl Stats { /// Record one group keyframe's wall-clock delivery latency. pub fn latency(&self, sent_ms: u128) { // Read the clock before locking so contention is not measured as latency. - let now_ms = moq_clock::wall() + let now_ms = kio::clock::wall() .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(); self.latency.observe(sent_ms, now_ms); @@ -130,7 +130,7 @@ impl Stats { /// recorded stats are partial is invalid, so the caller must fail the run /// rather than exit green. pub async fn report(&self, interval: Duration, mut output: Option) -> anyhow::Result<()> { - let mut ticker = moq_clock::interval(interval); + let mut ticker = kio::clock::interval(interval); // Skip the immediate first tick so the first report covers a full interval. ticker.tick().await; @@ -435,7 +435,7 @@ impl Latency { // include only part of an observation. One that reads the clock before the // boundary but locks after it counts in the next interval, unaltered. let state = self.state.lock().expect("latency lock poisoned"); - let captured_at = moq_clock::wall(); + let captured_at = kio::clock::wall(); let LatencyState { buckets, max_ms, diff --git a/rs/moq-boy/Cargo.toml b/rs/moq-boy/Cargo.toml index cec2ba135d4..2e1df4f2fd1 100644 --- a/rs/moq-boy/Cargo.toml +++ b/rs/moq-boy/Cargo.toml @@ -33,8 +33,8 @@ anyhow = { workspace = true, features = ["backtrace"] } boytacean = { version = "0.13", features = ["gen-mock"] } bytes = { workspace = true } hang = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-audio = { workspace = true } -moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-boy/src/input.rs b/rs/moq-boy/src/input.rs index dd17d750a8c..b7c954e7acc 100644 --- a/rs/moq-boy/src/input.rs +++ b/rs/moq-boy/src/input.rs @@ -209,7 +209,7 @@ mod tests { tokio::spawn(async move { handle_viewers(&consumer, &tx).await }); let (_viewer, track) = viewer(&origin); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; send(&track, "not json"); send(&track, r#"{"type":"explode"}"#); send(&track, r#"{"type":"buttons","buttons":["turbo"]}"#); @@ -245,25 +245,25 @@ mod tests { tokio::spawn(async move { handle_viewers(&consumer, &tx).await }); let (old, old_track) = viewer(&origin); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; send(&old_track, r#"{"type":"reset"}"#); assert!(matches!(rx.recv().await, Some(Command::Reset))); old.unannounce(); assert!(matches!(rx.recv().await, Some(Command::ViewerLeft { .. }))); let (_new, new_track) = viewer(&origin); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; // The old track is still live: anything it says now comes from a stale reader. send(&old_track, r#"{"type":"reset"}"#); drop(old_track); drop(old); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; send(&new_track, r#"{"type":"buttons","buttons":[]}"#); let next = rx.recv().await; assert!(matches!(next, Some(Command::Buttons { .. })), "{next:?}"); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(rx.try_recv().is_err(), "the old reader is still running"); } } diff --git a/rs/moq-boy/src/main.rs b/rs/moq-boy/src/main.rs index deff337f231..ef510255940 100644 --- a/rs/moq-boy/src/main.rs +++ b/rs/moq-boy/src/main.rs @@ -25,7 +25,7 @@ use anyhow::{Context, Result}; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/rs/moq-boy/src/stats.rs b/rs/moq-boy/src/stats.rs index edd8af3f9e9..ebb09660347 100644 --- a/rs/moq-boy/src/stats.rs +++ b/rs/moq-boy/src/stats.rs @@ -3,7 +3,7 @@ //! Tracks how much wall-clock time is spent on emulation, video encoding, //! and audio encoding. Published to viewers via the status track. -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; use serde::Serialize; diff --git a/rs/moq-boy/src/video.rs b/rs/moq-boy/src/video.rs index 655d6ce44eb..4916a8582ba 100644 --- a/rs/moq-boy/src/video.rs +++ b/rs/moq-boy/src/video.rs @@ -6,7 +6,7 @@ //! encode and the avc3 publish; this module keeps moq-boy's threading, //! frame-dropping, force-keyframe and timing-stats behavior. -use moq_clock::Instant; +use kio::clock::Instant; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Duration; diff --git a/rs/moq-c/Cargo.toml b/rs/moq-c/Cargo.toml index f9973efee35..0b116b6fd7b 100644 --- a/rs/moq-c/Cargo.toml +++ b/rs/moq-c/Cargo.toml @@ -49,7 +49,7 @@ url = { workspace = true } cbindgen = "0.29" [dev-dependencies] -moq-clock = { path = "../moq-clock" } +kio = { path = "../kio", features = ["runtime"] } moq-loc = { path = "../moq-loc" } # The tests encode with OpenH264, the one encoder a GPU-less host has, so they # turn it on without the `openh264` feature. diff --git a/rs/moq-c/src/id.rs b/rs/moq-c/src/id.rs index 420fc6796fb..820a360bd9b 100644 --- a/rs/moq-c/src/id.rs +++ b/rs/moq-c/src/id.rs @@ -156,7 +156,7 @@ mod tests { slab.map.insert(Id::try_from(raw).unwrap(), 0); } let iterations = 1000; - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); for _ in 0..iterations { if wrap { next.store(i32::MAX as u32, Ordering::Relaxed); diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index fdc0911e936..0f2bf7defb7 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -1510,7 +1510,7 @@ mod children_tests { let (broadcast, track, media, readers) = children(&mut state).await; state.publish_close(broadcast).unwrap().run().unwrap(); for mut reader in readers { - let read = moq_clock::timeout(TIMEOUT, reader.recv_group()).await; + let read = kio::clock::timeout(TIMEOUT, reader.recv_group()).await; assert!(matches!( read.expect("the track carried on"), Err(moq_net::Error::Unroutable) @@ -1543,7 +1543,7 @@ mod children_tests { state.publish_close(broadcast).unwrap().run().unwrap(); for mut reader in readers { - let read = moq_clock::timeout(TIMEOUT, reader.recv_group()).await; + let read = kio::clock::timeout(TIMEOUT, reader.recv_group()).await; assert!(matches!( read.expect("the track carried on"), Err(moq_net::Error::Unroutable) @@ -1569,7 +1569,7 @@ mod children_tests { state.publish.media_finish(media).unwrap(); state.publish_close(broadcast).unwrap().run().unwrap(); for mut reader in readers { - let read = moq_clock::timeout(TIMEOUT, reader.recv_group()).await; + let read = kio::clock::timeout(TIMEOUT, reader.recv_group()).await; assert!(matches!(read.expect("the track carried on"), Ok(None))); } } diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index ac4be83b61b..89cce4b069d 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -36,7 +36,7 @@ fn publish_broadcast(origin: u32, path: &[u8]) -> u32 { /// asynchronously, so an early request can race the attach and fail as unroutable; /// retry until the deadline. fn request_broadcast(origin: u32, path: &[u8]) -> u32 { - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; loop { let cb = Callback::new(); let _task = id(unsafe { @@ -56,7 +56,7 @@ fn request_broadcast(origin: u32, path: &[u8]) -> u32 { return code as u32; } // A failed request already delivered its terminal code; back off and retry. - assert!(moq_clock::now() < deadline, "timed out requesting broadcast: {code}"); + assert!(kio::clock::now() < deadline, "timed out requesting broadcast: {code}"); #[expect( clippy::disallowed_methods, reason = "the test thread has no runtime; it polls the C API's runtime between real retries" @@ -5318,9 +5318,9 @@ fn a_stalled_encode_does_not_block_unrelated_calls() { // Wait until it has resolved the handle, so it is genuinely inside the stalled // call rather than still on its way in: the slab holds one reference, this test // a second, and the parked publish is the third. - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; while handle.holders() < 3 { - assert!(moq_clock::now() < deadline, "the publish never reached the encoder"); + assert!(kio::clock::now() < deadline, "the publish never reached the encoder"); std::thread::yield_now(); } @@ -6347,14 +6347,14 @@ fn rate(reservation: u32) -> Option { /// Wait for `reservation`'s grant to reach `bps`, since a subscription reaches the /// allocator asynchronously and an unwatched track already reads a would-be share. fn wait_rate(reservation: u32, bps: u64) { - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; loop { let last = rate(reservation); if last == Some(bps) { return; } assert!( - moq_clock::now() < deadline, + kio::clock::now() < deadline, "timed out waiting for a {bps} bps rate, last {last:?}" ); #[expect( diff --git a/rs/moq-c/src/video.rs b/rs/moq-c/src/video.rs index 759c4cf862b..83c13a75f2a 100644 --- a/rs/moq-c/src/video.rs +++ b/rs/moq-c/src/video.rs @@ -1497,7 +1497,7 @@ mod follow_tests { }); assert_eq!(moved, Ok(None)); - let retried = moq_clock::timeout(Duration::from_secs(60), follower.next()) + let retried = kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .expect("the dropped target is asked for again"); assert_eq!(retried.unwrap(), Target::Enabled(Rate::from_mbps(2))); @@ -1512,7 +1512,7 @@ mod follow_tests { /// Retune at every target until the follower goes a minute without one. async fn quiet(follower: &mut Follower, ceiling: Rate, mut set: impl FnMut(Rate) -> Result<(), moq_video::Error>) { - while let Ok(bitrate) = moq_clock::timeout(Duration::from_secs(60), follower.next()).await { + while let Ok(bitrate) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await { rate(follower, ceiling, bitrate.unwrap(), &mut set).unwrap(); } } diff --git a/rs/moq-cli/Cargo.toml b/rs/moq-cli/Cargo.toml index 516d1820468..7005aa88530 100644 --- a/rs/moq-cli/Cargo.toml +++ b/rs/moq-cli/Cargo.toml @@ -107,10 +107,10 @@ bytes = { workspace = true } futures = { workspace = true } hang = { workspace = true } humantime = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-archive = { workspace = true } moq-audio = { workspace = true, optional = true, features = ["aac"] } moq-auth = { workspace = true, features = ["serve"] } -moq-clock = { workspace = true } # `server` enables the HTTP egress server for `moq export hls`; the importer is always available. moq-hls = { workspace = true, features = ["server"] } # Writes and reads the stats and feedback snapshots. diff --git a/rs/moq-cli/src/announced.rs b/rs/moq-cli/src/announced.rs index 4cdaa94b26c..91cba68c204 100644 --- a/rs/moq-cli/src/announced.rs +++ b/rs/moq-cli/src/announced.rs @@ -231,7 +231,7 @@ mod tests { // Every broadcast is on the relay before anything follows it. for (path, _) in &broadcasts { - moq_clock::timeout(TIMEOUT, relay.follow(*path, None).unwrap().available()) + kio::clock::timeout(TIMEOUT, relay.follow(*path, None).unwrap().available()) .await .expect("relay routes the broadcast") .expect("broadcast"); @@ -273,7 +273,7 @@ mod tests { /// The next line printed. async fn next(lines: &mut Lines>) -> String { - moq_clock::timeout(TIMEOUT, lines.next_line()) + kio::clock::timeout(TIMEOUT, lines.next_line()) .await .expect("a line in time") .expect("read") @@ -351,7 +351,7 @@ mod tests { assert_eq!(next(&mut lines).await, "+ other/c"); fixture.shutdown.start(); - let result = moq_clock::timeout(TIMEOUT, task) + let result = kio::clock::timeout(TIMEOUT, task) .await .expect("exits once the session ends") .expect("task"); diff --git a/rs/moq-cli/src/archive.rs b/rs/moq-cli/src/archive.rs index 4adcd2be007..361d4e7d984 100644 --- a/rs/moq-cli/src/archive.rs +++ b/rs/moq-cli/src/archive.rs @@ -345,7 +345,7 @@ mod tests { // Each recording ends with its broadcast, once it subscribed. for (broadcast, mut track) in broadcasts.drain(..2) { - moq_clock::timeout(Duration::from_secs(10), track.subscription_changed()) + kio::clock::timeout(Duration::from_secs(10), track.subscription_changed()) .await .expect("the export subscribes") .unwrap(); @@ -356,9 +356,9 @@ mod tests { format!("live/a/@{}/.end", epochs[0]), format!("live/b/@{}/.end", epochs[1]), ]; - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { while !complete.iter().all(|end| dir.path().join(end).exists()) { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -400,9 +400,9 @@ mod tests { let recording = tokio::spawn(moq_archive::Producer::new(open(&url).unwrap(), source.consume(), Default::default()).run()); // Its objects, then the markers once the broadcast ends. - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { while files(dir.path()).len() < 2 { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -418,7 +418,7 @@ mod tests { let epoch = moq_net::Epoch::mint(); let _import = tokio::spawn(import(origin.clone(), "replay".into(), args, epoch.clone())); let mut announced = origin.consume().announced(); - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { loop { if let Some(moq_net::announce::Event::Start(announce)) = announced.next().await { assert_eq!(announce.prefix.as_str(), "replay"); diff --git a/rs/moq-cli/src/auth.rs b/rs/moq-cli/src/auth.rs index 5e44a9725fa..c626fd5025c 100644 --- a/rs/moq-cli/src/auth.rs +++ b/rs/moq-cli/src/auth.rs @@ -789,9 +789,9 @@ fn read_token(path: &std::path::Path) -> anyhow::Result { } #[derive(Clone, Copy, Debug)] -struct UnixTimestamp(moq_clock::Wall); +struct UnixTimestamp(kio::clock::Wall); -impl From for moq_clock::Wall { +impl From for kio::clock::Wall { fn from(value: UnixTimestamp) -> Self { value.0 } @@ -805,7 +805,7 @@ impl std::str::FromStr for UnixTimestamp { let timestamp = timestamp.try_into().context("timestamp out of range")?; // Past 2554 saturates, like a decoded token time. Ok(Self( - moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(timestamp)), + kio::clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(timestamp)), )) } } @@ -1289,8 +1289,8 @@ mod tests { #[test] fn timestamp_past_the_wall_range_saturates() { - let last = moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); - let parse = |text: &str| moq_clock::Wall::from(text.parse::().unwrap()); + let last = kio::clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); + let parse = |text: &str| kio::clock::Wall::from(text.parse::().unwrap()); assert_eq!(parse(&i64::MAX.to_string()), last); assert!(parse("18446744073") < last); } diff --git a/rs/moq-cli/src/complete.rs b/rs/moq-cli/src/complete.rs index d0ca4c98da8..10e001be985 100644 --- a/rs/moq-cli/src/complete.rs +++ b/rs/moq-cli/src/complete.rs @@ -20,8 +20,8 @@ use std::future::Future; use std::time::Duration; use anyhow::Context; -use moq_clock::Instant; -use moq_clock::timeout_at; +use kio::clock::Instant; +use kio::clock::timeout_at; #[cfg(feature = "capture")] use usage_rs::complete::{Candidate, CompleteCtx, CompletionFuture}; use usage_rs::complete::{CompletionOverlay, CompletionRequest, Shell, render}; diff --git a/rs/moq-cli/src/fetch.rs b/rs/moq-cli/src/fetch.rs index 770c9567aec..97993ed4aa7 100644 --- a/rs/moq-cli/src/fetch.rs +++ b/rs/moq-cli/src/fetch.rs @@ -6,8 +6,8 @@ use std::time::Duration; use anyhow::Context; use base64::Engine; use hang::moq_net; -use moq_clock::Instant; -use moq_clock::timeout_at; +use kio::clock::Instant; +use kio::clock::timeout_at; use tokio::io::{AsyncWrite, AsyncWriteExt}; use crate::args::MoqSide; diff --git a/rs/moq-cli/src/hls.rs b/rs/moq-cli/src/hls.rs index a10b1890769..7dac0cfb3c8 100644 --- a/rs/moq-cli/src/hls.rs +++ b/rs/moq-cli/src/hls.rs @@ -464,7 +464,7 @@ mod test { }; let origin = moq_tokio::origin::spawn(); let exporting = export(origin.consume(), args, "live".to_string()); - let result = moq_clock::timeout(std::time::Duration::from_secs(1), exporting).await; + let result = kio::clock::timeout(std::time::Duration::from_secs(1), exporting).await; assert!(result.is_err(), "the recording gave up: {result:?}"); } diff --git a/rs/moq-cli/src/hls/record.rs b/rs/moq-cli/src/hls/record.rs index f83814f47a4..6a8225eaf97 100644 --- a/rs/moq-cli/src/hls/record.rs +++ b/rs/moq-cli/src/hls/record.rs @@ -440,7 +440,7 @@ struct Entry { /// The rendition's discontinuity sequence for the segment; the playlist adds its offset. discontinuity: u64, /// Written on the first entry and after each discontinuity. - program_date_time: Option, + program_date_time: Option, /// The init file the instance's first media segment maps. map: Option, } @@ -684,7 +684,7 @@ mod tests { async fn record(dir: &Path, broadcaster: &Broadcaster) -> anyhow::Result<()> { let recording = Recording::create(dir.to_path_buf())?; - moq_clock::timeout(TIMEOUT, recording.run(broadcaster)) + kio::clock::timeout(TIMEOUT, recording.run(broadcaster)) .await .expect("the recording ends") } @@ -712,7 +712,7 @@ mod tests { async fn recorded(dir: &Path, name: &str) { let playlist = dir.join("video").join(name).join("media.m3u8"); // The recording writes from blocking threads, which wake nothing here. - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while !std::fs::read_to_string(&playlist).is_ok_and(|text| text.contains("\n0.m4s\n")) { tokio::task::yield_now().await; } @@ -834,7 +834,7 @@ mod tests { publisher.gop(n); } publisher.finish(); - moq_clock::timeout(TIMEOUT, recording) + kio::clock::timeout(TIMEOUT, recording) .await .expect("the recording ends") .unwrap() @@ -884,7 +884,7 @@ mod tests { .unwrap(); publisher.gop(5); publisher.gop(6); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while removed.strong_count() > 0 { tokio::task::yield_now().await; } @@ -894,7 +894,7 @@ mod tests { publisher.gop(7); publisher.finish(); - moq_clock::timeout(TIMEOUT, recording) + kio::clock::timeout(TIMEOUT, recording) .await .expect("the recording ends") .unwrap() @@ -916,7 +916,7 @@ mod tests { let recording = Recording::create(dir.path().to_path_buf()).unwrap(); // Stands in for the colliding sibling, which a case-sensitive filesystem cannot produce. std::fs::create_dir_all(dir.path().join("video").join("video0")).unwrap(); - let err = moq_clock::timeout(TIMEOUT, recording.run(&broadcaster)) + let err = kio::clock::timeout(TIMEOUT, recording.run(&broadcaster)) .await .expect("the recording ends") .unwrap_err(); @@ -942,7 +942,7 @@ mod tests { } catalog.abort(lost); - let ended = moq_clock::timeout(TIMEOUT, recording) + let ended = kio::clock::timeout(TIMEOUT, recording) .await .expect("the recording ends"); let err = ended.unwrap().expect_err("an abrupt end fails"); @@ -1041,7 +1041,7 @@ mod tests { /// running sum of durations no longer gives it. #[test] fn a_discontinuity_restates_the_program_date_time() { - let at = |secs| Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(secs)); + let at = |secs| Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(secs)); let mut playlist = Playlist::new(2); for (segment, discontinuity, secs) in [(0, 0, 0), (1, 0, 2), (2, 1, 10), (3, 1, 12)] { playlist.push(Entry { diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index a3c74d6d564..15fee8bc078 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -1118,12 +1118,12 @@ mod tests { }); let server = accepting.await.unwrap(); tokio::spawn(moq_relay::supervise(server, lease.unwrap(), observer.serve(), None)); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; reading.store(false, Ordering::Relaxed); let mut signals = Signals::new().unwrap(); let shutdown = Shutdown { trigger, observer }; - moq_clock::timeout(window * 2, drain(shutdown, &mut signals)) + kio::clock::timeout(window * 2, drain(shutdown, &mut signals)) .await .expect("a stalled session held the drain past its deadline"); let (reason, _) = producer @@ -1226,7 +1226,7 @@ mod tests { ); tokio::time::advance(Duration::from_secs(1)).await; tokio::time::resume(); - let error = moq_clock::timeout(TIMEOUT, listening.connection.closed()) + let error = kio::clock::timeout(TIMEOUT, listening.connection.closed()) .await .unwrap() .unwrap_err(); @@ -1257,12 +1257,12 @@ mod tests { moq_auth::Pattern::all(), ))); tokio::time::resume(); - let connection = moq_clock::timeout(TIMEOUT, listening.connection.clone().established()) + let connection = kio::clock::timeout(TIMEOUT, listening.connection.clone().established()) .await .unwrap() .unwrap(); // Media proves the CLI admitted the session, even on a transport that establishes early. - let payload = moq_clock::timeout(TIMEOUT, async { + let payload = kio::clock::timeout(TIMEOUT, async { let broadcast = listening .consumer .follow("probe", None) @@ -1510,7 +1510,7 @@ mod tests { } assert!( - moq_clock::timeout(std::time::Duration::from_millis(50), tasks.join_next()) + kio::clock::timeout(std::time::Duration::from_millis(50), tasks.join_next()) .await .is_err(), "the server task should still be accepting connections" diff --git a/rs/moq-cli/src/play/fake.rs b/rs/moq-cli/src/play/fake.rs index 5a614aebe0f..cc2a91ee150 100644 --- a/rs/moq-cli/src/play/fake.rs +++ b/rs/moq-cli/src/play/fake.rs @@ -5,8 +5,8 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; +use kio::clock::Instant; use moq_audio::playback::Input; -use moq_clock::Instant; use super::output::{Output, Sink, Speaker}; use super::window::Event; @@ -54,7 +54,7 @@ impl Recorder { pub fn present_frame(&self, media: &super::media::Media) -> Option { let mut video = media.video.lock().unwrap(); let presentation = media.presentation.lock().unwrap(); - let now = moq_clock::now(); + let now = kio::clock::now(); let mut shown = None; while video .front() @@ -132,7 +132,7 @@ pub(super) struct FakeSink { impl Sink for FakeSink { async fn finish(self) { - moq_clock::sleep_until(self.end).await; + kio::clock::sleep_until(self.end).await; } fn write(&mut self, samples: &[u8]) -> anyhow::Result { diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 193e4106c0b..7d4eff35425 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -11,7 +11,7 @@ use moq_mux::catalog::{self, Stream}; use moq_mux::follow::{Event as FollowEvent, Instances}; // The ambient clock, which follows tokio's paused clock when a test drives the // playout clock itself. -use moq_clock::Instant; +use kio::clock::Instant; use super::args::Args; use super::output::{Output, Sink, Speaker}; @@ -700,7 +700,7 @@ async fn play_audio( .due(role.map(frame.timestamp)?) .and_then(|at| at.checked_sub(first)); if let Some(at) = at { - moq_clock::sleep_until(at).await; + kio::clock::sleep_until(at).await; } ended = false; // An end this frame did not cross ends the timeline it resumes. @@ -773,7 +773,7 @@ async fn play_audio( .due(mapped) .and_then(|at| at.checked_sub(lead(delay, &frame))); if let Some(at) = at { - moq_clock::sleep_until(at).await; + kio::clock::sleep_until(at).await; } } @@ -837,7 +837,7 @@ async fn play_audio( async fn drain(sink: impl Sink) { // The estimated target moves, so the depth the sink was opened with says // nothing about what it holds now: read it at retirement instead. - let _ = moq_clock::timeout(sink.buffered() + AUDIO_DRAIN_GRACE, sink.finish()).await; + let _ = kio::clock::timeout(sink.buffered() + AUDIO_DRAIN_GRACE, sink.finish()).await; } #[cfg(test)] @@ -1041,7 +1041,7 @@ mod tests { pcm.keyframe = index == 0; audio.write(pcm).unwrap(); video.write(picture(index, index == 0)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } if audio_end { audio.discontinuity().unwrap(); @@ -1314,7 +1314,7 @@ mod tests { }); for index in 0..5 { producer.write(packet(index, 0.25)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } // Video declares an end two seconds out, holding the audio replacement back. let video = Role::new(presentation.clone(), Kind::Video); @@ -1324,7 +1324,7 @@ mod tests { const REPLACEMENT: u64 = 100; for index in 0..REPLACEMENT { producer.write(packet(5 + index, 0.5)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } producer.finish().unwrap(); task.await.unwrap(); @@ -1387,7 +1387,7 @@ mod tests { }; for index in 0..3 { video.write(picture(index * 20, index == 0)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } video.discontinuity().unwrap(); // A burst longer than the age budget evicts this replacement's only keyframe. @@ -1485,7 +1485,7 @@ mod tests { for index in 10..40 { high.write(packet(index, 0.25)).unwrap(); low.write(packet(index, 0.5)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } low.finish().unwrap(); catalog.finish().unwrap(); @@ -1521,13 +1521,13 @@ mod tests { // Half a second muted, with the timeline running on through it. let demand = audio.demand(); for _ in 0..25 { - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; assert!(demand.wanted().is_some(), "the mute unsubscribed"); } enable(true); for index in 35..60 { audio.write(packet(index, 0.5)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } settle(player, &recorder).await; @@ -1565,7 +1565,7 @@ mod tests { while index < 50 { old.write(packet(index, OLD)).unwrap(); index += 1; - moq_clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; } // The replacement joins the catalog, then the old track finishes. @@ -1576,7 +1576,7 @@ mod tests { drop(old); while index < 100 { - moq_clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; new.write(packet(index, NEW)).unwrap(); index += 1; } @@ -1661,7 +1661,7 @@ mod tests { _ => a.write(packet(index, BACK)).unwrap(), } index += 1; - moq_clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; } settle(player, &recorder).await; @@ -1721,7 +1721,7 @@ mod tests { catalog::Producer, moq_mux::container::Producer, ) { - let request = moq_clock::timeout(Duration::from_secs(5), claim.requested_broadcast()) + let request = kio::clock::timeout(Duration::from_secs(5), claim.requested_broadcast()) .await .expect("the claim is asked") .unwrap(); @@ -1736,7 +1736,7 @@ mod tests { async fn write(audio: &mut moq_mux::container::Producer, count: u64, sample: f32) { for index in 0..count { audio.write(packet(index, sample)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } } @@ -1752,7 +1752,7 @@ mod tests { /// ends on its own: give it long enough to play out what it was handed, then /// stop it. async fn settle(player: tokio::task::JoinHandle<()>, recorder: &Recorder) { - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; for event in recorder.events() { match event { Event::Failed(err) => panic!("playback failed: {err}"), @@ -1807,7 +1807,7 @@ mod tests { let player = tokio::spawn(media(&origin, Duration::from_millis(50), recorder.clone()).run()); let request = handler.requested_broadcast().await.unwrap(); request.reject(moq_net::Error::NotFound); - moq_clock::timeout(Duration::from_secs(1), player) + kio::clock::timeout(Duration::from_secs(1), player) .await .expect("a refusal held the player") .unwrap(); @@ -1833,7 +1833,7 @@ mod tests { // A restart without an epoch waits out the origin's update hold, since a // withdrawal wave's stale route looks just like one, and the player joins the // new broadcast at its live edge. - moq_clock::sleep(moq_net::origin::Config::default().update_hold).await; + kio::clock::sleep(moq_net::origin::Config::default().update_hold).await; write(&mut new, 10, NEW).await; settle(player, &recorder).await; @@ -1868,7 +1868,7 @@ mod tests { drop((old_broadcast, old_catalog, old)); // Offline for longer than any timeout the player might give up on. - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; assert!(!player.is_finished(), "the player stopped following the path"); let (_new_broadcast, _new_catalog, mut new) = publish(&origin, Default::default()); @@ -1964,7 +1964,7 @@ mod tests { exact_catalog.finish().unwrap(); drop((exact_catalog, old)); // The broadcast ends while its route stands, so the player goes idle. - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; let pool = origin.requests("").unwrap(); drop(exact); @@ -1999,7 +1999,7 @@ mod tests { let player = tokio::spawn(media(&origin, Duration::from_millis(500), recorder.clone()).run()); for index in 0..50 { old.write(packet(index, OLD)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } exact.unannounce(); @@ -2007,7 +2007,7 @@ mod tests { let (mirror, mirror_catalog, mut copy) = answer(&pool, &route).await; for index in 50..60 { copy.write(packet(index, NEW)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } settle(player, &recorder).await; @@ -2036,7 +2036,7 @@ mod tests { broadcast.announce(route.clone().with_cost(5)).unwrap(); } audio.write(packet(index, SAMPLE)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; } settle(player, &recorder).await; @@ -2058,7 +2058,7 @@ mod tests { let player = tokio::spawn(media(&origin, Duration::from_millis(50), recorder.clone()).run()); let mut audio = rendition(&broadcast, &catalog, "audio"); audio.write(packet(0, 0.25)).unwrap(); - moq_clock::sleep(PACKET_DURATION).await; + kio::clock::sleep(PACKET_DURATION).await; audio.finish().unwrap(); drop(audio); catalog.finish().unwrap(); @@ -2083,7 +2083,7 @@ mod tests { let start = Instant::now(); for index in 0..COUNT { let ready = ((index + 1) * PACKET).div_ceil(BLOCK) * BLOCK; - moq_clock::sleep_until(start + Duration::from_secs_f64(ready as f64 / SAMPLE_RATE as f64)).await; + kio::clock::sleep_until(start + Duration::from_secs_f64(ready as f64 / SAMPLE_RATE as f64)).await; audio.write(packet(index, 0.25)).unwrap(); } settle(player, &recorder).await; diff --git a/rs/moq-cli/src/play/metrics.rs b/rs/moq-cli/src/play/metrics.rs index 10c8d451d06..8b6650b3260 100644 --- a/rs/moq-cli/src/play/metrics.rs +++ b/rs/moq-cli/src/play/metrics.rs @@ -15,8 +15,8 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use anyhow::Context; +use kio::clock::Instant; use moq_audio::playback::{Observation, Observer}; -use moq_clock::Instant; use serde::Serialize; use tokio::sync::mpsc; @@ -98,7 +98,7 @@ pub(super) struct Metrics { /// What closed engines counted, added to the current one's totals. base: Totals, start: Instant, - interval: moq_clock::Interval, + interval: kio::clock::Interval, } impl Metrics { @@ -109,8 +109,8 @@ impl Metrics { ) -> anyhow::Result<(Self, mpsc::UnboundedSender)> { let file = File::create(path).with_context(|| format!("failed to create {}", path.display()))?; let (observe, observers) = mpsc::unbounded_channel(); - let mut interval = moq_clock::interval(INTERVAL); - interval.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); + let mut interval = kio::clock::interval(INTERVAL); + interval.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Delay); let metrics = Self { file: BufWriter::new(file), presentation, @@ -140,7 +140,7 @@ impl Metrics { // The audio thread closes the gap on its next buffer. One that never // comes is a device that stopped pulling, which the render clock // already shows, so the wait is bounded rather than hung on it. - if moq_clock::timeout(FINISH_WAIT, observer.finish()).await.is_err() { + if kio::clock::timeout(FINISH_WAIT, observer.finish()).await.is_err() { tracing::warn!("the speaker never closed out the measurement; the last gap may be missing"); } } diff --git a/rs/moq-cli/src/play/timeline.rs b/rs/moq-cli/src/play/timeline.rs index 1b9fcdeb53b..36a38dbed2f 100644 --- a/rs/moq-cli/src/play/timeline.rs +++ b/rs/moq-cli/src/play/timeline.rs @@ -1,7 +1,7 @@ //! Media time: the playout clock, and the audio track's own timeline. use anyhow::Context; -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; use super::playback::Kind; @@ -304,7 +304,7 @@ impl Role { /// Stop while a tail still plays until `drained`, holding a declared end until /// then. Dropping instead discards the tail with the end. pub(super) fn retire(self, drained: Option) { - let now = moq_clock::now(); + let now = kio::clock::now(); let mut presentation = self.presentation.lock().unwrap(); presentation.tails.retain(|tail| *tail > now); if presentation.ends[self.role as usize].take().is_some() @@ -325,7 +325,7 @@ impl Role { /// long as its replacement has not started playing; otherwise this one opens /// a transition of its own. pub(super) fn declare(&self) -> Transition { - let now = moq_clock::now(); + let now = kio::clock::now(); let own = self.role as usize; let mut presentation = self.presentation.lock().unwrap(); presentation.prune(now); @@ -402,7 +402,7 @@ impl Role { pending.members[own] = false; pending.plans[own] = None; } - presentation.prune(moq_clock::now()); + presentation.prune(kio::clock::now()); drop(presentation); self.timeline.notify_waiters(); } @@ -413,7 +413,7 @@ impl Role { if let Some(pending) = presentation.transition(transition) { pending.resumed[self.role as usize] = true; } - presentation.prune(moq_clock::now()); + presentation.prune(kio::clock::now()); drop(presentation); self.timeline.notify_waiters(); } @@ -432,7 +432,7 @@ impl Role { let changed = self.timeline.notified(); let mut changed = std::pin::pin!(changed); changed.as_mut().enable(); - let now = moq_clock::now(); + let now = kio::clock::now(); let end = { let mut presentation = self.presentation.lock().unwrap(); // The peer already resumed this transition after draining every end @@ -451,7 +451,7 @@ impl Role { }; if let Some(end) = end.filter(|end| *end > now) { tokio::select! { - _ = moq_clock::sleep_until(end) => {}, + _ = kio::clock::sleep_until(end) => {}, _ = changed => {}, } continue; @@ -505,7 +505,7 @@ impl Drop for Role { pending.plans[own] = None; } presentation.declared[own] = Transition::default(); - presentation.prune(moq_clock::now()); + presentation.prune(kio::clock::now()); } self.timeline.notify_waiters(); } @@ -681,7 +681,7 @@ mod tests { #[tokio::test] async fn one_ended_role_maps_to_the_continuous_peers_clock() { tokio::time::pause(); - let start = moq_clock::now(); + let start = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); let audio = Role::new(presentation.clone(), Kind::Audio); let video = Role::new(presentation.clone(), Kind::Video); @@ -699,7 +699,7 @@ mod tests { #[tokio::test] async fn a_late_paired_replacement_keeps_its_media_offset() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -724,7 +724,7 @@ mod tests { #[tokio::test] async fn a_late_replacement_pairs_with_its_own_transition() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -752,7 +752,7 @@ mod tests { #[tokio::test] async fn a_peer_two_restarts_ahead_pairs_with_the_first() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -781,7 +781,7 @@ mod tests { #[tokio::test] async fn an_abandoned_replacement_leaves_the_next_transition_alone() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -800,7 +800,7 @@ mod tests { audio.apply(transition, audio.resume(transition, ms(0), Some(DELAY)).await.unwrap()); video.apply(next, video.resume(next, ms(5_000), None).await.unwrap()); // The later replacement maps onto the running clock, not the audio restart's. - let resumed = moq_clock::now() + DELAY; + let resumed = kio::clock::now() + DELAY; assert_eq!( presentation.lock().unwrap().due(video.map(ms(5_000)).unwrap()), Some(resumed) @@ -810,7 +810,7 @@ mod tests { #[tokio::test] async fn an_abandoned_peer_plan_is_not_paired() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -824,7 +824,7 @@ mod tests { video.plan(transition, ms(40), None); tokio::time::advance(DELAY + Duration::from_millis(20)).await; video.apply(transition, video.resume(transition, ms(40), None).await.unwrap()); - let resumed = moq_clock::now() + DELAY; + let resumed = kio::clock::now() + DELAY; assert_eq!( presentation.lock().unwrap().due(video.map(ms(40)).unwrap()), Some(resumed) @@ -834,7 +834,7 @@ mod tests { #[tokio::test] async fn a_resumed_transition_ignores_the_peers_later_end() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -852,14 +852,14 @@ mod tests { video.declare(); video.end(ms(60_000)).unwrap(); audio.plan(transition, ms(0), Some(DELAY)); - let resumed = moq_clock::timeout(Duration::from_millis(1), audio.resume(transition, ms(0), Some(DELAY))).await; + let resumed = kio::clock::timeout(Duration::from_millis(1), audio.resume(transition, ms(0), Some(DELAY))).await; assert!(resumed.is_ok(), "audio waited for video's next end"); } #[tokio::test] async fn a_cancelled_role_releases_its_declared_end() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -871,7 +871,7 @@ mod tests { let transition = video.declare(); video.end(ms(10_000)).unwrap(); video.plan(transition, ms(0), None); - let resume = moq_clock::timeout( + let resume = kio::clock::timeout( DELAY + Duration::from_millis(150), video.resume(transition, ms(0), None), ) @@ -882,7 +882,7 @@ mod tests { #[tokio::test] async fn a_closed_role_still_holds_its_declared_end() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -894,7 +894,7 @@ mod tests { let transition = video.declare(); video.end(ms(10_000)).unwrap(); video.plan(transition, ms(0), None); - let resume = moq_clock::timeout( + let resume = kio::clock::timeout( DELAY + Duration::from_millis(150), video.resume(transition, ms(0), None), ) @@ -905,7 +905,7 @@ mod tests { #[tokio::test] async fn a_retired_end_ignores_a_later_re_pin() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -921,14 +921,14 @@ mod tests { } let transition = video.declare(); video.plan(transition, ms(0), None); - let resume = moq_clock::timeout(Duration::from_millis(400), video.resume(transition, ms(0), None)).await; + let resume = kio::clock::timeout(Duration::from_millis(400), video.resume(transition, ms(0), None)).await; assert!(resume.is_ok(), "video waited past the drained tail"); } #[tokio::test] async fn a_cancelled_successor_keeps_a_retired_tail() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); @@ -942,14 +942,14 @@ mod tests { drop(successor); let transition = video.declare(); video.plan(transition, ms(0), None); - let resume = moq_clock::timeout(Duration::from_millis(250), video.resume(transition, ms(0), None)).await; + let resume = kio::clock::timeout(Duration::from_millis(250), video.resume(transition, ms(0), None)).await; assert!(resume.is_err(), "video resumed over the retired audio tail"); } #[tokio::test] async fn paired_plans_keep_media_offsets_and_follow_the_speakers_delay() { tokio::time::pause(); - let now = moq_clock::now(); + let now = kio::clock::now(); let presentation = std::sync::Arc::new(std::sync::Mutex::new(Presentation::new(DELAY))); presentation.lock().unwrap().audio(Duration::from_secs(10), DELAY, now); let audio = Role::new(presentation.clone(), Kind::Audio); diff --git a/rs/moq-cli/src/play/video.rs b/rs/moq-cli/src/play/video.rs index 5b0f039b860..2b8714dd449 100644 --- a/rs/moq-cli/src/play/video.rs +++ b/rs/moq-cli/src/play/video.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeSet, VecDeque}; use std::sync::{Arc, Mutex}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_mux::container::{Frame, Read}; use moq_video::decode::Read as Decoded; use moq_video::decode::{Lane, Next, Selector}; @@ -413,7 +413,7 @@ impl Video { let frames = match step { Step::Wait(Some(at)) => { tokio::select! { - _ = moq_clock::sleep_until(at) => {}, + _ = kio::clock::sleep_until(at) => {}, _ = self.changed.notified() => {}, } continue; @@ -616,7 +616,7 @@ impl Video { match at { Some(at) => tokio::select! { _ = woken => {}, - _ = moq_clock::sleep_until(at) => {}, + _ = kio::clock::sleep_until(at) => {}, }, None => woken.await, } @@ -700,7 +700,7 @@ mod tests { impl Decoder for Buffered { async fn decode(&mut self, frame: Frame) -> anyhow::Result> { if !self.cost.is_zero() { - moq_clock::sleep(self.cost).await; + kio::clock::sleep(self.cost).await; } self.decoded.lock().unwrap().push((frame.timestamp, Instant::now())); let size = self.size as usize; diff --git a/rs/moq-cli/src/play/window.rs b/rs/moq-cli/src/play/window.rs index 81a533b0857..36d36f10893 100644 --- a/rs/moq-cli/src/play/window.rs +++ b/rs/moq-cli/src/play/window.rs @@ -5,7 +5,7 @@ use std::collections::VecDeque; use std::sync::{Arc, Mutex}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use anyhow::Context; use hang::moq_net; @@ -334,7 +334,7 @@ impl ApplicationHandler for App { return; } - let now = moq_clock::now(); + let now = kio::clock::now(); match self.next_redraw { Some(deadline) if deadline <= now => { self.next_redraw = None; diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 8d2982a69c8..b2040055271 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -772,7 +772,7 @@ struct Reader { // diagnosed by the rate at which these climb, and stdin may never end, so // they have to surface as they accumulate rather than at exit. log: ts::stats::Log, - sampled: moq_clock::Instant, + sampled: kio::clock::Instant, } /// Decode `input` into the broadcast until EOF. @@ -815,7 +815,7 @@ async fn decode( // whatever is available without waiting to fill it. buffer: bytes::BytesMut::with_capacity(64 * 1024), log: ts::stats::Log::default(), - sampled: moq_clock::now(), + sampled: kio::clock::now(), }; let result = loop { @@ -862,7 +862,7 @@ impl Instance { } if reader.sampled.elapsed() >= ts::stats::Log::INTERVAL { - reader.sampled = moq_clock::now(); + reader.sampled = kio::clock::now(); if let Some(stats) = decoder.stats() { if let Some(sections) = §ions { sections.set(|report| report.mpegts = Some(stats.clone())); @@ -1295,7 +1295,7 @@ pub(crate) mod tests { // Past the export's release delay and the send-ahead window behind it, so the first // frame goes out before it ends. let wait = RECORDING_MAX_AGE * 3 + Duration::from_secs(1); - while let Ok(res) = moq_clock::timeout(wait, exporter.next()).await { + while let Ok(res) = kio::clock::timeout(wait, exporter.next()).await { match res.expect("exporter error") { Some(frame) => out.extend_from_slice(&frame.payload), None => break, @@ -1673,12 +1673,12 @@ pub(crate) mod tests { // the lead holds; the jump is in the copy after it. const WAIT: Duration = Duration::from_secs(10); decoder.decode_chunk(&lead).unwrap(); - let consumer = moq_clock::timeout(WAIT, remote.consume().follow("pt.hang", None).unwrap().available()) + let consumer = kio::clock::timeout(WAIT, remote.consume().follow("pt.hang", None).unwrap().available()) .await .unwrap() .unwrap(); let mut catalogs = hang::catalog::Catalog::<()>::subscribe(&consumer).await.unwrap(); - let catalog = moq_clock::timeout(WAIT, catalogs.next()) + let catalog = kio::clock::timeout(WAIT, catalogs.next()) .await .unwrap() .unwrap() @@ -1690,13 +1690,13 @@ pub(crate) mod tests { // SUBSCRIBE arrives, not when it is sent. let start = async |subscription: moq_net::track::Subscription| { let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap(); - let first = moq_clock::timeout(WAIT, track.recv_group()).await.unwrap().unwrap(); + let first = kio::clock::timeout(WAIT, track.recv_group()).await.unwrap().unwrap(); (track, first) }; // Each group's sequence and frames, read until the track ends. A read cut off as // stale leaves `None` for that group's frames, and a marker leaves none. let read = |(mut track, first): (moq_net::track::Subscriber, Option)| { - tokio::spawn(moq_clock::timeout(WAIT, async move { + tokio::spawn(kio::clock::timeout(WAIT, async move { let mut groups = Vec::new(); let mut next = first; while let Some(mut group) = next { @@ -1811,9 +1811,9 @@ pub(crate) mod tests { let Source::Stream { decoder, .. } = &mut publish.source else { panic!("expected a stream source"); }; - let before = moq_clock::wall(); + let before = kio::clock::wall(); decoder.decode_chunk(BBB).unwrap(); - let after = moq_clock::wall(); + let after = kio::clock::wall(); decoder.finish().unwrap(); let catalog = hang::catalog::Catalog::<()>::subscribe(&consumer) @@ -1963,7 +1963,7 @@ pub(crate) mod tests { let Source::Stream { decoder, catalog } = publish.source else { panic!("expected a stream source"); }; - let start = moq_clock::now(); + let start = kio::clock::now(); decode(decoder, catalog, input, Publication::default()).await.unwrap(); let elapsed = start.elapsed(); let bytes = INPUT.len() * copies; @@ -1998,7 +1998,7 @@ pub(crate) mod tests { let mut last = None; loop { - let next = moq_clock::timeout(Duration::from_secs(1), catalogs.next()) + let next = kio::clock::timeout(Duration::from_secs(1), catalogs.next()) .await .expect("the catalog track ends"); match next.expect("the catalog ends cleanly") { @@ -2031,7 +2031,7 @@ pub(crate) mod tests { let Source::Stream { decoder, catalog } = publish.source else { panic!("expected a stream source"); }; - let started = moq_clock::Instant::now(); + let started = kio::clock::Instant::now(); let publication = Publication { broadcast: publish.broadcast.clone(), linger: LINGER, @@ -2106,7 +2106,7 @@ pub(crate) mod tests { tokio::select! { res = &mut import => panic!("the import returned before its input ended: {res:?}"), - event = moq_clock::timeout(Duration::from_secs(5), announced.next()) => { + event = kio::clock::timeout(Duration::from_secs(5), announced.next()) => { assert!(event.is_err(), "announced before any input: {event:?}"); } } @@ -2114,7 +2114,7 @@ pub(crate) mod tests { tokio::io::AsyncWriteExt::write_all(&mut stdin, input).await.unwrap(); let resolved = tokio::select! { res = &mut import => panic!("the import returned before its input ended: {res:?}"), - _ = moq_clock::sleep(Duration::from_secs(30)) => panic!("never announced"), + _ = kio::clock::sleep(Duration::from_secs(30)) => panic!("never announced"), resolved = async { let event = announced.next().await.expect("origin closed"); assert!(matches!(event, moq_net::announce::Event::Start(_)), "{event:?}"); @@ -2234,7 +2234,7 @@ pub(crate) mod tests { let mut next = async |import: &mut std::pin::Pin<&mut _>| { tokio::select! { res = import => panic!("the import returned before its input ended: {res:?}"), - _ = moq_clock::sleep(Duration::from_secs(30)) => panic!("never announced"), + _ = kio::clock::sleep(Duration::from_secs(30)) => panic!("never announced"), epoch = async { loop { use moq_net::announce::Event; @@ -2315,7 +2315,7 @@ pub(crate) mod tests { }; let err = decode(decoder, catalog, &input[..], publication).await.unwrap_err(); assert!(err.to_string().contains("declared"), "{err:#}"); - let event = moq_clock::timeout(Duration::from_secs(1), announced.next()).await; + let event = kio::clock::timeout(Duration::from_secs(1), announced.next()).await; assert!(event.is_err(), "announced an empty broadcast: {event:?}"); } } @@ -2437,7 +2437,7 @@ pub(crate) mod tests { async fn read_frame(consumer: &moq_net::broadcast::Consumer, name: &str) -> Vec { let track = consumer.track(name).unwrap().subscribe(None).await.unwrap(); let mut reader = Consumer::new(track, Container::Legacy(moq_mux::container::Kind::Data)); - let frame = moq_clock::timeout(Duration::from_secs(1), next_frame(&mut reader)) + let frame = kio::clock::timeout(Duration::from_secs(1), next_frame(&mut reader)) .await .expect("verbatim read timed out"); frame.payload.to_vec() diff --git a/rs/moq-cli/src/report.rs b/rs/moq-cli/src/report.rs index ad2b10f86be..e74e4e55549 100644 --- a/rs/moq-cli/src/report.rs +++ b/rs/moq-cli/src/report.rs @@ -198,7 +198,7 @@ impl Stats { /// Write a snapshot every interval, for as long as the import runs beside it. pub async fn run(&mut self) -> Infallible { - let mut interval = moq_clock::interval(INTERVAL); + let mut interval = kio::clock::interval(INTERVAL); loop { interval.tick().await; self.write(); @@ -298,7 +298,7 @@ impl Echo { None } }; - let mut interval = moq_clock::interval(INTERVAL); + let mut interval = kio::clock::interval(INTERVAL); loop { tokio::select! { update = next(&mut catalog) => match update { @@ -539,7 +539,7 @@ impl Readers { }; let id = reader.id(); self.drains.spawn(async move { - moq_clock::sleep(DRAIN).await; + kio::clock::sleep(DRAIN).await; (path, id) }); } @@ -645,9 +645,9 @@ mod tests { assert!(line.contains(r#""n":1"#), "{line}"); broadcast.unannounce(); - moq_clock::sleep(DRAIN * 2).await; + kio::clock::sleep(DRAIN * 2).await; feedback.update(&serde_json::json!({ "n": 2 })).unwrap(); - let late = moq_clock::timeout(Duration::from_secs(1), lines.next_line()).await; + let late = kio::clock::timeout(Duration::from_secs(1), lines.next_line()).await; assert!(late.is_err(), "a drained reader wrote {late:?}"); } @@ -685,7 +685,7 @@ mod tests { tokio::spawn(write_echo(origin.consume(), ".viewers".to_string(), out)); feedback.update(&serde_json::json!({ "n": 1 })).unwrap(); - let line = moq_clock::timeout(Duration::from_secs(5), lines.next_line()).await; + let line = kio::clock::timeout(Duration::from_secs(5), lines.next_line()).await; let line = line.expect("no feedback read").unwrap().unwrap(); assert!(line.contains(r#""n":1"#), "{line}"); } diff --git a/rs/moq-cli/src/report/echo_test.rs b/rs/moq-cli/src/report/echo_test.rs index 5dabce78bc7..07dc8e5e6ed 100644 --- a/rs/moq-cli/src/report/echo_test.rs +++ b/rs/moq-cli/src/report/echo_test.rs @@ -96,7 +96,7 @@ async fn export_echo_reports_where_the_import_solicits() { let final_report: hang::echo::Snapshot = serde_json::from_value(final_report).unwrap(); // It may have arrived while the export was still running. while feedback.last().is_none_or(|line| line.feedback != final_report) { - let line = moq_clock::timeout(Duration::from_secs(30), lines.next_line()) + let line = kio::clock::timeout(Duration::from_secs(30), lines.next_line()) .await .expect("the final feedback never arrived") .unwrap() diff --git a/rs/moq-cli/src/rtsp.rs b/rs/moq-cli/src/rtsp.rs index 2565277ca2f..8349d0ac090 100644 --- a/rs/moq-cli/src/rtsp.rs +++ b/rs/moq-cli/src/rtsp.rs @@ -52,7 +52,7 @@ pub async fn connect_import(target: ImportTarget, url: Url) -> anyhow::Result<() } tracing::info!(%url, ?backoff, "RTSP reconnecting"); - moq_clock::sleep(backoff).await; + kio::clock::sleep(backoff).await; backoff = (backoff * 2).min(BACKOFF_MAX); } } diff --git a/rs/moq-cli/src/subscribe.rs b/rs/moq-cli/src/subscribe.rs index 6d9324c2f72..0b0355ed213 100644 --- a/rs/moq-cli/src/subscribe.rs +++ b/rs/moq-cli/src/subscribe.rs @@ -431,7 +431,7 @@ impl Subscribe { // Reports a track that stops reaching the output while the rest keeps flowing, // the way `publish` reports one that stops arriving. let mut log = moq_mux::container::ts::stats::Log::default(); - let mut sampled = moq_clock::now(); + let mut sampled = kio::clock::now(); // The export's drop, gap and out-of-tolerance counts, as last logged. let mut reported = (0, 0, 0, 0); let sections = self.sections; @@ -453,7 +453,7 @@ impl Subscribe { stdout.flush().await?; if sampled.elapsed() >= moq_mux::container::ts::stats::Log::INTERVAL { - sampled = moq_clock::now(); + sampled = kio::clock::now(); let stats = ts.export().stats(); report(&stats); let release = &stats.release; @@ -488,14 +488,14 @@ impl Subscribe { sections.set(|report| report.release = Some(stats.clone())); } }; - let mut sampled = moq_clock::now(); + let mut sampled = kio::clock::now(); let mut reported = (0, 0, 0, 0); while let Some(object) = release.next().await? { stdout.write_all(&object.payload).await?; stdout.flush().await?; if sampled.elapsed() >= moq_mux::container::ts::stats::Log::INTERVAL { - sampled = moq_clock::now(); + sampled = kio::clock::now(); let stats = release.stats(); report(&stats); let counts = (stats.dropped, stats.trimmed, stats.gaps, stats.out_of_tolerance); diff --git a/rs/moq-cli/src/transcode.rs b/rs/moq-cli/src/transcode.rs index 44209bcff7a..3bc8e4b8163 100644 --- a/rs/moq-cli/src/transcode.rs +++ b/rs/moq-cli/src/transcode.rs @@ -290,7 +290,7 @@ mod tests { let first = next(&mut derivatives).await; catalog.finish().unwrap(); - moq_clock::timeout(std::time::Duration::from_secs(1), first.closed()) + kio::clock::timeout(std::time::Duration::from_secs(1), first.closed()) .await .expect("the ladder outlived its source's end"); assert!(!task.is_finished(), "a clean end stopped following"); @@ -313,7 +313,7 @@ mod tests { } } }; - moq_clock::timeout(std::time::Duration::from_secs(1), start) + kio::clock::timeout(std::time::Duration::from_secs(1), start) .await .expect("no derivative instance was announced") } diff --git a/rs/moq-cli/tests/integration/auth_serve.rs b/rs/moq-cli/tests/integration/auth_serve.rs index a2f607aed8d..3359dba336b 100644 --- a/rs/moq-cli/tests/integration/auth_serve.rs +++ b/rs/moq-cli/tests/integration/auth_serve.rs @@ -32,7 +32,7 @@ async fn stops_on(signal: libc::c_int) { // Signal only once the handler can be installed: before that, the default action // would kill the process whether or not the fix is in. let mut lines = BufReader::new(child.stderr.take().expect("stderr")).lines(); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while let Some(line) = lines.next_line().await.expect("read stderr") { if line.contains("auth server listening") { return; @@ -47,7 +47,7 @@ async fn stops_on(signal: libc::c_int) { // SAFETY: `kill` has no memory-safety preconditions; the pid is our live child. assert_eq!(unsafe { libc::kill(pid, signal) }, 0, "failed to signal moq"); - let status = moq_clock::timeout(TIMEOUT, child.wait()) + let status = kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("moq ignored the signal") .expect("wait for moq"); diff --git a/rs/moq-cli/tests/integration/epochs.rs b/rs/moq-cli/tests/integration/epochs.rs index 4eee104ce28..8094e67b5e6 100644 --- a/rs/moq-cli/tests/integration/epochs.rs +++ b/rs/moq-cli/tests/integration/epochs.rs @@ -2,7 +2,7 @@ use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use hang::moq_net::{self, Epoch, Timestamp, announce, origin, track}; use moq_mux::catalog::Stream; @@ -113,7 +113,7 @@ fn publish(origin: &origin::Producer, epoch: &Epoch, tag: &str) -> Published { /// Finish a route change within [`routing`] of `started`. async fn within(started: Instant, change: impl Future) -> T { let deadline = started + routing(); - moq_clock::timeout_at(deadline, change) + kio::clock::timeout_at(deadline, change) .await .unwrap_or_else(|_| panic!("route change took longer than {:?}", routing())) } diff --git a/rs/moq-cli/tests/integration/export.rs b/rs/moq-cli/tests/integration/export.rs index 82c1eee8f94..ec10665bd69 100644 --- a/rs/moq-cli/tests/integration/export.rs +++ b/rs/moq-cli/tests/integration/export.rs @@ -13,7 +13,7 @@ use std::process::Stdio; use std::sync::{Arc, Mutex}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use hang::moq_net; use moq_mux::container::ts; @@ -48,9 +48,9 @@ struct Export { impl Export { /// Wait for output, retaining the child verdict and stderr on every timeout. async fn output_past(&mut self, len: usize) { - let arrived = moq_clock::timeout(TIMEOUT, async { + let arrived = kio::clock::timeout(TIMEOUT, async { while self.output.lock().unwrap().len() <= len { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } }) .await; @@ -64,7 +64,7 @@ impl Export { /// Wait for the verdict and drain both pipes before inspecting their contents. async fn wait(mut self) -> (std::process::ExitStatus, String) { - let status = match moq_clock::timeout(TIMEOUT, self.child.wait()).await { + let status = match kio::clock::timeout(TIMEOUT, self.child.wait()).await { Ok(status) => status.expect("wait for export"), Err(err) => { let _ = self.child.kill().await; @@ -272,7 +272,7 @@ fn feed(mut stdin: ChildStdin, format: Format) -> JoinHandle { tokio::spawn(async move { for chunk in format.clip.chunks(format.chunk) { stdin.write_all(chunk).await.expect("write stdin"); - moq_clock::sleep(Duration::from_millis(150)).await; + kio::clock::sleep(Duration::from_millis(150)).await; } stdin }) @@ -293,7 +293,7 @@ async fn interrupt(mut child: Child, stdin: ChildStdin) { } async fn wait(child: &mut Child) -> std::process::ExitStatus { - moq_clock::timeout(TIMEOUT, child.wait()) + kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("moq never exited") .expect("wait for moq") @@ -425,13 +425,13 @@ async fn interrupted(export: &mut Export, publisher: (Child, JoinHandle (Child, JoinHandle (tokio::sync::mpsc::UnboundedSender, JoinHand let task = tokio::spawn(async move { let source = redundant_source(); let mut inputs: Vec = Vec::new(); - let mut pace = moq_clock::interval(Duration::from_micros(30_080)); + let mut pace = kio::clock::interval(Duration::from_micros(30_080)); for chunk in source.chunks(8 * 188) { pace.tick().await; while let Ok(input) = added.try_recv() { @@ -947,7 +947,7 @@ async fn redundant_failover(bufferbloat: bool) { let mut second = redundant_import(&relay, &feed, &[]); for version in 1..=3 { for export in &mut exports { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { if export.child.try_wait().unwrap().is_some() { let errors = (&mut export.stderr).await.expect("collect exporter stderr"); @@ -959,7 +959,7 @@ async fn redundant_failover(bufferbloat: bool) { { break; } - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } }) .await @@ -1056,7 +1056,7 @@ async fn redundant_failover(bufferbloat: bool) { /// The epoch of the next route announced for the path. async fn next_epoch(announced: &mut moq_net::announce::Consumer) -> moq_net::Epoch { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { match announced.next().await.expect("the relay stays up") { moq_net::announce::Event::Start(announce) diff --git a/rs/moq-cli/tests/integration/import.rs b/rs/moq-cli/tests/integration/import.rs index 70e7e7a4e59..11333ef629d 100644 --- a/rs/moq-cli/tests/integration/import.rs +++ b/rs/moq-cli/tests/integration/import.rs @@ -21,7 +21,7 @@ async fn running(child: &mut Child, what: &str, step: impl Future tokio::select! { out = step => out, status = child.wait() => panic!("moq exited with {} before {what}", status.expect("wait for moq")), - _ = moq_clock::sleep(TIMEOUT) => panic!("{what} timed out"), + _ = kio::clock::sleep(TIMEOUT) => panic!("{what} timed out"), } } @@ -107,14 +107,14 @@ async fn import_delivers_the_catalog_finish_at_eof() { .expect("a catalog"); drop(stdin); - let status = moq_clock::timeout(TIMEOUT, child.wait()) + let status = kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("moq never exited") .expect("wait for moq"); assert!(status.success(), "moq exited with {status}"); loop { - match moq_clock::timeout(TIMEOUT, catalogs.next()) + match kio::clock::timeout(TIMEOUT, catalogs.next()) .await .expect("the catalog never ended") { @@ -178,7 +178,7 @@ async fn a_short_import_drains_its_media_to_a_waiting_subscriber() { .await .expect("subscribe to the catalog"); - let catalog = moq_clock::timeout(TIMEOUT, catalogs.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalogs.next()) .await .expect("no catalog") .expect("catalog read") @@ -190,12 +190,12 @@ async fn a_short_import_drains_its_media_to_a_waiting_subscriber() { .next() .expect("a video rendition") .clone(); - let mut track = moq_clock::timeout(TIMEOUT, broadcast.track(&name).expect("track").subscribe(None)) + let mut track = kio::clock::timeout(TIMEOUT, broadcast.track(&name).expect("track").subscribe(None)) .await .expect("the video subscription timed out") .expect("subscribe to the video"); let mut frames = 0; - while let Some(mut group) = moq_clock::timeout(TIMEOUT, track.recv_group()) + while let Some(mut group) = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("the video never ended") .expect("video group") @@ -206,7 +206,7 @@ async fn a_short_import_drains_its_media_to_a_waiting_subscriber() { } assert!(frames > 0, "the subscriber received no video"); - let status = moq_clock::timeout(TIMEOUT, child.wait()) + let status = kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("moq never exited") .expect("wait for moq"); diff --git a/rs/moq-cli/tests/integration/listen.rs b/rs/moq-cli/tests/integration/listen.rs index 6a871936bd2..7fdcc2145a2 100644 --- a/rs/moq-cli/tests/integration/listen.rs +++ b/rs/moq-cli/tests/integration/listen.rs @@ -47,7 +47,7 @@ async fn listen(stage: &str, flags: &[&str]) -> Listening { .unwrap(); let stdin = child.stdin.take().unwrap(); let mut stderr = BufReader::new(child.stderr.take().unwrap()); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let mut output = String::new(); loop { let mut line = String::new(); @@ -86,7 +86,7 @@ impl Listening { } async fn stopped(mut self) { - let status = moq_clock::timeout(TIMEOUT, self.child.wait()) + let status = kio::clock::timeout(TIMEOUT, self.child.wait()) .await .expect("listening CLI did not stop after its sessions left") .unwrap(); @@ -108,7 +108,7 @@ async fn connects(listening: &Listening, stage: &str) -> (moq_tokio::Connection, } else { client.with_publisher(origin) }; - let connection = moq_clock::timeout(TIMEOUT, client.connect(listening.url.clone()).established()) + let connection = kio::clock::timeout(TIMEOUT, client.connect(listening.url.clone()).established()) .await .unwrap() .unwrap(); @@ -120,7 +120,7 @@ async fn drains(stage: &str) { let (connection, _origin) = connects(&listening, stage).await; let draining = connection.draining().unwrap(); listening.signal(); - let goaway = moq_clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) + let goaway = kio::clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) .await .expect("no GOAWAY after SIGTERM") .expect("CLI closed the session without GOAWAY"); @@ -164,7 +164,7 @@ async fn an_export_stage_ending_during_drain_waits_for_every_session() { while demand.wanted_changed().await?.is_none() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(TIMEOUT, wanted).await.unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, wanted).await.unwrap().unwrap(); let mut legacy = moq_tokio::connect::Config::default(); legacy.version = vec!["moq-lite-03".parse().unwrap()]; let legacy = legacy @@ -176,14 +176,14 @@ async fn an_export_stage_ending_during_drain_waits_for_every_session() { .await .unwrap(); let draining = publisher.draining().unwrap(); - let signalled = moq_clock::now(); + let signalled = kio::clock::now(); listening.signal(); - moq_clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) + kio::clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) .await .unwrap() .unwrap(); publisher.closed().await.unwrap(); - moq_clock::timeout(TIMEOUT, legacy.closed()) + kio::clock::timeout(TIMEOUT, legacy.closed()) .await .unwrap() .expect_err("legacy peer was force-closed"); diff --git a/rs/moq-cli/tests/integration/report.rs b/rs/moq-cli/tests/integration/report.rs index e0f8e8603da..b625dd4cc51 100644 --- a/rs/moq-cli/tests/integration/report.rs +++ b/rs/moq-cli/tests/integration/report.rs @@ -22,8 +22,8 @@ const HALF: usize = CLIP.len() / 2; /// Feed `clip` to `write` at about real time, never catching up in a burst. async fn feed(clip: &[u8], mut write: impl AsyncFnMut(&[u8])) { - let mut pace = moq_clock::interval(PACE); - pace.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); + let mut pace = kio::clock::interval(PACE); + pace.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Delay); for chunk in clip.chunks(CHUNK) { pace.tick().await; write(chunk).await; @@ -75,7 +75,7 @@ fn sink(relay: &Relay, broadcast: &str, sink: &str) -> (Child, Lines(lines: &mut Lines>) -> Option { - let line = moq_clock::timeout(TIMEOUT, lines.next_line()) + let line = kio::clock::timeout(TIMEOUT, lines.next_line()) .await .expect("the sink printed nothing") .expect("read the sink"); @@ -83,7 +83,7 @@ async fn next(lines: &mut Lines std::process::ExitStatus { - moq_clock::timeout(TIMEOUT, child.wait()) + kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("moq never exited") .expect("wait for moq") @@ -355,7 +355,7 @@ async fn a_late_sink_reads_the_final_report() { stdin.write_all(CLIP).await.expect("write stdin"); drop(stdin); let mut stderr = BufReader::new(import.stderr.take().expect("stderr")).lines(); - let ended = moq_clock::timeout(TIMEOUT, async { + let ended = kio::clock::timeout(TIMEOUT, async { while let Some(line) = stderr.next_line().await.expect("read the import's stderr") { if line.contains("input ended") { return; diff --git a/rs/moq-cli/tests/integration/rtsp.rs b/rs/moq-cli/tests/integration/rtsp.rs index 9e6daf598f0..3cea3258acb 100644 --- a/rs/moq-cli/tests/integration/rtsp.rs +++ b/rs/moq-cli/tests/integration/rtsp.rs @@ -18,7 +18,7 @@ async fn running(child: &mut Child, what: &str, step: impl Future tokio::select! { out = step => out, status = child.wait() => panic!("moq exited with {} before {what}", status.expect("wait for moq")), - _ = moq_clock::sleep(TIMEOUT) => panic!("{what} timed out"), + _ = kio::clock::sleep(TIMEOUT) => panic!("{what} timed out"), } } diff --git a/rs/moq-clock/CHANGELOG.md b/rs/moq-clock/CHANGELOG.md deleted file mode 100644 index c08249dd458..00000000000 --- a/rs/moq-clock/CHANGELOG.md +++ /dev/null @@ -1,14 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -## [0.11.0] - -### Added - -- First release of the clock library: logical instants, wall time, deadlines, ambient timers, and a deterministic simulator. It replaces the "CLOCK over QUIC" demo binary, last published as 0.10.21 and now the moq-tokio `clock` example. diff --git a/rs/moq-clock/Cargo.toml b/rs/moq-clock/Cargo.toml deleted file mode 100644 index dd63e5a305f..00000000000 --- a/rs/moq-clock/Cargo.toml +++ /dev/null @@ -1,53 +0,0 @@ -[package] -name = "moq-clock" -description = "One clock for Media over QUIC: logical instants, wall time, deadlines, and a deterministic simulator." -authors = ["Luke Curley"] -repository = "https://github.com/moq-dev/moq" -license = "MIT OR Apache-2.0" - -# The crates.io name previously held the "CLOCK over QUIC" demo binary (last 0.10.21). -version = "0.11.0" -edition = "2024" -rust-version.workspace = true - -keywords = ["moq", "time", "clock", "timer", "simulation"] -categories = ["asynchronous", "date-and-time", "development-tools::testing"] - -[package.metadata.docs.rs] -features = ["manual", "sim", "serde"] - -# The self dev-dependency below only enables a feature; no code names it. -[package.metadata.cargo-shear] -ignored = ["moq-clock"] - -[features] -default = ["runtime"] -# Numeric Unix-second JSON adapters for public wall times. -serde = ["dep:serde", "dep:serde_with"] -# The deterministic single-threaded executor and `#[moq_clock::test]`. Meant for -# dev-dependencies, so production builds never compile it. -sim = ["dep:futures", "dep:moq-clock-macros", "kio/_sim"] -runtime = ["dep:tokio"] -# `Manual::install`: a clock that only a test moves, as one tokio runtime's ambient -# clock. Meant for test builds, so production builds never compile it. -manual = ["runtime"] - -[dependencies] -futures = { workspace = true, optional = true } -kio = { workspace = true } -moq-clock-macros = { workspace = true, optional = true } -serde = { workspace = true, optional = true } -serde_with = { workspace = true, optional = true } -# The host timers, and the runtime handle that keeps a paused runtime's clock on its own origin. -tokio = { workspace = true, features = ["rt", "time"], optional = true } - -[dev-dependencies] -# Enable the simulator and the installed manual clock so their tests run in the merge -# gate. Without default features, so `--no-default-features` still tests the build -# without the runtime. -moq-clock = { path = ".", default-features = false, features = ["manual", "sim", "serde"] } -serde_json = { workspace = true } -tokio = { workspace = true, features = ["rt", "rt-multi-thread", "test-util", "time"] } - -[lints] -workspace = true diff --git a/rs/moq-clock/MIGRATE.md b/rs/moq-clock/MIGRATE.md deleted file mode 100644 index bd3b497f610..00000000000 --- a/rs/moq-clock/MIGRATE.md +++ /dev/null @@ -1,15 +0,0 @@ -# Migrating moq-clock - -How to update your code for each breaking change, newest first. - -## Unreleased - -### `anchor()` is `origin()` (#6510) - -Rename `moq_clock::anchor()` to `moq_clock::origin()`, matching `@moq/clock`; it still returns the fixed `(Instant, Wall)` pair. - -### moq-clock is a time library (#5465) - -moq-clock 0.10 was the "CLOCK over QUIC" example binary. -0.11 is a library: logical instants, wall time, deadlines, and a deterministic simulator. -The clock example lives on as `cargo run -p moq-tokio --example clock`, which takes `--connect` instead of `--url`. diff --git a/rs/moq-clock/README.md b/rs/moq-clock/README.md deleted file mode 100644 index a8ae8175d04..00000000000 --- a/rs/moq-clock/README.md +++ /dev/null @@ -1,28 +0,0 @@ -[![Documentation](https://docs.rs/moq-clock/badge.svg)](https://docs.rs/moq-clock/) -[![Crates.io](https://img.shields.io/crates/v/moq-clock.svg)](https://crates.io/crates/moq-clock) -[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/moq-dev/moq/blob/main/LICENSE-MIT) - -# moq-clock - -One clock for [Media over QUIC](https://moq.dev): logical instants, wall time, -deadlines, and a deterministic simulator for tests. - -```bash -cargo add moq-clock -cargo add --dev moq-clock --features sim -``` - -```rust -#[moq_clock::test] -async fn retries_after_a_second() { - let start = moq_clock::now(); // Instant::ZERO - moq_clock::sleep(std::time::Duration::from_secs(1)).await; // returns at once - assert_eq!(moq_clock::now() - start, std::time::Duration::from_secs(1)); -} -``` - -Versions up to 0.10 were the "CLOCK over QUIC" demo binary, now the -[clock example](https://github.com/moq-dev/moq/blob/main/rs/moq-tokio/examples/clock.rs). - -See [docs.rs/moq-clock](https://docs.rs/moq-clock) for the API and -[doc.moq.dev](https://doc.moq.dev/lib/rs/moq-clock) for an overview. diff --git a/rs/moq-clock/macros/Cargo.toml b/rs/moq-clock/macros/Cargo.toml deleted file mode 100644 index 6af8280d5ce..00000000000 --- a/rs/moq-clock/macros/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -# The `#[moq_clock::test]` attribute. A separate crate only because a proc macro -# must be; `moq-clock` re-exports it behind its `sim` feature. -[package] -name = "moq-clock-macros" -description = "The #[moq_clock::test] attribute; use it through moq-clock's sim feature." -authors = ["Luke Curley"] -repository = "https://github.com/moq-dev/moq" -license = "MIT OR Apache-2.0" - -version = "0.1.0" -edition = "2024" -rust-version.workspace = true - -keywords = ["moq", "test", "simulation"] -categories = ["development-tools::testing"] - -[lib] -proc-macro = true - -[lints] -workspace = true diff --git a/rs/moq-clock/macros/MIGRATE.md b/rs/moq-clock/macros/MIGRATE.md deleted file mode 100644 index f7e0a138a83..00000000000 --- a/rs/moq-clock/macros/MIGRATE.md +++ /dev/null @@ -1,5 +0,0 @@ -# Migrating moq-clock-macros - -How to update your code for each breaking change, newest first. - -## Unreleased diff --git a/rs/moq-congestion/Cargo.toml b/rs/moq-congestion/Cargo.toml index 01e8936a357..aa9eedf09b7 100644 --- a/rs/moq-congestion/Cargo.toml +++ b/rs/moq-congestion/Cargo.toml @@ -12,13 +12,13 @@ license = "MIT OR Apache-2.0" testing = [] [dependencies] -moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false } +kio = { workspace = true } rand = { workspace = true } rand_pcg = { workspace = true } [dev-dependencies] cpu-time = "1.0.0" -moq-clock = { path = "../moq-clock" } +kio = { path = "../kio", features = ["runtime"] } stats_alloc = "0.1.10" [lints] diff --git a/rs/moq-congestion/README.md b/rs/moq-congestion/README.md index de14ca649ee..898d009fb12 100644 --- a/rs/moq-congestion/README.md +++ b/rs/moq-congestion/README.md @@ -2,7 +2,7 @@ BBR3, Cubic, and Unlimited congestion controllers, consumed by moq-quic and the native transport drivers. -The controllers take explicit `moq_clock::Instant` values and never drive a runtime. The `Controller` trait names no transport types: `on_sent` returns an opaque per-packet state that the transport stores and hands back with each acknowledgement or loss, and the controller paces its own sends. +The controllers take explicit `kio::clock::Instant` values and never drive a runtime. The `Controller` trait names no transport types: `on_sent` returns an opaque per-packet state that the transport stores and hands back with each acknowledgement or loss, and the controller paces its own sends. The code was extracted from [moq-quic](../moq-quic), under the same MIT or Apache-2.0 license. Cubic originated in quinn; BBR3 was ported from moq-dev/noq and carries the fixes listed in [moq-quic's fork history](../moq-quic/README.md). diff --git a/rs/moq-congestion/src/lib.rs b/rs/moq-congestion/src/lib.rs index a45e32909fb..b3fc6b4d53b 100644 --- a/rs/moq-congestion/src/lib.rs +++ b/rs/moq-congestion/src/lib.rs @@ -5,7 +5,7 @@ //! packet's [`Packet`] state is stored by the transport and handed back on ACK or loss, so a //! controller keeps no per-packet table of its own. -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; use std::any::Any; diff --git a/rs/moq-congestion/src/pacer.rs b/rs/moq-congestion/src/pacer.rs index 33137fe6c72..b295b739b01 100644 --- a/rs/moq-congestion/src/pacer.rs +++ b/rs/moq-congestion/src/pacer.rs @@ -1,6 +1,6 @@ //! Pacing of packet transmissions. -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; /// A simple token-bucket pacer diff --git a/rs/moq-congestion/src/rate.rs b/rs/moq-congestion/src/rate.rs index 2a7285bf625..abb57f61bba 100644 --- a/rs/moq-congestion/src/rate.rs +++ b/rs/moq-congestion/src/rate.rs @@ -5,7 +5,7 @@ //! into a rate sample. //! -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; use crate::{Ack, Sent}; diff --git a/rs/moq-e2ee/Cargo.toml b/rs/moq-e2ee/Cargo.toml index 7815c77692d..0fafe3ebbda 100644 --- a/rs/moq-e2ee/Cargo.toml +++ b/rs/moq-e2ee/Cargo.toml @@ -25,7 +25,7 @@ zeroize = { workspace = true } [dev-dependencies] criterion = { package = "bench-harness", path = "../bench-harness" } hex = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } diff --git a/rs/moq-e2ee/tests/transport.rs b/rs/moq-e2ee/tests/transport.rs index d71b9d160d2..84620291471 100644 --- a/rs/moq-e2ee/tests/transport.rs +++ b/rs/moq-e2ee/tests/transport.rs @@ -89,7 +89,7 @@ async fn connect_protected(version: Version, track: &str) -> Fixture { #[tokio::test] async fn grouped_over_lite() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut fixture = connect_protected("moq-lite-07-wip".parse().unwrap(), "video").await; let mut group = fixture.producer.append_group().unwrap(); group @@ -106,7 +106,7 @@ async fn grouped_over_lite() { #[tokio::test] async fn grouped_over_ietf() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut fixture = connect_protected("moq-transport-22".parse().unwrap(), "video").await; let mut group = fixture.producer.append_group().unwrap(); group @@ -122,7 +122,7 @@ async fn grouped_over_ietf() { } async fn datagram_roundtrip(version: &str) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut fixture = connect_protected(version.parse().unwrap(), "audio").await; fixture .producer diff --git a/rs/moq-ffi/Cargo.toml b/rs/moq-ffi/Cargo.toml index 6fcfee974a6..736b72e5754 100644 --- a/rs/moq-ffi/Cargo.toml +++ b/rs/moq-ffi/Cargo.toml @@ -34,15 +34,14 @@ qlog = ["moq-tokio/qlog"] # Test-only hooks for the host suites: control of the runtime clock (`just py test`) and a # count of moq's heap (the Dart leak tests). Released builds leave it off, so they never # carry the `moq_ffi_test_*` symbols or the counting allocator. -testing = ["moq-clock/manual"] +testing = ["kio/manual"] [dependencies] bytes = { workspace = true } hang = { workspace = true } -kio = { workspace = true } +kio = { workspace = true, features = ["runtime"] } # Codecs only: the language wrappers do their own device I/O. moq-audio = { workspace = true, optional = true, features = ["aac"] } -moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-ffi/src/auth.rs b/rs/moq-ffi/src/auth.rs index 9c1a046c99b..f21687a0f3f 100644 --- a/rs/moq-ffi/src/auth.rs +++ b/rs/moq-ffi/src/auth.rs @@ -94,7 +94,7 @@ mod tests { // Let the wait park before cancelling it. tokio::task::yield_now().await; grants.cancel(); - let result = moq_clock::timeout(Duration::from_secs(5), waiting) + let result = kio::clock::timeout(Duration::from_secs(5), waiting) .await .expect("the wait outlived its cancel") .unwrap(); diff --git a/rs/moq-ffi/src/bench.rs b/rs/moq-ffi/src/bench.rs index 9e06333261b..b2751380a2e 100644 --- a/rs/moq-ffi/src/bench.rs +++ b/rs/moq-ffi/src/bench.rs @@ -98,7 +98,7 @@ impl Report { Fut: Future, { // The test runs many budgets back to back, so a wedged read is caught per round, not by nextest. - let mut run = |n| moq_clock::timeout(ROUND_TIMEOUT, round(n)); + let mut run = |n| kio::clock::timeout(ROUND_TIMEOUT, round(n)); for n in 0..WARMUP { run(n).await.expect("round wedged"); } diff --git a/rs/moq-ffi/src/ffi.rs b/rs/moq-ffi/src/ffi.rs index 4fdd43e7524..2c25c58d7b4 100644 --- a/rs/moq-ffi/src/ffi.rs +++ b/rs/moq-ffi/src/ffi.rs @@ -19,7 +19,7 @@ pub(crate) struct Runtime { handle: tokio::runtime::Handle, /// The clock a test drives, when the runtime started with one. #[cfg(feature = "testing")] - clock: Option, + clock: Option, /// Taken by [`shutdown`], so the thread is stopped and joined once. thread: std::sync::Mutex>, /// Set by [`shutdown`] to wake the [`Task::run`] calls parked in place, so they observe @@ -58,7 +58,7 @@ pub(crate) fn runtime() -> &'static Runtime { RUNTIME.get_or_init(|| Runtime::new(false)) } -/// Start the runtime on a [`moq_clock::Manual`] clock that only a test moves. +/// Start the runtime on a [`kio::clock::Manual`] clock that only a test moves. /// /// False when the runtime already started, since its timers are armed on the host clock. #[cfg(feature = "testing")] @@ -73,7 +73,7 @@ pub(crate) fn start_test_clock() -> bool { /// The clock [`start_test_clock`] installed, if it did. #[cfg(feature = "testing")] -pub(crate) fn test_clock() -> Option<&'static moq_clock::Installed> { +pub(crate) fn test_clock() -> Option<&'static kio::clock::Installed> { RUNTIME.get()?.clock.as_ref() } @@ -93,7 +93,7 @@ impl Runtime { let handle = runtime.handle().clone(); // Before any task runs, so every read and timer lands on it. #[cfg(feature = "testing")] - let clock = test_clock.then(|| moq_clock::Manual::new().install(&handle)); + let clock = test_clock.then(|| kio::clock::Manual::new().install(&handle)); let (stop, stopped) = tokio::sync::oneshot::channel(); let join = std::thread::Builder::new() @@ -686,7 +686,7 @@ mod tests { /// Fail the test instead of hanging when a wakeup goes missing. async fn soon(f: F) -> F::Output { - moq_clock::timeout(Duration::from_secs(5), f).await.expect("timed out") + kio::clock::timeout(Duration::from_secs(5), f).await.expect("timed out") } #[tokio::test] diff --git a/rs/moq-ffi/src/lib.rs b/rs/moq-ffi/src/lib.rs index 5ba2360df5a..5e8e59729ff 100644 --- a/rs/moq-ffi/src/lib.rs +++ b/rs/moq-ffi/src/lib.rs @@ -75,7 +75,7 @@ pub extern "C" fn moq_ffi_test_clock_advance(nanos: u64) -> bool { #[unsafe(no_mangle)] pub extern "C" fn moq_ffi_test_clock_now() -> u64 { ffi::test_clock().map_or(u64::MAX, |clock| { - clock.now().duration_since(moq_clock::Instant::ZERO).as_nanos() as u64 + clock.now().duration_since(kio::clock::Instant::ZERO).as_nanos() as u64 }) } diff --git a/rs/moq-ffi/src/media.rs b/rs/moq-ffi/src/media.rs index 930f09d0b38..ddac8c5fb0b 100644 --- a/rs/moq-ffi/src/media.rs +++ b/rs/moq-ffi/src/media.rs @@ -2038,7 +2038,7 @@ mod timebase_tests { reserve(); } for touched in [1, 16, 256] { - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); for _ in 0..1000 { for _ in 0..touched { reserve(); diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index fd119bcfa2a..e1bbd7ce5b7 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -73,11 +73,11 @@ where std::task::Poll::Pending => fut.await, } }); - moq_clock::timeout(TIMEOUT, started_rx) + kio::clock::timeout(TIMEOUT, started_rx) .await .expect("timed out waiting for the read to start") .expect("the read task dropped before polling"); - moq_clock::timeout(TIMEOUT, ffi_caught_up()) + kio::clock::timeout(TIMEOUT, ffi_caught_up()) .await .expect("timed out waiting for the FFI runtime to poll the read"); handle @@ -113,7 +113,7 @@ async fn wait_for_config_error( mut op: impl FnMut() -> Result<(), MoqError>, want: impl Fn(&MoqError) -> bool, ) -> MoqError { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { match op() { Err(err) if want(&err) => return err, @@ -128,7 +128,7 @@ async fn wait_for_config_error( /// Wait until `read_frame` has taken `group` off the ordered cursor. async fn wait_group_acquired(group: &MoqGroupProducer) { - moq_clock::timeout(TIMEOUT, group.wanted()) + kio::clock::timeout(TIMEOUT, group.wanted()) .await .expect("timed out waiting for the group to be acquired") .unwrap(); @@ -187,13 +187,13 @@ async fn detached_cancels_inner_on_drop() { std::future::pending::>().await })); - moq_clock::timeout(TIMEOUT, started_rx) + kio::clock::timeout(TIMEOUT, started_rx) .await .expect("timed out waiting for detached task to start") .unwrap(); outer.abort(); assert!(outer.await.unwrap_err().is_cancelled()); - moq_clock::timeout(TIMEOUT, dropped_rx) + kio::clock::timeout(TIMEOUT, dropped_rx) .await .expect("timed out waiting for detached task to be dropped") .unwrap(); @@ -223,7 +223,7 @@ fn video_init(format: MoqVideoFormat, data: Vec) -> MoqVideoInit { /// These tests wait for that future announcement before resolving the reference. async fn await_announced(consumer: &MoqOriginConsumer, path: &str) -> Arc { let announced = consumer.follow(path.into(), None).unwrap(); - moq_clock::timeout(TIMEOUT, announced.available()) + kio::clock::timeout(TIMEOUT, announced.available()) .await .unwrap_or_else(|_| panic!("timed out waiting for {path} to be announced")) .unwrap() @@ -239,7 +239,7 @@ fn create_announced(origin: &MoqOriginProducer, path: &str) -> Arc MoqAnnounceEvent { - moq_clock::timeout(TIMEOUT, announced.next()) + kio::clock::timeout(TIMEOUT, announced.next()) .await .expect("timed out waiting for an announce event") .unwrap() @@ -519,13 +519,13 @@ async fn raw_track_activity() { assert_eq!(demand.name(), "status"); let consumer = track.consume(None).unwrap(); - moq_clock::timeout(TIMEOUT, demand.until_wanted()) + kio::clock::timeout(TIMEOUT, demand.until_wanted()) .await .expect("timed out waiting for raw track to become used") .unwrap(); drop(consumer); - moq_clock::timeout(TIMEOUT, demand.until_unwanted()) + kio::clock::timeout(TIMEOUT, demand.until_unwanted()) .await .expect("timed out waiting for raw track to become unused") .unwrap(); @@ -568,7 +568,7 @@ async fn raw_audio_activity() { .unwrap(); assert_eq!(audio.demand().unwrap().name(), "microphone"); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for raw audio catalog") .unwrap() @@ -586,7 +586,7 @@ async fn raw_audio_activity() { ) .await .unwrap(); - moq_clock::timeout(TIMEOUT, audio.demand().unwrap().until_wanted()) + kio::clock::timeout(TIMEOUT, audio.demand().unwrap().until_wanted()) .await .expect("timed out waiting for raw audio to become used") .unwrap(); @@ -596,7 +596,7 @@ async fn raw_audio_activity() { data: vec![0; FRAME_SAMPLES * std::mem::size_of::()], }) .unwrap(); - let first = moq_clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) + let first = kio::clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) .await .expect("timed out waiting for raw audio frame") .unwrap() @@ -604,7 +604,7 @@ async fn raw_audio_activity() { assert_eq!(first.timestamp_us, FIRST_TIMESTAMP_US); drop(subscription); - moq_clock::timeout(TIMEOUT, audio.demand().unwrap().until_unwanted()) + kio::clock::timeout(TIMEOUT, audio.demand().unwrap().until_unwanted()) .await .expect("timed out waiting for raw audio to become unused") .unwrap(); @@ -618,7 +618,7 @@ async fn raw_audio_activity() { ) .await .unwrap(); - moq_clock::timeout(TIMEOUT, audio.demand().unwrap().until_wanted()) + kio::clock::timeout(TIMEOUT, audio.demand().unwrap().until_wanted()) .await .expect("timed out waiting for raw audio to become used again") .unwrap(); @@ -629,13 +629,13 @@ async fn raw_audio_activity() { data: vec![0; FRAME_SAMPLES * std::mem::size_of::()], }) .unwrap(); - let mut resumed = moq_clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) + let mut resumed = kio::clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) .await .expect("timed out waiting for resumed raw audio frame") .unwrap() .expect("expected a resumed raw audio frame"); if resumed.timestamp_us == first.timestamp_us { - resumed = moq_clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) + resumed = kio::clock::timeout(TIMEOUT, next_encoded_frame(&subscription)) .await .expect("timed out waiting for re-anchored raw audio frame") .unwrap() @@ -727,7 +727,7 @@ async fn audio_subscribes_a_held_disabled_rendition() { } audio.finish().unwrap(); let mut frames = 0; - while let Some(read) = moq_clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { + while let Some(read) = kio::clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { if matches!(read, MoqAudioRead::Frame { .. }) { frames += 1; } @@ -795,7 +795,7 @@ async fn audio_raw_publish_from_many_threads() { let closer = audio.clone(); std::thread::spawn(move || closer.finish()).join().unwrap().unwrap(); let mut pcm = Vec::new(); - while let Some(read) = moq_clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { + while let Some(read) = kio::clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { let frame = match read { MoqAudioRead::Frame { frame } => frame, MoqAudioRead::End { end_us } => { @@ -901,7 +901,7 @@ async fn raw_audio_decode_delay() { }, ) .unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for raw audio catalog") .unwrap() @@ -939,7 +939,7 @@ async fn raw_audio_decode_delay() { .unwrap(); } for read in [fixed_read, estimated_read] { - let read = moq_clock::timeout(TIMEOUT, read) + let read = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out waiting for decoded audio") .unwrap() @@ -1031,7 +1031,7 @@ async fn raw_audio_decode_reports_encoder_ends() { let mut ends = Vec::new(); let mut frames = Vec::new(); - while let Some(read) = moq_clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { + while let Some(read) = kio::clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { match read { MoqAudioRead::Frame { frame } => frames.push((ends.len(), frame.timestamp_us)), MoqAudioRead::Gap { .. } => panic!("nothing was lost"), @@ -1212,7 +1212,7 @@ async fn raw_track_datagram_roundtrip() { timestamp_us: Some(123_456), }) .unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for datagram") .unwrap() @@ -1275,7 +1275,7 @@ async fn raw_track_update_does_not_wait_for_pending_read() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, read) + let frame = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out waiting for raw frame") .expect("read task panicked") @@ -1427,7 +1427,7 @@ async fn json_snapshot_roundtrip() { producer.update(format!(r#"{{"a":{n}}}"#), Some(n * 1000)).unwrap(); } - let value = moq_clock::timeout(TIMEOUT, consumer.next()) + let value = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for json snapshot") .unwrap() @@ -1438,7 +1438,7 @@ async fn json_snapshot_roundtrip() { ); assert_eq!(value.timestamp_us, Some(1000)); - let value = moq_clock::timeout(TIMEOUT, consumer.next()) + let value = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for json snapshot delta") .unwrap() @@ -1450,7 +1450,7 @@ async fn json_snapshot_roundtrip() { assert_eq!(value.timestamp_us, Some(2000)); // `latest` skips the buffered third state. - let value = moq_clock::timeout(TIMEOUT, consumer.latest()) + let value = kio::clock::timeout(TIMEOUT, consumer.latest()) .await .expect("timed out waiting for the latest json snapshot") .unwrap() @@ -1466,7 +1466,7 @@ async fn json_snapshot_roundtrip() { producer.update(r#"{"a":5}"#.into(), Some(5000)), Err(MoqError::Closed) )); - let end = moq_clock::timeout(TIMEOUT, consumer.next()) + let end = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for the end of the json snapshot") .unwrap(); @@ -1499,7 +1499,7 @@ async fn json_snapshot_refreshes_for_a_joiner() { // The join crosses the ratio, so the producer restates the value without another update. The // joiner may read the open group first or skip straight to the restatement. let joiner = subscribe(&broadcast, "meta").await; - let refreshed = moq_clock::timeout(TIMEOUT, async { + let refreshed = kio::clock::timeout(TIMEOUT, async { loop { let group = joiner.recv_group().await.unwrap().expect("expected a group"); if group.sequence() > 0 { @@ -1511,7 +1511,7 @@ async fn json_snapshot_refreshes_for_a_joiner() { .expect("timed out waiting for the refresh"); assert_eq!(refreshed.sequence(), 1); let consumer = MoqJsonSnapshotConsumer::new(&*subscribe(&broadcast, "meta").await).unwrap(); - let value = moq_clock::timeout(TIMEOUT, consumer.next()) + let value = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for the restated value") .unwrap() @@ -1542,11 +1542,11 @@ async fn json_demand() { let snapshot_consumer = MoqJsonSnapshotConsumer::new(&*subscribe(&broadcast, "status").await).unwrap(); let stream_consumer = MoqJsonStreamConsumer::new(&*subscribe(&broadcast, "events").await).unwrap(); - moq_clock::timeout(TIMEOUT, snapshot_demand.until_wanted()) + kio::clock::timeout(TIMEOUT, snapshot_demand.until_wanted()) .await .expect("timed out waiting for the json snapshot to become used") .unwrap(); - moq_clock::timeout(TIMEOUT, stream_demand.until_wanted()) + kio::clock::timeout(TIMEOUT, stream_demand.until_wanted()) .await .expect("timed out waiting for the json stream to become used") .unwrap(); @@ -1554,11 +1554,11 @@ async fn json_demand() { drop(snapshot_consumer); drop(stream_consumer); - moq_clock::timeout(TIMEOUT, snapshot_demand.until_unwanted()) + kio::clock::timeout(TIMEOUT, snapshot_demand.until_unwanted()) .await .expect("timed out waiting for the json snapshot to become unused") .unwrap(); - moq_clock::timeout(TIMEOUT, stream_demand.until_unwanted()) + kio::clock::timeout(TIMEOUT, stream_demand.until_unwanted()) .await .expect("timed out waiting for the json stream to become unused") .unwrap(); @@ -1573,7 +1573,7 @@ async fn json_demand() { /// Read the next window event, failing the test if none arrives. async fn next_window(consumer: &MoqJsonWindowConsumer) -> Option { - moq_clock::timeout(TIMEOUT, consumer.next()) + kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for a json window event") .unwrap() @@ -1670,7 +1670,7 @@ async fn json_window_cut_restates_the_window() { producer.cut().unwrap(); producer.push(r#"{"n":3}"#.into(), None).unwrap(); - let group = moq_clock::timeout(TIMEOUT, async { + let group = kio::clock::timeout(TIMEOUT, async { loop { let group = raw.recv_group().await.unwrap().expect("expected a group"); if group.sequence() > 0 { @@ -1727,7 +1727,7 @@ async fn json_window_refreshes_a_bounded_checkpoint_for_a_joiner() { // The join crosses the ratio, so the producer restates the window without another edit. let joiner = subscribe(&broadcast, "log").await; - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while joiner.recv_group().await.unwrap().expect("expected a group").sequence() == 0 {} }) .await @@ -1780,12 +1780,12 @@ async fn json_window_demand() { assert!(demand.wanted().is_none()); let consumer = MoqJsonWindowConsumer::new(&*subscribe(&broadcast, "log").await).unwrap(); - moq_clock::timeout(TIMEOUT, demand.until_wanted()) + kio::clock::timeout(TIMEOUT, demand.until_wanted()) .await .expect("timed out waiting for the json window to become used") .unwrap(); drop(consumer); - moq_clock::timeout(TIMEOUT, demand.until_unwanted()) + kio::clock::timeout(TIMEOUT, demand.until_unwanted()) .await .expect("timed out waiting for the json window to become unused") .unwrap(); @@ -1815,7 +1815,7 @@ async fn demand_handle_outlives_finish() { assert_eq!(media_demand.name(), media.demand().unwrap().name()); let consumer = track.consume(None).unwrap(); - moq_clock::timeout(TIMEOUT, track_demand.until_wanted()) + kio::clock::timeout(TIMEOUT, track_demand.until_wanted()) .await .expect("timed out waiting for the raw track to become used") .unwrap(); @@ -1825,10 +1825,10 @@ async fn demand_handle_outlives_finish() { drop(track); media.finish().unwrap(); broadcast.close().unwrap(); - let track_err = moq_clock::timeout(TIMEOUT, track_demand.until_wanted()) + let track_err = kio::clock::timeout(TIMEOUT, track_demand.until_wanted()) .await .expect("timed out waiting for the finished raw track"); - let media_err = moq_clock::timeout(TIMEOUT, media_demand.until_wanted()) + let media_err = kio::clock::timeout(TIMEOUT, media_demand.until_wanted()) .await .expect("timed out waiting for the finished media track"); assert!(matches!(track_err, Err(MoqError::Closed)), "{track_err:?}"); @@ -1844,7 +1844,7 @@ async fn json_stream_roundtrip() { for n in 0..3 { producer.append(format!(r#"{{"n":{n}}}"#), None).unwrap(); - let value = moq_clock::timeout(TIMEOUT, consumer.next()) + let value = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for json stream record") .unwrap() @@ -1869,12 +1869,12 @@ async fn json_on_requested_track() { let consumer = broadcast.consume().unwrap(); tokio::spawn(async move { consumer.subscribe_track("events".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_track()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) .await .expect("timed out waiting for requested track") .unwrap(); let producer = MoqJsonStreamProducer::new(&broadcast, &request.accept(None).unwrap()).unwrap(); - let track = moq_clock::timeout(TIMEOUT, subscribe) + let track = kio::clock::timeout(TIMEOUT, subscribe) .await .expect("timed out waiting for the subscribe") .unwrap() @@ -1882,7 +1882,7 @@ async fn json_on_requested_track() { let consumer = MoqJsonStreamConsumer::new(&track).unwrap(); producer.append(r#"{"n":1}"#.into(), None).unwrap(); - let value = moq_clock::timeout(TIMEOUT, consumer.next()) + let value = kio::clock::timeout(TIMEOUT, consumer.next()) .await .expect("timed out waiting for json stream record") .unwrap() @@ -1903,7 +1903,7 @@ async fn json_consumer_takes_an_unread_track() { .await .unwrap(); track.append_group().unwrap().finish().unwrap(); - moq_clock::timeout(TIMEOUT, read.recv_group()) + kio::clock::timeout(TIMEOUT, read.recv_group()) .await .expect("timed out waiting for a group") .unwrap() @@ -1979,7 +1979,7 @@ async fn dynamic_track_request() { tokio::spawn(async move { consumer.subscribe_track("events".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_track()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) .await .expect("timed out waiting for requested track") .unwrap(); @@ -1995,13 +1995,13 @@ async fn dynamic_track_request() { }) .unwrap(); - let track_consumer = moq_clock::timeout(TIMEOUT, subscribe) + let track_consumer = kio::clock::timeout(TIMEOUT, subscribe) .await .expect("timed out waiting for subscribe") .expect("subscribe task panicked") .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, track_consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, track_consumer.read_frame()) .await .expect("timed out waiting for dynamic track frame") .unwrap() @@ -2091,7 +2091,7 @@ async fn raw_frame_timestamps() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out waiting for raw track frame") .unwrap() @@ -2110,7 +2110,7 @@ async fn raw_frame_timestamps() { .unwrap(); group.finish().unwrap(); - let frame = moq_clock::timeout(TIMEOUT, group_consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_consumer.read_frame()) .await .expect("timed out waiting for raw group frame") .unwrap() @@ -2197,7 +2197,7 @@ async fn dynamic_track_request_can_abort() { tokio::spawn(async move { consumer.subscribe_track("unknown".into(), None).await }) }; - let track = moq_clock::timeout(TIMEOUT, dynamic.requested_track()) + let track = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) .await .expect("timed out waiting for requested track") .unwrap(); @@ -2205,7 +2205,7 @@ async fn dynamic_track_request_can_abort() { track.abort(404).unwrap(); assert!(matches!(track.name(), Err(MoqError::Closed))); - let result = moq_clock::timeout(TIMEOUT, subscribe) + let result = kio::clock::timeout(TIMEOUT, subscribe) .await .expect("timed out waiting for subscribe") .expect("subscribe task panicked"); @@ -2360,7 +2360,7 @@ async fn fetch_media_group_decodes_multiple_cmaf_samples() { } media.finish().unwrap(); - let fetched = moq_clock::timeout( + let fetched = kio::clock::timeout( TIMEOUT, MoqMediaGroupConsumer::fetch( &consumer, @@ -2375,7 +2375,7 @@ async fn fetch_media_group_decodes_multiple_cmaf_samples() { .expect("timed out fetching CMAF group") .unwrap(); - let first = moq_clock::timeout(TIMEOUT, fetched.next()) + let first = kio::clock::timeout(TIMEOUT, fetched.next()) .await .expect("timed out reading first CMAF sample") .unwrap() @@ -2383,7 +2383,7 @@ async fn fetch_media_group_decodes_multiple_cmaf_samples() { assert_eq!(first.payload, b"keyframe"); assert_eq!(first.timestamp_us, 2_000_000); assert!(first.keyframe); - let second = moq_clock::timeout(TIMEOUT, fetched.next()) + let second = kio::clock::timeout(TIMEOUT, fetched.next()) .await .expect("timed out reading second CMAF sample") .unwrap() @@ -2392,7 +2392,7 @@ async fn fetch_media_group_decodes_multiple_cmaf_samples() { assert_eq!(second.timestamp_us, 2_020_000); assert!(!second.keyframe); assert!( - moq_clock::timeout(TIMEOUT, fetched.next()) + kio::clock::timeout(TIMEOUT, fetched.next()) .await .expect("timed out finishing CMAF group") .unwrap() @@ -2435,7 +2435,7 @@ async fn legacy_track() -> ( } async fn recv_raw_group(track: &MoqTrackConsumer) -> Arc { - moq_clock::timeout(TIMEOUT, track.recv_group()) + kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("timed out waiting for a group") .unwrap() @@ -2448,7 +2448,7 @@ async fn recv_media_group(track: &MoqTrackConsumer) -> Arc Result, MoqError> { - moq_clock::timeout(TIMEOUT, group.next()) + kio::clock::timeout(TIMEOUT, group.next()) .await .expect("timed out reading a media frame") } @@ -2564,7 +2564,7 @@ async fn dynamic_track_serves_fetch_miss_and_priority() { .await }); - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_fill()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_fill()) .await .expect("timed out waiting for fill") .unwrap(); @@ -2584,7 +2584,7 @@ async fn dynamic_track_serves_fetch_miss_and_priority() { .unwrap(); group.finish().unwrap(); - let fetched = moq_clock::timeout(TIMEOUT, fetch) + let fetched = kio::clock::timeout(TIMEOUT, fetch) .await .expect("timed out waiting for fetch") .expect("fetch task panicked") @@ -2603,7 +2603,7 @@ async fn fill_goes_unwanted_when_the_fetcher_leaves() { let consumer = broadcast.consume().unwrap(); let fetch = tokio::spawn(async move { consumer.fetch_group("events".into(), 5, None).await }); - let fill = moq_clock::timeout(TIMEOUT, dynamic.requested_fill()) + let fill = kio::clock::timeout(TIMEOUT, dynamic.requested_fill()) .await .expect("timed out waiting for fill") .unwrap(); @@ -2612,13 +2612,13 @@ async fn fill_goes_unwanted_when_the_fetcher_leaves() { assert!(!fill.is_wanted(6), "outside the fill"); fetch.abort(); - let wanted = moq_clock::timeout(TIMEOUT, fill.wanted_changed()) + let wanted = kio::clock::timeout(TIMEOUT, fill.wanted_changed()) .await .expect("timed out waiting for the abandoned fetch to become unwanted") .unwrap(); assert_eq!(wanted, None); assert_eq!(fill.wanted(), None); - moq_clock::timeout(TIMEOUT, fill.unwanted(5)) + kio::clock::timeout(TIMEOUT, fill.unwanted(5)) .await .expect("an unwanted fill wants none of its groups") .unwrap(); @@ -2636,7 +2636,7 @@ async fn fill_wanted_changed_cancelled_before_free_leaves_the_change() { let consumer = broadcast.consume().unwrap(); let fetch = tokio::spawn(async move { consumer.fetch_group("events".into(), 5, None).await }); - let fill = moq_clock::timeout(TIMEOUT, dynamic.requested_fill()) + let fill = kio::clock::timeout(TIMEOUT, dynamic.requested_fill()) .await .expect("timed out waiting for fill") .unwrap(); @@ -2653,7 +2653,7 @@ async fn fill_wanted_changed_cancelled_before_free_leaves_the_change() { let next = fill.wanted_changed(); drop(cancelled); - let wanted = moq_clock::timeout(TIMEOUT, next) + let wanted = kio::clock::timeout(TIMEOUT, next) .await .expect("the cancelled call took the change") .unwrap(); @@ -2668,14 +2668,14 @@ async fn dynamic_track_rejects_fetch_miss() { let consumer = broadcast.consume().unwrap(); let fetch = tokio::spawn(async move { consumer.fetch_group("events".into(), 5, None).await }); - let fill = moq_clock::timeout(TIMEOUT, dynamic.requested_fill()) + let fill = kio::clock::timeout(TIMEOUT, dynamic.requested_fill()) .await .expect("timed out waiting for fill") .unwrap(); fill.drop_groups(5, 6); assert_eq!(fill.wanted(), None, "the dropped group is answered"); - let result = moq_clock::timeout(TIMEOUT, fetch) + let result = kio::clock::timeout(TIMEOUT, fetch) .await .expect("timed out waiting for rejected fetch") .expect("fetch task panicked"); @@ -2709,14 +2709,14 @@ async fn requested_track_dynamic_survives_accept() { let consumer = broadcast.consume().unwrap(); let fetch = tokio::spawn(async move { consumer.fetch_group("archive".into(), 9, None).await }); - let request = moq_clock::timeout(TIMEOUT, broadcast_dynamic.requested_track()) + let request = kio::clock::timeout(TIMEOUT, broadcast_dynamic.requested_track()) .await .expect("timed out waiting for track request") .unwrap(); let track_dynamic = request.requests().unwrap(); let _track = request.accept(Some(timed_info())).unwrap(); - let fill = moq_clock::timeout(TIMEOUT, track_dynamic.requested_fill()) + let fill = kio::clock::timeout(TIMEOUT, track_dynamic.requested_fill()) .await .expect("timed out waiting for fill") .unwrap(); @@ -2730,7 +2730,7 @@ async fn requested_track_dynamic_survives_accept() { .unwrap(); group.finish().unwrap(); - let fetched = moq_clock::timeout(TIMEOUT, fetch) + let fetched = kio::clock::timeout(TIMEOUT, fetch) .await .expect("timed out waiting for fetch") .expect("fetch task panicked") @@ -2781,7 +2781,7 @@ async fn video_publish_named_track() { Err(MoqError::Codec { .. }) )); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -2849,7 +2849,7 @@ async fn track_stream_producer_publishes_its_last_access_unit() { } stream.finish().unwrap(); - let frame = moq_clock::timeout(TIMEOUT, track.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, track.read_frame()) .await .expect("timed out waiting for the access unit") .unwrap() @@ -2873,7 +2873,7 @@ async fn requested_track_keeps_its_name() { .await }); - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_track()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) .await .expect("timed out waiting for requested track") .unwrap(); @@ -2913,7 +2913,7 @@ async fn dynamic_track_request_can_publish_media() { }) }; - let track = moq_clock::timeout(TIMEOUT, dynamic.requested_track()) + let track = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) .await .expect("timed out waiting for requested track") .unwrap(); @@ -2928,13 +2928,13 @@ async fn dynamic_track_request_can_publish_media() { assert_eq!(media.demand().unwrap().name(), "requested-audio"); assert!(matches!(track.name(), Err(MoqError::Closed))); - let media_consumer = moq_clock::timeout(TIMEOUT, subscribe) + let media_consumer = kio::clock::timeout(TIMEOUT, subscribe) .await .expect("timed out waiting for subscribe") .expect("subscribe task panicked") .unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -2955,7 +2955,7 @@ async fn dynamic_track_request_can_publish_media() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .expect("timed out waiting for media frame") .unwrap() @@ -2983,7 +2983,7 @@ async fn media_track_activity_and_name() { let broadcast_consumer = broadcast.consume().unwrap(); let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -2991,13 +2991,13 @@ async fn media_track_activity_and_name() { assert!(catalog.audio.contains_key(&track_name)); let track_consumer = broadcast_consumer.subscribe_track(track_name, None).await.unwrap(); - moq_clock::timeout(TIMEOUT, media.demand().unwrap().until_wanted()) + kio::clock::timeout(TIMEOUT, media.demand().unwrap().until_wanted()) .await .expect("timed out waiting for media track to become used") .unwrap(); drop(track_consumer); - moq_clock::timeout(TIMEOUT, media.demand().unwrap().until_unwanted()) + kio::clock::timeout(TIMEOUT, media.demand().unwrap().until_unwanted()) .await .expect("timed out waiting for media track to become unused") .unwrap(); @@ -3021,7 +3021,7 @@ async fn publish_media_aac_populates_description() { let consumer = broadcast.consume().unwrap(); let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -3063,7 +3063,7 @@ async fn create_broadcast_is_invisible_until_announced() { let consumer = origin.consume(); let publication = origin.create_broadcast("live".into()).unwrap(); - let unroutable = moq_clock::timeout(TIMEOUT, consumer.request("live".into(), None)) + let unroutable = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("an unroutable request answers at once"); assert!(unroutable.is_err(), "an unannounced broadcast is unroutable"); @@ -3072,17 +3072,17 @@ async fn create_broadcast_is_invisible_until_announced() { let pending = tokio::spawn(async move { announced.next().await }); let waiting = consumer.follow("live".into(), None).unwrap(); let waited = tokio::spawn(async move { waiting.available().await }); - moq_clock::sleep(std::time::Duration::from_millis(50)).await; + kio::clock::sleep(std::time::Duration::from_millis(50)).await; assert!(!pending.is_finished(), "create_broadcast must not advertise the path"); assert!(!waited.is_finished(), "an unannounced broadcast must not resolve"); publication.announce(MoqAnnounceRoute::default()).unwrap(); - moq_clock::timeout(TIMEOUT, waited) + kio::clock::timeout(TIMEOUT, waited) .await .expect("timed out waiting for the announced broadcast") .expect("task") .expect("the announced broadcast resolves"); - let update = moq_clock::timeout(TIMEOUT, pending) + let update = kio::clock::timeout(TIMEOUT, pending) .await .expect("timed out waiting for announce") .expect("task") @@ -3106,14 +3106,14 @@ async fn follow_keeps_the_requested_path() { let broadcast = create_announced(&origin, "a/pub"); let announced = consumer.follow("a/pub".into(), None).unwrap(); - let waited = moq_clock::timeout(TIMEOUT, announced.available()) + let waited = kio::clock::timeout(TIMEOUT, announced.available()) .await .expect("timed out waiting for the announcement") .unwrap(); assert_eq!(waited.inner().info().path.as_str(), "a/pub"); // The same broadcast reached by request names itself identically. - let requested = moq_clock::timeout(TIMEOUT, consumer.request("a/pub".into(), None)) + let requested = kio::clock::timeout(TIMEOUT, consumer.request("a/pub".into(), None)) .await .expect("timed out requesting the broadcast") .unwrap(); @@ -3140,7 +3140,7 @@ async fn audio_consumer_follows_a_sibling_broadcast_reference() { let broadcast = await_announced(&consumer, "a/pub").await; await_announced(&consumer, "a/source").await; - let decoded = moq_clock::timeout( + let decoded = kio::clock::timeout( TIMEOUT, crate::audio::MoqAudioConsumer::subscribe( &broadcast, @@ -3154,7 +3154,7 @@ async fn audio_consumer_follows_a_sibling_broadcast_reference() { decoded.expect("the rendition's broadcast reference should resolve to the sibling"); // Without the reference the same call has nowhere to find the track. - let missing = moq_clock::timeout( + let missing = kio::clock::timeout( TIMEOUT, crate::audio::MoqAudioConsumer::subscribe(&broadcast, "audio".into(), sibling_audio(""), audio_output()), ) @@ -3217,7 +3217,7 @@ async fn media_consumers_follow_a_rendition_track_in_a_sibling_broadcast() { config, }; - let live = moq_clock::timeout( + let live = kio::clock::timeout( TIMEOUT, MoqMediaTrackConsumer::subscribe( &broadcast, @@ -3230,14 +3230,14 @@ async fn media_consumers_follow_a_rendition_track_in_a_sibling_broadcast() { .await .expect("timed out subscribing to the rendition") .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&live)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&live)) .await .expect("timed out reading the rendition") .unwrap() .expect("expected a frame"); assert_eq!(frame.payload, b"right"); - let fetched = moq_clock::timeout( + let fetched = kio::clock::timeout( TIMEOUT, MoqMediaGroupConsumer::fetch( &broadcast, @@ -3251,7 +3251,7 @@ async fn media_consumers_follow_a_rendition_track_in_a_sibling_broadcast() { .await .expect("timed out fetching the rendition") .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, fetched.next()) + let frame = kio::clock::timeout(TIMEOUT, fetched.next()) .await .expect("timed out reading the fetched group") .unwrap() @@ -3300,11 +3300,11 @@ async fn followed_broadcasts_resolve_siblings_under_the_prefix() { await_announced(&consumer, "a/source").await; - let sibling = moq_clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some("./source"), None))) + let sibling = kio::clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some("./source"), None))) .await .expect("timed out resolving the reference") .unwrap(); - moq_clock::timeout(TIMEOUT, sibling.subscribe_track("video".into(), None)) + kio::clock::timeout(TIMEOUT, sibling.subscribe_track("video".into(), None)) .await .expect("timed out subscribing on the resolved broadcast") .unwrap(); @@ -3400,20 +3400,20 @@ async fn resolve_returns_a_broadcast_that_resolves_further_references() { let broadcast = await_announced(&consumer, "a/pub").await; await_announced(&consumer, "a/source").await; - let sibling = moq_clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some("./source"), None))) + let sibling = kio::clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some("./source"), None))) .await .expect("timed out resolving the reference") .unwrap(); assert_eq!(sibling.inner().info().path.as_str(), "a/source"); // The sibling is a full consumer: the referenced track subscribes on it directly. - moq_clock::timeout(TIMEOUT, sibling.subscribe_track("video".into(), None)) + kio::clock::timeout(TIMEOUT, sibling.subscribe_track("video".into(), None)) .await .expect("timed out subscribing on the resolved broadcast") .unwrap(); // And it can follow a reference of its own, back to where we started. - let back = moq_clock::timeout(TIMEOUT, sibling.resolve(referencing(Some("./pub"), None))) + let back = kio::clock::timeout(TIMEOUT, sibling.resolve(referencing(Some("./pub"), None))) .await .expect("timed out resolving back") .unwrap(); @@ -3433,7 +3433,7 @@ async fn resolve_honors_the_reference_epoch() { reference: &str, epoch: Option<&str>, ) -> Result, MoqError> { - moq_clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some(reference), epoch))) + kio::clock::timeout(TIMEOUT, broadcast.resolve(referencing(Some(reference), epoch))) .await .expect("timed out resolving the reference") } @@ -3485,7 +3485,7 @@ async fn resolve_honors_the_reference_epoch() { rendition: referencing(Some("./source"), Some(&other)), subscription: None, }; - let subscribed = moq_clock::timeout(TIMEOUT, MoqMediaTrackConsumer::subscribe(&broadcast, config)) + let subscribed = kio::clock::timeout(TIMEOUT, MoqMediaTrackConsumer::subscribe(&broadcast, config)) .await .expect("timed out subscribing to the rendition"); assert!(matches!(subscribed, Err(MoqError::Mux { reason }) if reason.contains("serves epoch"))); @@ -3520,7 +3520,7 @@ async fn announce_and_unannounce_toggles_discovery() { wait_live(&announced, false).await; // Unannounced for local consumers exactly as for peers. - let unroutable = moq_clock::timeout(TIMEOUT, consumer.request("live".into(), None)) + let unroutable = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("an unroutable request answers at once"); assert!(unroutable.is_err(), "an unannounced broadcast is unroutable"); @@ -3528,7 +3528,7 @@ async fn announce_and_unannounce_toggles_discovery() { // Announcing again brings it back. publication.announce(MoqAnnounceRoute::default()).unwrap(); wait_live(&announced, true).await; - moq_clock::timeout(TIMEOUT, consumer.request("live".into(), None)) + kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("timed out requesting the reannounced broadcast") .expect("a reannounced broadcast resolves"); @@ -3557,7 +3557,7 @@ async fn dropping_a_publication_keeps_its_route() { broadcast.close().unwrap(); publication.broadcast().close().unwrap(); for path in ["live", "held"] { - let unroutable = moq_clock::timeout(TIMEOUT, consumer.request(path.into(), None)) + let unroutable = kio::clock::timeout(TIMEOUT, consumer.request(path.into(), None)) .await .expect("an unroutable request answers at once"); assert!(unroutable.is_err(), "a closed broadcast is unroutable"); @@ -3581,7 +3581,7 @@ async fn a_stale_publication_leaves_its_replacement_alone() { Err(MoqError::Closed) )); assert!(matches!(stale.unannounce(), Err(MoqError::Closed))); - moq_clock::timeout(TIMEOUT, consumer.request("live".into(), None)) + kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("timed out requesting the replacement") .expect("the replacement still resolves"); @@ -3596,7 +3596,7 @@ async fn finish_unpublishes() { let broadcast = create_announced(&origin, "live"); let announced = consumer.follow("live".into(), None).unwrap(); - moq_clock::timeout(TIMEOUT, announced.available()) + kio::clock::timeout(TIMEOUT, announced.available()) .await .expect("timed out waiting for the announcement") .unwrap(); @@ -3604,12 +3604,12 @@ async fn finish_unpublishes() { // A graceful finish detaches immediately; the path stops resolving. Removal is // asynchronous, so poll until it takes effect. broadcast.close().unwrap(); - let removed = moq_clock::timeout(TIMEOUT, async { + let removed = kio::clock::timeout(TIMEOUT, async { loop { if consumer.request("live".into(), None).await.is_err() { return; } - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + kio::clock::sleep(std::time::Duration::from_millis(10)).await; } }) .await; @@ -3638,7 +3638,7 @@ async fn local_publish_consume_audio() { let broadcast_consumer = await_announced(&consumer, &announcement.prefix).await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -3672,7 +3672,7 @@ async fn local_publish_consume_audio() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .expect("timed out waiting for frame") .unwrap() @@ -3704,7 +3704,7 @@ async fn video_publish_consume() { let broadcast_consumer = await_announced(&consumer, &announcement.prefix).await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out") .unwrap() @@ -3743,7 +3743,7 @@ async fn video_publish_consume() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .expect("timed out") .unwrap() @@ -3795,12 +3795,12 @@ async fn video_raw_publish_consume() { assert_eq!(video.demand().unwrap().name(), "camera"); let local_consumer = broadcast.consume().unwrap(); let demand_consumer = local_consumer.subscribe_track("camera".into(), None).await.unwrap(); - moq_clock::timeout(TIMEOUT, video.demand().unwrap().until_wanted()) + kio::clock::timeout(TIMEOUT, video.demand().unwrap().until_wanted()) .await .expect("timed out waiting for video demand") .unwrap(); drop(demand_consumer); - moq_clock::timeout(TIMEOUT, video.demand().unwrap().until_unwanted()) + kio::clock::timeout(TIMEOUT, video.demand().unwrap().until_unwanted()) .await .expect("timed out waiting for video demand to clear") .unwrap(); @@ -3824,7 +3824,7 @@ async fn video_raw_publish_consume() { let broadcast_consumer = await_announced(&consumer, &announcement.prefix).await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out") .unwrap() @@ -3868,7 +3868,7 @@ async fn video_raw_publish_consume() { .unwrap(); } - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .expect("timed out") .unwrap() @@ -3933,7 +3933,7 @@ async fn video_decode_frame_ownership() { let consumer = origin.consume(); let broadcast_consumer = await_announced(&consumer, "video-decode-frame").await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out") .unwrap() @@ -3979,7 +3979,7 @@ async fn video_decode_frame_ownership() { } let next = async |decoder: &MoqVideoConsumer| { - let read = moq_clock::timeout(TIMEOUT, decoder.next()) + let read = kio::clock::timeout(TIMEOUT, decoder.next()) .await .expect("timed out") .unwrap(); @@ -4087,7 +4087,7 @@ async fn video_decode_start() { let broadcast_consumer = await_announced(&consumer, "video-decode-start").await; // The newest group must be cached before `Latest` subscribes, or it would join the first. let raw = broadcast_consumer.subscribe_track("camera".into(), None).await.unwrap(); - while moq_clock::timeout(TIMEOUT, raw.recv_group()) + while kio::clock::timeout(TIMEOUT, raw.recv_group()) .await .expect("timed out") .unwrap() @@ -4096,7 +4096,7 @@ async fn video_decode_start() { == 0 {} let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out") .unwrap() @@ -4124,7 +4124,7 @@ async fn video_decode_start() { let timestamps = async |decoder: Arc| { let mut timestamps = Vec::new(); - while let Some(read) = moq_clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { + while let Some(read) = kio::clock::timeout(TIMEOUT, decoder.next()).await.unwrap().unwrap() { match read { MoqVideoRead::Frame { frame } => timestamps.push(frame.timestamp_us()), MoqVideoRead::End { .. } => break, @@ -4219,7 +4219,7 @@ async fn video_raw_publish_from_many_threads() { MoqMediaCatalogConsumer::subscribe(await_announced(&consumer, &announcement.prefix).await.as_ref()) .await .unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out") .unwrap() @@ -4334,7 +4334,7 @@ async fn multiple_frames_ordering() { let broadcast_consumer = await_announced(&consumer, &announcement.prefix).await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .unwrap() .unwrap() @@ -4366,7 +4366,7 @@ async fn multiple_frames_ordering() { } for (i, &expected_ts) in timestamps.iter().enumerate() { - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .unwrap_or_else(|_| panic!("timed out waiting for frame {i}")) .unwrap() @@ -4396,7 +4396,7 @@ async fn catalog_update_on_new_track() { let broadcast_consumer = await_announced(&consumer, &announcement.prefix).await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&broadcast_consumer).await.unwrap(); - let catalog1 = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog1 = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .unwrap() .unwrap() @@ -4411,7 +4411,7 @@ async fn catalog_update_on_new_track() { ) .unwrap(); - let catalog2 = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog2 = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .unwrap() .unwrap() @@ -4482,7 +4482,7 @@ async fn finish_serves_finished_tracks_until_close() { let late = await_announced(&consumer, "finish").await; let track = late.subscribe_track("audio".into(), None).await.unwrap(); - let frame = moq_clock::timeout(TIMEOUT, track.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, track.read_frame()) .await .expect("timed out reading the finished track") .unwrap() @@ -4522,7 +4522,7 @@ async fn children( /// Each reader ends with `Unroutable`, the cause of a publisher leaving. async fn assert_left(readers: [Arc; N]) { for reader in readers { - let read = moq_clock::timeout(TIMEOUT, reader.read_frame()).await; + let read = kio::clock::timeout(TIMEOUT, reader.read_frame()).await; let Err(err) = read.expect("the track carried on") else { panic!("the track ended without a cause"); }; @@ -4574,7 +4574,7 @@ async fn finishing_before_close_ends_tracks_cleanly() { drop(raw); broadcast.close().unwrap(); for reader in readers { - let read = moq_clock::timeout(TIMEOUT, reader.read_frame()).await; + let read = kio::clock::timeout(TIMEOUT, reader.read_frame()).await; assert!(read.expect("the track carried on").unwrap().is_none()); } } @@ -4686,7 +4686,7 @@ async fn a_failed_finish_ends_the_track_with_its_cause() { stream.write(vec![0, 0, 0, 1, 0x61, 0xe0, 0x12, 0x34]).unwrap(); assert!(matches!(stream.finish(), Err(MoqError::Codec { .. }))); - let read = moq_clock::timeout(TIMEOUT, reader.read_frame()).await; + let read = kio::clock::timeout(TIMEOUT, reader.read_frame()).await; let Err(err) = read.expect("the track carried on") else { panic!("the track ended without a cause"); }; @@ -4747,7 +4747,7 @@ async fn dynamic_broadcast_request() { tokio::spawn(async move { consumer.request("dynamic/broadcast".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("timed out waiting for requested broadcast") .unwrap(); @@ -4769,7 +4769,7 @@ async fn dynamic_broadcast_request() { .unwrap(); assert!(matches!(request.path(), Err(MoqError::Closed))); - let broadcast = moq_clock::timeout(TIMEOUT, requesting) + let broadcast = kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for requested broadcast result") .expect("request task panicked") @@ -4784,7 +4784,7 @@ async fn dynamic_broadcast_request() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, track_consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, track_consumer.read_frame()) .await .expect("timed out waiting for dynamic broadcast frame") .unwrap() @@ -4808,7 +4808,7 @@ async fn dynamic_serves_a_request_under_a_prefix() { let consumer = consumer.clone(); tokio::spawn(async move { consumer.request("live/cam".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("timed out waiting for the prefix request") .unwrap(); @@ -4816,14 +4816,14 @@ async fn dynamic_serves_a_request_under_a_prefix() { let prepared = request.prepare(moq_net::Epoch::mint().to_string()).unwrap(); let served = prepared.broadcast(); prepared.publish().unwrap(); - moq_clock::timeout(TIMEOUT, requesting) + kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for the request to resolve") .expect("request task panicked") .expect("the handler served the path"); dynamic.cancel(); - let err = moq_clock::timeout(TIMEOUT, consumer.request("live/other".into(), None)) + let err = kio::clock::timeout(TIMEOUT, consumer.request("live/other".into(), None)) .await .expect("timed out waiting for the retraction to reject the request") .err() @@ -4851,14 +4851,14 @@ async fn dynamic_keeps_the_origin_alive() { let consumer = consumer.clone(); tokio::spawn(async move { consumer.request("live".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the handler must still receive requests") .unwrap(); let prepared = request.prepare(moq_net::Epoch::mint().to_string()).unwrap(); let served = prepared.broadcast(); prepared.publish().unwrap(); - moq_clock::timeout(TIMEOUT, requesting) + kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for the request to resolve") .expect("request task panicked") @@ -4913,12 +4913,12 @@ async fn raw_track_next_group_is_repeatable() { }) .unwrap(); - let group = moq_clock::timeout(TIMEOUT, consumer.next_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) .await .expect("timed out waiting for a group") .unwrap() .expect("expected a group"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("timed out waiting for a frame") .unwrap() @@ -4952,7 +4952,7 @@ async fn raw_track_group_order_commits_on_first_read() { .unwrap(); // An arrival read commits the track to arrival order. - let group = moq_clock::timeout(TIMEOUT, consumer.recv_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.recv_group()) .await .expect("timed out waiting for a group") .unwrap() @@ -4968,7 +4968,7 @@ async fn raw_track_group_order_commits_on_first_read() { timestamp_us: Some(0), }) .unwrap(); - let group = moq_clock::timeout(TIMEOUT, consumer.recv_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.recv_group()) .await .expect("timed out waiting for a group") .unwrap() @@ -4982,7 +4982,7 @@ async fn raw_track_group_order_commits_on_first_read() { timestamp_us: Some(0), }) .unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for a datagram") .unwrap() @@ -5032,7 +5032,7 @@ where assert!(!group_read.is_finished(), "group read should still be pending"); let sequence = track.append_datagram(datagram_frame(b"beep")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for datagram behind a pending group read") .unwrap() @@ -5042,7 +5042,7 @@ where assert!(!group_read.is_finished(), "group read should stay pending"); track.write_frame(group_frame(b"group")).unwrap(); - moq_clock::timeout(TIMEOUT, group_read) + kio::clock::timeout(TIMEOUT, group_read) .await .expect("timed out waiting for the parked group") .expect("group read panicked") @@ -5065,14 +5065,14 @@ where assert!(!datagram_read.is_finished(), "datagram read should still be pending"); track.write_frame(group_frame(b"group")).unwrap(); - moq_clock::timeout(TIMEOUT, start_group(consumer.clone())) + kio::clock::timeout(TIMEOUT, start_group(consumer.clone())) .await .expect("timed out waiting for a group behind a pending datagram read") .unwrap(); assert!(!datagram_read.is_finished(), "datagram read should stay pending"); let sequence = track.append_datagram(datagram_frame(b"beep")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, datagram_read) + let datagram = kio::clock::timeout(TIMEOUT, datagram_read) .await .expect("timed out waiting for the parked datagram") .expect("datagram read panicked") @@ -5088,7 +5088,7 @@ async fn raw_track_insert_datagram_keeps_its_sequence() { let (_broadcast, track, consumer) = raw_track(); track.insert_datagram(7, datagram_frame(b"seven")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for the inserted datagram") .unwrap() @@ -5130,7 +5130,7 @@ async fn broadcast_consumer_closed_resolves_on_close() { assert!(!closed.is_finished(), "closed resolved while the broadcast is live"); broadcast.close().unwrap(); - moq_clock::timeout(TIMEOUT, closed) + kio::clock::timeout(TIMEOUT, closed) .await .expect("timed out waiting for closed") .expect("closed panicked") @@ -5206,7 +5206,7 @@ async fn raw_track_update_during_pending_group_still_reads_datagram() { .unwrap(); let sequence = track.append_datagram(datagram_frame(b"after-update")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for datagram after update") .unwrap() @@ -5215,7 +5215,7 @@ async fn raw_track_update_during_pending_group_still_reads_datagram() { assert_eq!(datagram.payload, b"after-update".to_vec()); track.write_frame(group_frame(b"group")).unwrap(); - moq_clock::timeout(TIMEOUT, group_read) + kio::clock::timeout(TIMEOUT, group_read) .await .expect("timed out waiting for the parked group") .expect("group read panicked") @@ -5239,7 +5239,7 @@ async fn raw_track_dropping_a_pending_group_read_does_not_cancel_datagrams() { } let sequence = track.append_datagram(datagram_frame(b"still-open")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for datagram after a cancelled group read") .unwrap() @@ -5247,12 +5247,12 @@ async fn raw_track_dropping_a_pending_group_read_does_not_cancel_datagrams() { assert_eq!(datagram.sequence, sequence); track.write_frame(group_frame(b"group")).unwrap(); - let group = moq_clock::timeout(TIMEOUT, consumer.next_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) .await .expect("timed out waiting for a group after the cancelled read") .unwrap() .expect("expected a group"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("timed out waiting for the group's frame") .unwrap() @@ -5276,7 +5276,7 @@ async fn raw_track_dropping_a_pending_datagram_read_does_not_cancel_groups() { } track.write_frame(group_frame(b"group")).unwrap(); - let group = moq_clock::timeout(TIMEOUT, consumer.next_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) .await .expect("timed out waiting for a group after a cancelled datagram read") .unwrap() @@ -5284,7 +5284,7 @@ async fn raw_track_dropping_a_pending_datagram_read_does_not_cancel_groups() { assert_eq!(group.sequence(), 0); let sequence = track.append_datagram(datagram_frame(b"later")).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, consumer.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) .await .expect("timed out waiting for a datagram after the cancelled read") .unwrap() @@ -5307,7 +5307,7 @@ async fn raw_track_handle_cancel_aborts_both_pending_lanes() { consumer.cancel(); - match moq_clock::timeout(TIMEOUT, group_read) + match kio::clock::timeout(TIMEOUT, group_read) .await .expect("timed out waiting for cancelled group read") .expect("group read panicked") @@ -5317,7 +5317,7 @@ async fn raw_track_handle_cancel_aborts_both_pending_lanes() { Ok(_) => panic!("handle cancel should fail the group read"), } - match moq_clock::timeout(TIMEOUT, datagram_read) + match kio::clock::timeout(TIMEOUT, datagram_read) .await .expect("timed out waiting for cancelled datagram read") .expect("datagram read panicked") @@ -5360,7 +5360,7 @@ async fn raw_read_frame_skips_empty_group_on_open_track() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, read) + let frame = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out waiting for the frame after an empty group") .expect("read task panicked") @@ -5389,7 +5389,7 @@ async fn raw_read_frame_skips_empty_then_populated_groups() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out skipping empty groups") .unwrap() @@ -5422,7 +5422,7 @@ async fn raw_read_frame_skips_a_group_reset_as_old() { .write_frame(moq_net::Timestamp::from_millis(1).unwrap(), b"later".as_slice()) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, read) + let frame = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out skipping the expired group") .expect("read task panicked") @@ -5448,7 +5448,7 @@ async fn raw_read_frame_cancelled_before_free_leaves_the_frame() { let next = consumer.read_frame(); drop(cancelled); - let frame = moq_clock::timeout(TIMEOUT, next) + let frame = kio::clock::timeout(TIMEOUT, next) .await .expect("the cancelled read took the frame") .unwrap() @@ -5477,7 +5477,7 @@ async fn raw_read_frame_keeps_group_across_cancelled_call() { group.finish().unwrap(); track.finish().unwrap(); - let frame = moq_clock::timeout(TIMEOUT, consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out reading the preserved group") .unwrap() @@ -5486,7 +5486,7 @@ async fn raw_read_frame_keeps_group_across_cancelled_call() { assert_eq!(frame.timestamp_us, Some(3_000)); assert!( - moq_clock::timeout(TIMEOUT, consumer.read_frame()) + kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out waiting for track EOF") .unwrap() @@ -5510,7 +5510,7 @@ async fn raw_read_frame_drops_aborted_pending_group() { wait_group_acquired(&first).await; first.abort(409).unwrap(); - let err = moq_clock::timeout(TIMEOUT, read) + let err = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out waiting for the aborted group") .expect("read task panicked"); @@ -5532,7 +5532,7 @@ async fn raw_read_frame_drops_aborted_pending_group() { timestamp_us: Some(4_000), }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out reading the group after an aborted pending group") .unwrap() @@ -5560,12 +5560,12 @@ async fn raw_read_frame_and_next_group_share_the_cursor() { .unwrap(); first.finish().unwrap(); - let group = moq_clock::timeout(TIMEOUT, consumer.next_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) .await .expect("timed out taking the pending group") .unwrap() .expect("next_group should return the group read_frame acquired"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("timed out reading the handed-off group") .unwrap() @@ -5578,7 +5578,7 @@ async fn raw_read_frame_and_next_group_share_the_cursor() { timestamp_us: Some(0), }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, consumer.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, consumer.read_frame()) .await .expect("timed out reading the next group") .unwrap() @@ -5594,7 +5594,7 @@ async fn raw_read_frame_terminal_cancel_releases_demand() { let consumer = track.consume(None).unwrap(); let demand = track.demand().unwrap(); - moq_clock::timeout(TIMEOUT, demand.until_wanted()) + kio::clock::timeout(TIMEOUT, demand.until_wanted()) .await .expect("timed out waiting for the subscriber") .unwrap(); @@ -5607,7 +5607,7 @@ async fn raw_read_frame_terminal_cancel_releases_demand() { wait_group_acquired(&open).await; consumer.cancel(); - let err = moq_clock::timeout(TIMEOUT, read) + let err = kio::clock::timeout(TIMEOUT, read) .await .expect("timed out waiting for the cancelled read") .expect("read task panicked"); @@ -5618,7 +5618,7 @@ async fn raw_read_frame_terminal_cancel_releases_demand() { Ok(None) => panic!("cancelled read returned EOF"), } - moq_clock::timeout(TIMEOUT, demand.until_unwanted()) + kio::clock::timeout(TIMEOUT, demand.until_unwanted()) .await .expect("timed out waiting for demand to drop") .unwrap(); @@ -5637,7 +5637,7 @@ async fn dynamic_broadcast_request_can_reject() { tokio::spawn(async move { consumer.request("missing".into(), None).await }) }; - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("timed out waiting for requested broadcast") .unwrap(); @@ -5646,7 +5646,7 @@ async fn dynamic_broadcast_request_can_reject() { request.reject(404).unwrap(); assert!(matches!(request.path(), Err(MoqError::Closed))); - let result = moq_clock::timeout(TIMEOUT, requesting) + let result = kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for rejected broadcast") .expect("request task panicked"); @@ -5662,7 +5662,7 @@ async fn cancelling_dynamic_broadcasts_unregisters_the_handler() { dynamic.cancel(); assert!(matches!(dynamic.requested_broadcast().await, Err(MoqError::Closed))); - let result = moq_clock::timeout(TIMEOUT, consumer.request("missing".into(), None)) + let result = kio::clock::timeout(TIMEOUT, consumer.request("missing".into(), None)) .await .expect("request stayed pending after the dynamic handler was cancelled"); let err = match result { @@ -5738,7 +5738,7 @@ async fn server_client_roundtrip() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -5769,12 +5769,12 @@ async fn server_client_roundtrip() { ..Default::default() }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -5798,7 +5798,7 @@ async fn server_client_roundtrip() { // Subscribe to the audio track and verify a frame round-trips. let bc = await_announced(&consumer, "hello").await; let catalog_consumer = MoqMediaCatalogConsumer::subscribe(&bc).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalog_consumer.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("timed out waiting for catalog") .unwrap() @@ -5825,7 +5825,7 @@ async fn server_client_roundtrip() { }) .unwrap(); - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(&media_consumer)) .await .expect("timed out waiting for frame") .unwrap() @@ -5846,7 +5846,7 @@ async fn server_client_roundtrip() { /// Subscribe to the first audio rendition in `broadcast`'s catalog. async fn subscribe_audio(broadcast: &MoqBroadcastConsumer) -> Arc { let catalogs = MoqMediaCatalogConsumer::subscribe(broadcast).await.unwrap(); - let catalog = moq_clock::timeout(TIMEOUT, catalogs.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalogs.next()) .await .expect("timed out waiting for the catalog") .unwrap() @@ -5876,7 +5876,7 @@ async fn roundtrip(media: &MoqMediaTrackProducer, track: &MoqMediaTrackConsumer, }) .unwrap(); loop { - let frame = moq_clock::timeout(TIMEOUT, next_encoded_frame(track)) + let frame = kio::clock::timeout(TIMEOUT, next_encoded_frame(track)) .await .expect("timed out waiting for a frame") .unwrap() @@ -5900,7 +5900,7 @@ async fn follow_follows_an_epochless_replacement() { ..Default::default() }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -5931,7 +5931,7 @@ async fn follow_follows_an_epochless_replacement() { ..Default::default() }) .unwrap(); - moq_clock::timeout(TIMEOUT, client.connect(url.clone())) + kio::clock::timeout(TIMEOUT, client.connect(url.clone())) .await .expect("connect timed out") .expect("connect failed") @@ -5939,7 +5939,7 @@ async fn follow_follows_an_epochless_replacement() { let first = connect().await; let followed = viewer.consume().follow("cam".into(), None).unwrap(); - let old = moq_clock::timeout(TIMEOUT, followed.available()) + let old = kio::clock::timeout(TIMEOUT, followed.available()) .await .expect("timed out waiting for the broadcast") .unwrap(); @@ -5947,7 +5947,7 @@ async fn follow_follows_an_epochless_replacement() { roundtrip(&media, &old_track, b"before", 1_000_000).await; let second = connect().await; - let fresh = moq_clock::timeout(TIMEOUT, followed.available()) + let fresh = kio::clock::timeout(TIMEOUT, followed.available()) .await .expect("the replacement was never handed out") .unwrap(); @@ -5976,7 +5976,7 @@ async fn follow_retries_a_dropped_wait() { let waiting = followed.clone(); let dropped = tokio::spawn(async move { waiting.available().await }); - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the wait never asked for the broadcast") .unwrap(); @@ -5985,7 +5985,7 @@ async fn follow_retries_a_dropped_wait() { let retry = tokio::spawn(async move { followed.available().await }); let served = request.prepare(moq_mint_epoch()).unwrap().publish().unwrap(); - moq_clock::timeout(TIMEOUT, retry) + kio::clock::timeout(TIMEOUT, retry) .await .expect("the retry waited for another instance") .unwrap() @@ -6006,19 +6006,19 @@ async fn follow_hands_out_a_takeover_once(dynamic_at: &str) { let waiting = followed.clone(); let first = tokio::spawn(async move { waiting.available().await }); // The wait is on the dynamic route's answer when the exact path takes over without an epoch. - let _unanswered = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let _unanswered = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the wait never asked for the broadcast") .unwrap(); let takeover = create_announced(&origin, "live"); - let _held = moq_clock::timeout(TIMEOUT, first) + let _held = kio::clock::timeout(TIMEOUT, first) .await .expect("the takeover never resolved") .unwrap() .unwrap(); let next = tokio::spawn(async move { followed.available().await }); - moq_clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; + kio::clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; assert!(!next.is_finished(), "the takeover was handed out twice"); next.abort(); takeover.close().unwrap(); @@ -6047,7 +6047,7 @@ async fn follow_hands_out_the_instance_again_after_an_end() { }; let publication = origin.create_broadcast("live".into()).unwrap(); publication.announce(route.clone()).unwrap(); - let first = moq_clock::timeout(TIMEOUT, followed.available()) + let first = kio::clock::timeout(TIMEOUT, followed.available()) .await .expect("timed out waiting for the broadcast") .unwrap(); @@ -6056,14 +6056,14 @@ async fn follow_hands_out_the_instance_again_after_an_end() { let dynamic = origin.inner().inner.requests("").unwrap(); publication.unannounce().unwrap(); let again = tokio::spawn(async move { followed.available().await }); - let request = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let request = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the instance never asked the route above the path") .unwrap(); let epoch = route.epoch.clone().unwrap().parse().unwrap(); let served = request.prepare(epoch).unwrap().publish().unwrap(); - let again = moq_clock::timeout(TIMEOUT, again) + let again = kio::clock::timeout(TIMEOUT, again) .await .expect("the instance was never handed out again") .unwrap() @@ -6092,7 +6092,7 @@ async fn an_epoch_pins_request_and_follow() { }) .unwrap(); - let pinned = moq_clock::timeout(TIMEOUT, consumer.request("live".into(), Some(epoch.clone()))) + let pinned = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), Some(epoch.clone()))) .await .expect("timed out requesting the pinned instance") .unwrap(); @@ -6100,7 +6100,7 @@ async fn an_epoch_pins_request_and_follow() { pinned.inner().info().epoch.as_ref().map(ToString::to_string), Some(epoch.clone()) ); - let err = moq_clock::timeout(TIMEOUT, consumer.request("live".into(), Some(moq_mint_epoch()))) + let err = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), Some(moq_mint_epoch()))) .await .expect("timed out requesting another instance") .err() @@ -6116,7 +6116,7 @@ async fn an_epoch_pins_request_and_follow() { )); let followed = consumer.follow("live".into(), Some(epoch.clone())).unwrap(); - moq_clock::timeout(TIMEOUT, followed.available()) + kio::clock::timeout(TIMEOUT, followed.available()) .await .expect("timed out following the pinned instance") .unwrap(); @@ -6129,7 +6129,7 @@ async fn an_epoch_pins_request_and_follow() { .unwrap(); // An unpinned request resolves the takeover and holds it, so a follower resolving it joins // that answer at once: one poll, which applies the takeover first, would hand it out. - let takeover = moq_clock::timeout(TIMEOUT, consumer.request("live".into(), None)) + let takeover = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("timed out requesting the takeover") .unwrap(); @@ -6159,21 +6159,21 @@ async fn follow_hands_out_a_gap_while_resolving_once() { let waiting = followed.clone(); let first = tokio::spawn(async move { waiting.available().await }); - let _unanswered = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let _unanswered = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the wait never asked for the broadcast") .unwrap(); dynamic.cancel(); - moq_clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; + kio::clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; let arrival = create_announced(&origin, "live"); - let _held = moq_clock::timeout(TIMEOUT, first) + let _held = kio::clock::timeout(TIMEOUT, first) .await .expect("the arrival never resolved") .unwrap() .unwrap(); let next = tokio::spawn(async move { followed.available().await }); - moq_clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; + kio::clock::sleep(moq_net::origin::Config::default().update_hold * 2).await; assert!(!next.is_finished(), "the arrival was handed out twice"); next.abort(); arrival.close().unwrap(); @@ -6189,20 +6189,20 @@ async fn follow_hands_out_a_dropped_takeover_again() { let waiting = followed.clone(); let first = tokio::spawn(async move { waiting.available().await }); - let _unanswered = moq_clock::timeout(TIMEOUT, dynamic.requested_broadcast()) + let _unanswered = kio::clock::timeout(TIMEOUT, dynamic.requested_broadcast()) .await .expect("the wait never asked for the broadcast") .unwrap(); let takeover = create_announced(&origin, "live"); drop( - moq_clock::timeout(TIMEOUT, first) + kio::clock::timeout(TIMEOUT, first) .await .expect("the takeover never resolved") .unwrap() .unwrap(), ); - moq_clock::timeout(TIMEOUT, followed.available()) + kio::clock::timeout(TIMEOUT, followed.available()) .await .expect("the dropped takeover was never handed out again") .unwrap(); @@ -6223,7 +6223,7 @@ async fn server_client_roundtrip_auto_origin() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -6246,7 +6246,7 @@ async fn server_client_roundtrip_auto_origin() { ..Default::default() }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); @@ -6254,7 +6254,7 @@ async fn server_client_roundtrip_auto_origin() { let publisher = cs.publish(); let consumer = cs.consume(); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -6278,7 +6278,7 @@ async fn server_client_roundtrip_auto_origin() { let local_broadcast = create_announced(&publisher, "local-only"); // Visibility is asynchronous, so wait for the announcement rather than requesting. let local_announced = consumer.follow("local-only".into(), None).unwrap(); - moq_clock::timeout(TIMEOUT, local_announced.available()) + kio::clock::timeout(TIMEOUT, local_announced.available()) .await .expect("timed out waiting for the loopback broadcast") .expect("an auto-origin session should discover its own announcement"); @@ -6453,7 +6453,7 @@ async fn client_keylog_writes_session_keys() { ..Default::default() }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -6468,11 +6468,11 @@ async fn client_keylog_writes_session_keys() { }); let client = keylog_client(server.cert_fingerprints().unwrap()).unwrap(); - let session = moq_clock::timeout(TIMEOUT, client.connect(format!("https://{addr}"))) + let session = kio::clock::timeout(TIMEOUT, client.connect(format!("https://{addr}"))) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -6499,7 +6499,7 @@ async fn client_connects_with_every_knob_set() { ..Default::default() }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -6543,11 +6543,11 @@ async fn client_connects_with_every_knob_set() { ..Default::default() }) .unwrap(); - let session = moq_clock::timeout(TIMEOUT, client.connect(url)) + let session = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -6573,7 +6573,7 @@ async fn server_cert_fingerprints_available_after_listen() { Err(crate::error::MoqError::Bind { .. }) )); - moq_clock::timeout(TIMEOUT, server.listen()) + kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -6594,7 +6594,7 @@ async fn server_cert_fingerprints_rejected_after_cancel() { }) .unwrap(); - moq_clock::timeout(TIMEOUT, server.listen()) + kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -6647,7 +6647,7 @@ async fn server_cancel_releases_the_bound_port() { .unwrap(); rebound.listen().await.expect("the port should rebind immediately"); - let accept = moq_clock::timeout(TIMEOUT, accept) + let accept = kio::clock::timeout(TIMEOUT, accept) .await .expect("accept task timed out") .expect("accept task panicked"); @@ -6722,18 +6722,18 @@ async fn server_accept_cancelled_before_free_leaves_the_session() { let connect = tokio::spawn(async move { client.connect(format!("https://{addr}")).await }); // The wake means the session is ready for the cancelled accept, wherever it now sits. - moq_clock::timeout(TIMEOUT, woken.0.notified()) + kio::clock::timeout(TIMEOUT, woken.0.notified()) .await .expect("the session never reached the cancelled accept"); drop(cancelled); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("the cancelled accept took the session") .expect("accept errored") .expect("accept returned None"); let server_session = request.accept(None, None).await.expect("accept the session"); - let _client_session = moq_clock::timeout(TIMEOUT, connect) + let _client_session = kio::clock::timeout(TIMEOUT, connect) .await .expect("connect timed out") .expect("connect task panicked") @@ -6785,12 +6785,12 @@ async fn request_double_respond_returns_already_responded() { ..Default::default() }) .unwrap(); - let _session = moq_clock::timeout(TIMEOUT, client.connect(url)) + let _session = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("accept timed out") .expect("accept task panicked"); @@ -6837,12 +6837,12 @@ async fn request_per_session_publish_override() { ..Default::default() }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("accept timed out") .expect("accept task panicked"); @@ -6896,7 +6896,7 @@ async fn session_state_names_a_failing_first_dial() { assert!(state.version.is_none()); drop(client); for _ in 0..2 { - state = moq_clock::timeout(TIMEOUT, session.state_changed(state.revision)) + state = kio::clock::timeout(TIMEOUT, session.state_changed(state.revision)) .await .unwrap() .unwrap(); @@ -6914,7 +6914,7 @@ async fn session_state_names_a_failing_first_dial() { server.listen().await.unwrap(); let request = server.accept().await.unwrap().unwrap(); let accepted = request.accept(None, None).await.unwrap(); - let connected = moq_clock::timeout(TIMEOUT, wait_phase(&session, MoqConnectionPhase::Connected)) + let connected = kio::clock::timeout(TIMEOUT, wait_phase(&session, MoqConnectionPhase::Connected)) .await .unwrap() .unwrap(); @@ -6932,7 +6932,7 @@ async fn session_state_names_a_failing_first_dial() { .is_pending() ); accepted.cancel(0); - let terminal = moq_clock::timeout(TIMEOUT, ending).await.unwrap().unwrap(); + let terminal = kio::clock::timeout(TIMEOUT, ending).await.unwrap().unwrap(); assert_eq!(terminal.phase, MoqConnectionPhase::Closed); assert!(terminal.version.is_none()); assert!(terminal.failure.is_some()); @@ -6960,7 +6960,7 @@ async fn client_reconnects_and_resumes_announcements() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7004,13 +7004,13 @@ async fn client_reconnects_and_resumes_announcements() { }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); // Observe the first successful connect through the same state as its initial dial. - let status = moq_clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) + let status = kio::clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("status timed out") .expect("status errored"); @@ -7022,13 +7022,13 @@ async fn client_reconnects_and_resumes_announcements() { // Kill the transport under the client, simulating a relay restart. // Nothing accepts the redial until the gate opens. - let first = moq_clock::timeout(TIMEOUT, first_rx) + let first = kio::clock::timeout(TIMEOUT, first_rx) .await .expect("first session timed out") .expect("accept task gone"); first.cancel(0); - let status = moq_clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Disconnected)) + let status = kio::clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Disconnected)) .await .expect("disconnect status timed out") .expect("disconnect status errored"); @@ -7040,7 +7040,7 @@ async fn client_reconnects_and_resumes_announcements() { // Open the gate; the redial completes. regate_tx.send(()).expect("accept task gone"); - let status = moq_clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) + let status = kio::clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("reconnect status timed out") .expect("reconnect status errored"); @@ -7051,7 +7051,7 @@ async fn client_reconnects_and_resumes_announcements() { assert_eq!(status.connects, 2, "phase and count come from one observation"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -7081,7 +7081,7 @@ async fn one_shot_client_close_surfaces_through_closed() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7105,18 +7105,18 @@ async fn one_shot_client_close_surfaces_through_closed() { }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); server_session.cancel(7); - moq_clock::timeout(TIMEOUT, cs.closed()) + kio::clock::timeout(TIMEOUT, cs.closed()) .await .expect("closed timed out") .expect_err("a severed one-shot session must surface as an error"); @@ -7137,7 +7137,7 @@ async fn rejected_session_surfaces_through_closed() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7164,11 +7164,11 @@ async fn rejected_session_surfaces_through_closed() { // Either the dial fails outright, or the optimistic connect resolves and the // rejection lands as the session's terminal close. Both must surface within // the timeout. - if let Ok(cs) = moq_clock::timeout(TIMEOUT, client.connect(url)) + if let Ok(cs) = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect neither resolved nor failed") { - moq_clock::timeout(TIMEOUT, cs.closed()) + kio::clock::timeout(TIMEOUT, cs.closed()) .await .expect("closed timed out") .expect_err("a rejected session must surface as an error"); @@ -7188,7 +7188,7 @@ async fn cancel_before_connect_fails_fast() { }) .unwrap(); client.cancel(); - let result = moq_clock::timeout( + let result = kio::clock::timeout( Duration::from_secs(5), client.connect("https://localhost:0/test".into()), ) @@ -7215,7 +7215,7 @@ async fn cancelled_state_wait_does_not_swallow_the_next_transition() { }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7241,17 +7241,17 @@ async fn cancelled_state_wait_does_not_swallow_the_next_transition() { }) .unwrap(); - let cs = moq_clock::timeout(TIMEOUT, client.connect(url)) + let cs = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); - let status = moq_clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) + let status = kio::clock::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("status timed out") .expect("status errored"); @@ -7261,7 +7261,7 @@ async fn cancelled_state_wait_does_not_swallow_the_next_transition() { // the abandoned call has to actually reach its await for this to prove // anything, and a spawn that never got there would pass either way. assert!( - moq_clock::timeout(Duration::from_millis(200), cs.state_changed(status.revision)) + kio::clock::timeout(Duration::from_millis(200), cs.state_changed(status.revision)) .await .is_err(), "no transition was pending, so this must be the caller giving up", @@ -7270,7 +7270,7 @@ async fn cancelled_state_wait_does_not_swallow_the_next_transition() { // The transition the abandoned call would have eaten. server_session.cancel(0); - let status = moq_clock::timeout(TIMEOUT, cs.state_changed(status.revision)) + let status = kio::clock::timeout(TIMEOUT, cs.state_changed(status.revision)) .await .expect("the cancelled waiter swallowed the disconnect") .expect("status errored"); @@ -7334,17 +7334,17 @@ async fn video_encoder_follows_a_shrinking_grant() { .unwrap(); assert_eq!(reservation.rate(), Some(1_000_000)); - let deadline = moq_clock::Instant::now() + TIMEOUT; + let deadline = kio::clock::Instant::now() + TIMEOUT; loop { if video.applied_bitrate() == 1_000_000 { break; } assert!( - moq_clock::Instant::now() < deadline, + kio::clock::Instant::now() < deadline, "encoder did not follow the shrinking grant, last applied {}", video.applied_bitrate() ); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } video.finish().unwrap(); @@ -7398,7 +7398,7 @@ async fn dropping_a_video_producer_stops_the_rate_follower() { ) .unwrap(); - moq_clock::timeout(TIMEOUT, tokio::task::spawn_blocking(move || drop(video))) + kio::clock::timeout(TIMEOUT, tokio::task::spawn_blocking(move || drop(video))) .await .expect("rate follower did not stop") .expect("drop panicked"); @@ -7457,7 +7457,7 @@ async fn one_shot_peers() -> (Arc, Arc, Arc) ..Default::default() }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7480,11 +7480,11 @@ async fn one_shot_peers() -> (Arc, Arc, Arc) ..Default::default() }) .unwrap(); - let client_session = moq_clock::timeout(TIMEOUT, client.connect(url)) + let client_session = kio::clock::timeout(TIMEOUT, client.connect(url)) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("server accept timed out") .expect("server accept task panicked"); @@ -7510,7 +7510,7 @@ async fn session_protocol_codes_cross_the_ffi() { ] { let (client, server_session, server) = one_shot_peers().await; server_session.cancel(code); - let err = match moq_clock::timeout(TIMEOUT, client.closed()) + let err = match kio::clock::timeout(TIMEOUT, client.closed()) .await .expect("closed timed out") { @@ -7543,7 +7543,7 @@ async fn cancelling_a_session_aborts_its_first_dial() { let revision = session.state().revision; client.cancel(); session.cancel(0); - moq_clock::timeout(TIMEOUT, session.closed()).await.unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, session.closed()).await.unwrap().unwrap(); let state = session.state_changed(revision).await.unwrap(); assert_eq!(state.phase, MoqConnectionPhase::Closed); assert_eq!(state.connects, 0); @@ -7578,7 +7578,7 @@ async fn server_cert_fingerprints_busy_during_accept_and_cancelled_after() { server.cancel(); assert!(matches!(server.cert_fingerprints(), Err(MoqError::Cancelled))); - let accept_err = moq_clock::timeout(TIMEOUT, accept) + let accept_err = kio::clock::timeout(TIMEOUT, accept) .await .expect("accept task timed out") .expect("accept task panicked"); @@ -7616,7 +7616,7 @@ async fn request_accept_inherits_overrides_and_captures_origins() { .unwrap(); let connecting = client.clone(); let connect = tokio::spawn(async move { connecting.connect(format!("https://{addr}")).await }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .unwrap() .unwrap() @@ -7632,7 +7632,7 @@ async fn request_accept_inherits_overrides_and_captures_origins() { }) .await }); - moq_clock::timeout(TIMEOUT, held_rx).await.unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, held_rx).await.unwrap().unwrap(); let accepting = request.clone(); let accept = spawn_parked(async move { accepting.accept(publish, consume).await }).await; drop(fresh); @@ -7643,9 +7643,9 @@ async fn request_accept_inherits_overrides_and_captures_origins() { ); } release_tx.send(()).unwrap(); - moq_clock::timeout(TIMEOUT, hold).await.unwrap().unwrap().unwrap(); - let session = moq_clock::timeout(TIMEOUT, accept).await.unwrap().unwrap().unwrap(); - let client_session = moq_clock::timeout(TIMEOUT, connect).await.unwrap().unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, hold).await.unwrap().unwrap().unwrap(); + let session = kio::clock::timeout(TIMEOUT, accept).await.unwrap().unwrap().unwrap(); + let client_session = kio::clock::timeout(TIMEOUT, connect).await.unwrap().unwrap().unwrap(); assert_eq!(session.publish().inner().hop(), expected_publish); // Incoming broadcasts reach the selected consume origin, independently @@ -7695,7 +7695,7 @@ async fn request_accept_cancelled_after_cancel() { let connecting = client.clone(); let connect = tokio::spawn(async move { connecting.connect(format!("https://{addr}")).await }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timed out") .expect("accept errored") @@ -7712,7 +7712,7 @@ async fn request_accept_cancelled_after_cancel() { }) .await }); - moq_clock::timeout(TIMEOUT, held_rx).await.unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, held_rx).await.unwrap().unwrap(); let origin = MoqOriginProducer::new(MoqOriginConfig::default()); let captured = Arc::downgrade(&origin); let accepting = request.clone(); @@ -7723,9 +7723,9 @@ async fn request_accept_cancelled_after_cancel() { assert!(matches!(request.accept(None, None).await, Err(MoqError::Cancelled))); assert!(matches!(request.reject(403).await, Err(MoqError::Cancelled))); - let result = moq_clock::timeout(TIMEOUT, accept).await.unwrap().unwrap(); + let result = kio::clock::timeout(TIMEOUT, accept).await.unwrap().unwrap(); assert!(matches!(result, Err(MoqError::Cancelled))); - let result = moq_clock::timeout(TIMEOUT, hold).await.unwrap().unwrap(); + let result = kio::clock::timeout(TIMEOUT, hold).await.unwrap().unwrap(); assert!(matches!(result, Err(MoqError::Cancelled))); assert!( captured.upgrade().is_none(), @@ -7733,7 +7733,7 @@ async fn request_accept_cancelled_after_cancel() { ); client.cancel(); - let _ = moq_clock::timeout(TIMEOUT, connect).await; + let _ = kio::clock::timeout(TIMEOUT, connect).await; server.cancel(); } @@ -7769,7 +7769,7 @@ async fn shutdown_cancels_and_drops_cleanly() { ..Default::default() }) .unwrap(); - let addr = moq_clock::timeout(TIMEOUT, server.listen()) + let addr = kio::clock::timeout(TIMEOUT, server.listen()) .await .expect("listen timed out") .expect("listen failed"); @@ -7787,11 +7787,11 @@ async fn shutdown_cancels_and_drops_cleanly() { ..Default::default() }) .unwrap(); - let session = moq_clock::timeout(TIMEOUT, client.connect(format!("https://{addr}"))) + let session = kio::clock::timeout(TIMEOUT, client.connect(format!("https://{addr}"))) .await .expect("connect timed out") .expect("connect failed"); - let server_session = moq_clock::timeout(TIMEOUT, accept) + let server_session = kio::clock::timeout(TIMEOUT, accept) .await .expect("accept timed out") .expect("accept task panicked"); @@ -7801,7 +7801,7 @@ async fn shutdown_cancels_and_drops_cleanly() { let track = broadcast.publish_track("data".into(), None).unwrap(); let consumer = client_origin.consume(); let bc = await_announced(&consumer, "hello").await; - let subscriber = moq_clock::timeout(TIMEOUT, bc.subscribe_track("data".into(), None)) + let subscriber = kio::clock::timeout(TIMEOUT, bc.subscribe_track("data".into(), None)) .await .expect("subscribe timed out") .expect("subscribe failed"); @@ -7815,7 +7815,7 @@ async fn shutdown_cancels_and_drops_cleanly() { // Idempotent: the thread is already gone. crate::moq_ffi_shutdown(); - let parked = moq_clock::timeout(TIMEOUT, parked) + let parked = kio::clock::timeout(TIMEOUT, parked) .await .expect("the parked read never resolved") .expect("the read task panicked"); @@ -7855,7 +7855,7 @@ fn shutdown_waits_for_an_in_place_poll() { entered.send(()).unwrap(); // Holds this poll open while shutdown starts on another thread. release_rx.recv().unwrap(); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; // Even if the sleep is already due, only the shutdown may finish this call. std::future::pending::>().await }); @@ -7980,7 +7980,7 @@ async fn memory_shutdown_pair() -> (Arc, Arc) { let (session, driver) = moq_net::Client::new() .with_origin(a.inner.clone()) .with_versions(version.into()) - .connect(moq_clock::Instant::now(), client) + .connect(kio::clock::Instant::now(), client) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -7991,7 +7991,7 @@ async fn memory_shutdown_pair() -> (Arc, Arc) { .with_publisher(&b.inner) .with_subscriber(b.inner.clone()) .with_versions(version.into()) - .accept(moq_clock::Instant::now(), server) + .accept(kio::clock::Instant::now(), server) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -8100,7 +8100,7 @@ async fn shutdown_ready(track: &MoqTrackProducer, reader: &MoqTrackConsumer) { }) .unwrap(); group.finish().unwrap(); - let ready = moq_clock::timeout(TIMEOUT, reader.read_frame()) + let ready = kio::clock::timeout(TIMEOUT, reader.read_frame()) .await .expect("subscription ready") .expect("priming read") @@ -8111,7 +8111,7 @@ async fn shutdown_ready(track: &MoqTrackProducer, reader: &MoqTrackConsumer) { #[tokio::test] async fn shutdown_delivers_the_finished_track() { for client_publishes in [false, true] { - let (server, client, accepted) = moq_clock::timeout(TIMEOUT, shutdown_pair()).await.expect("pair"); + let (server, client, accepted) = kio::clock::timeout(TIMEOUT, shutdown_pair()).await.expect("pair"); let (publisher, subscriber) = if client_publishes { (&client, &accepted) } else { @@ -8120,7 +8120,7 @@ async fn shutdown_delivers_the_finished_track() { let broadcast = create_announced(&publisher.publish(), "tail"); let track = broadcast.publish_track("data".into(), Some(timed_info())).unwrap(); let remote = await_announced(&subscriber.consume(), "tail").await; - let reader = moq_clock::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) + let reader = kio::clock::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) .await .expect("subscribe") .unwrap(); @@ -8131,7 +8131,7 @@ async fn shutdown_delivers_the_finished_track() { Ok::<_, MoqError>((frame, end)) }); let closing = publisher.clone(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, crate::ffi::detached(async move { let group = track.append_group()?; @@ -8149,7 +8149,7 @@ async fn shutdown_delivers_the_finished_track() { .await .expect("shutdown") .unwrap(); - let (frame, end) = moq_clock::timeout(TIMEOUT, receiving) + let (frame, end) = kio::clock::timeout(TIMEOUT, receiving) .await .expect("read") .unwrap() @@ -8165,7 +8165,7 @@ async fn shutdown_delivers_the_finished_track() { #[tokio::test] async fn shutdown_times_out_on_an_unfinished_track() { for client_publishes in [false, true] { - let (server, client, accepted) = moq_clock::timeout(TIMEOUT, shutdown_pair()).await.expect("pair"); + let (server, client, accepted) = kio::clock::timeout(TIMEOUT, shutdown_pair()).await.expect("pair"); let (publisher, subscriber) = if client_publishes { (&client, &accepted) } else { @@ -8174,13 +8174,13 @@ async fn shutdown_times_out_on_an_unfinished_track() { let broadcast = create_announced(&publisher.publish(), "live"); let track = broadcast.publish_track("data".into(), Some(timed_info())).unwrap(); let remote = await_announced(&subscriber.consume(), "live").await; - let reader = moq_clock::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) + let reader = kio::clock::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) .await .expect("subscribe") .unwrap(); shutdown_ready(&track, &reader).await; let receiving = tokio::spawn(async move { reader.read_frame().await }); - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); let mut closed = Box::pin(publisher.closed()); assert!( closed @@ -8189,7 +8189,7 @@ async fn shutdown_times_out_on_an_unfinished_track() { .is_pending() ); publisher.shutdown(); - let err = moq_clock::timeout(TIMEOUT, closed) + let err = kio::clock::timeout(TIMEOUT, closed) .await .expect("shutdown") .expect_err("unfinished track must time out"); @@ -8203,7 +8203,7 @@ async fn shutdown_times_out_on_an_unfinished_track() { assert!( matches!(err, MoqError::Protocol { details } if details.kind == crate::error::MoqProtocolKind::DeliveryTimeout) ); - let _ = moq_clock::timeout(TIMEOUT, receiving).await.unwrap().unwrap(); + let _ = kio::clock::timeout(TIMEOUT, receiving).await.unwrap().unwrap(); client.cancel(0); accepted.cancel(0); server.cancel(); @@ -8249,7 +8249,7 @@ async fn ascending_subscription_reads_a_cached_backlog_oldest_first() { let consumer = track.consume(Some(subscription)).unwrap(); let mut sequences = Vec::new(); for _ in 0..3 { - let group = moq_clock::timeout(TIMEOUT, consumer.recv_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.recv_group()) .await .expect("timed out waiting for a cached group") .unwrap() @@ -8264,7 +8264,7 @@ async fn await_grant(session: &MoqSession, want: crate::auth::MoqGrant) { // A fresh consumer starts from the grant as it is now, so `changed` follows from there. let grants = session.grants(); let mut current = grants.grant(); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while current.as_ref() != Some(&want) { current = grants.changed().await.expect("grant watch ended"); } @@ -8285,7 +8285,7 @@ fn grant(publish: &[&str], subscribe: &[&str]) -> crate::auth::MoqGrant { /// The peer's answer to the tokens set last. async fn answered(session: &MoqSession) -> Result<(), MoqError> { let tokens = session.tokens().expect("a client session has tokens"); - moq_clock::timeout(TIMEOUT, tokens.answered()) + kio::clock::timeout(TIMEOUT, tokens.answered()) .await .expect("the tokens were never answered") } @@ -8301,7 +8301,7 @@ async fn auth_reads_the_peer_grant() { } async fn auth_reads_the_peer_grant_on(version: &str) { - let (server, client, accepted) = moq_clock::timeout(TIMEOUT, session_pair(version)).await.expect("pair"); + let (server, client, accepted) = kio::clock::timeout(TIMEOUT, session_pair(version)).await.expect("pair"); // Each side's origins span the root, so its peer grants it everything. await_grant(&client, grant(&["**"], &["**"])).await; @@ -8330,7 +8330,7 @@ async fn auth_reads_the_peer_grant_on(version: &str) { /// answer is that the session cannot carry it. #[tokio::test] async fn auth_refuses_a_token_nothing_carries() { - let (server, client, accepted) = moq_clock::timeout(TIMEOUT, session_pair("moq-lite-06")) + let (server, client, accepted) = kio::clock::timeout(TIMEOUT, session_pair("moq-lite-06")) .await .expect("pair"); client.tokens().unwrap().set(vec!["extra".into()]).unwrap(); @@ -8382,7 +8382,7 @@ async fn auth_tokens_join_and_leave_the_union() { ..Default::default() }) .unwrap(); - let session = moq_clock::timeout(TIMEOUT, client.connect(format!("tcp://{addr}"))) + let session = kio::clock::timeout(TIMEOUT, client.connect(format!("tcp://{addr}"))) .await .expect("connect timed out") .unwrap(); @@ -8397,7 +8397,7 @@ async fn auth_tokens_join_and_leave_the_union() { answered(&session).await.expect("the extra token was refused"); // Patterns are kept sorted. await_grant(&session, grant(&["extra/**", "setup/**"], &[])).await; - let seen = moq_clock::timeout(TIMEOUT, watcher.changed()) + let seen = kio::clock::timeout(TIMEOUT, watcher.changed()) .await .expect("the second consumer sees the change") .unwrap(); @@ -8414,7 +8414,7 @@ async fn auth_tokens_join_and_leave_the_union() { await_grant(&session, grant(&["setup/**"], &[])).await; session.cancel(0); - moq_clock::timeout(TIMEOUT, serving) + kio::clock::timeout(TIMEOUT, serving) .await .expect("server ended") .unwrap(); @@ -8448,7 +8448,7 @@ async fn time_anchors_start_at_the_containing_group() { let consumer = track.consume(Some(since(1_500))).unwrap(); let mut sequences = Vec::new(); for _ in 0..2 { - let group = moq_clock::timeout(TIMEOUT, consumer.recv_group()) + let group = kio::clock::timeout(TIMEOUT, consumer.recv_group()) .await .expect("timed out waiting for a cached group") .unwrap() diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index bec33e8074d..68d123df536 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -1565,7 +1565,7 @@ mod follow_tests { }); assert_eq!(moved, Ok(None)); - let retried = moq_clock::timeout(Duration::from_secs(60), follower.next()) + let retried = kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .expect("the dropped target is asked for again"); assert_eq!(retried.unwrap(), Target::Enabled(Rate::from_mbps(2))); @@ -1580,7 +1580,7 @@ mod follow_tests { /// Retune at every target until the follower goes a minute without one. async fn quiet(follower: &mut Follower, ceiling: Rate, mut set: impl FnMut(Rate) -> Result<(), moq_video::Error>) { - while let Ok(bitrate) = moq_clock::timeout(Duration::from_secs(60), follower.next()).await { + while let Ok(bitrate) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await { rate(follower, ceiling, bitrate.unwrap(), &mut set).unwrap(); } } diff --git a/rs/moq-gst/Cargo.toml b/rs/moq-gst/Cargo.toml index b1cd30a6565..7200b4a28a2 100644 --- a/rs/moq-gst/Cargo.toml +++ b/rs/moq-gst/Cargo.toml @@ -23,7 +23,7 @@ bytes = { workspace = true } gst = { package = "gstreamer", version = "0.25" } gst-audio = { package = "gstreamer-audio", version = "0.25" } hang = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-mux = { workspace = true } moq-net = { workspace = true } moq-tokio = { workspace = true, default-features = true } diff --git a/rs/moq-gst/src/sink/imp.rs b/rs/moq-gst/src/sink/imp.rs index d63a06c7c30..a6983b5b8be 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -696,7 +696,7 @@ impl MoqSink { }); let sample = super::wall::Sample { running: reference_running_time, - wall: moq_clock::wall(), + wall: kio::clock::wall(), }; let map = buffer.map_readable().map_err(|_| { gst::error!(CAT, "failed to map buffer on pad {}", pad.name()); @@ -1307,7 +1307,7 @@ mod tests { Duration::ZERO, super::super::wall::Sample { running: Some(gst::ClockTime::ZERO), - wall: moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600), + wall: kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600), }, ) .unwrap(); @@ -2281,11 +2281,11 @@ mod tests { while bus.pop().is_some() {} let linger = Duration::from_secs(30); - let start = moq_clock::now(); + let start = kio::clock::now(); let finished = moq_mux::Linger::new([broadcast], track, linger); let lingering = tokio::spawn(linger_task(finished, sink.downgrade(), session)); - moq_clock::sleep(linger - Duration::from_secs(1)).await; + kio::clock::sleep(linger - Duration::from_secs(1)).await; let mut late = consumer.track("video").unwrap().subscribe(None).await.unwrap(); assert!( late.recv_group().await.unwrap().is_some(), @@ -2294,7 +2294,7 @@ mod tests { assert!(bus.pop_filtered(&[gst::MessageType::Eos]).is_none(), "the EOS waits"); lingering.await.unwrap(); - assert_eq!(moq_clock::now() - start, linger); + assert_eq!(kio::clock::now() - start, linger); assert!(consumer.is_closed()); assert!( bus.pop_filtered(&[gst::MessageType::Eos]).is_some(), diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 014f4ebe620..10930fbbd54 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -1508,7 +1508,7 @@ mod tests { let vp8 = gst::Caps::builder("video/x-vp8").build(); pad.observe_caps(&broadcast, &catalog, producer_options(&vp8, Some("camera"))); let drained = async { while records.recv_group().await.unwrap().is_some() {} }; - let ended = moq_clock::timeout(Duration::from_secs(1), drained).await; + let ended = kio::clock::timeout(Duration::from_secs(1), drained).await; assert!(ended.is_ok(), "the old track's records end"); } @@ -2075,7 +2075,7 @@ mod tests { subscriber, moq_mux::catalog::hang::Container::Loc(moq_mux::container::Kind::Data), ); - let frame = moq_clock::timeout(std::time::Duration::from_secs(1), media.read()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(1), media.read()) .await .expect("LOC media read timed out") .unwrap(); diff --git a/rs/moq-gst/src/sink/wall.rs b/rs/moq-gst/src/sink/wall.rs index 4d3b9fea990..918454d1023 100644 --- a/rs/moq-gst/src/sink/wall.rs +++ b/rs/moq-gst/src/sink/wall.rs @@ -12,7 +12,7 @@ use anyhow::{Context, Result}; #[derive(Clone, Copy)] pub(super) struct Sample { pub running: Option, - pub wall: moq_clock::Wall, + pub wall: kio::clock::Wall, } /// Places running-time zero on the wall clock once per run, holding the first catalog until then. @@ -54,7 +54,7 @@ impl Wall { } } -fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result { +fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result { for meta in buffer.iter_meta::() { let Some(reference) = meta.reference().structure(0) else { continue; @@ -68,7 +68,7 @@ fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result continue, }; - return moq_clock::Wall::UNIX_EPOCH + return kio::clock::Wall::UNIX_EPOCH .checked_add(unix) .and_then(|wall| wall.checked_sub(pts)) .context("reference timestamp cannot place running-time zero"); @@ -93,7 +93,7 @@ mod tests { #[test] fn delayed_buffers_and_unknown_domains_use_the_pipeline_clock() { gst::init().unwrap(); - let now = moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_620); + let now = kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_620); let mut buffer = gst::Buffer::new(); gst::ReferenceTimestampMeta::add( buffer.get_mut().unwrap(), @@ -145,11 +145,11 @@ mod tests { Duration::from_secs(3), Sample { running: None, - wall: moq_clock::Wall::UNIX_EPOCH + wall: kio::clock::Wall::UNIX_EPOCH } ) .unwrap(), - moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600) + kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600) ); } } diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index f6c8f07037a..a98b48eeed5 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -2330,7 +2330,7 @@ mod session_tests { /// its subscriber stays parked. Bounded so a session that never subscribes fails the test. fn await_request(dynamic: &mut moq_net::broadcast::Requests) -> moq_net::track::Request { super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), dynamic.requested_track()).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), dynamic.requested_track()).await }) .expect("no track was ever requested") .expect("broadcast closed") } @@ -2394,7 +2394,7 @@ mod session_tests { .unwrap() .broadcast = Some(moq_net::path::Relative::new("./right").unwrap()); let next = super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), replacement.requested_track()).await }); + .block_on(async { kio::clock::timeout(Duration::from_secs(10), replacement.requested_track()).await }); stopping.send(true).unwrap(); super::RUNTIME.block_on(following).unwrap().unwrap(); assert_eq!( @@ -2524,7 +2524,7 @@ mod session_tests { moq_net::Result::Ok(()) }; super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), unwanted).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), unwanted).await }) .expect("the cancelled reader never dropped its subscription") .expect("the pending request is still open"); @@ -2652,7 +2652,7 @@ mod session_tests { // No shutdown is sent: the run has to end on the media draining alone. super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), session).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), session).await }) .expect("the run outlived the renditions it was serving") .unwrap() .unwrap(); @@ -2903,7 +2903,7 @@ mod session_tests { audio.finish().unwrap(); catalog.finish().unwrap(); super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), session).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), session).await }) .expect("the run outlived its broadcast") .unwrap() .unwrap(); @@ -3158,7 +3158,7 @@ mod session_tests { broadcast: moq_net::broadcast::Producer, catalog: moq_mux::catalog::Producer, video: moq_mux::container::Producer, - start: moq_clock::Instant, + start: kio::clock::Instant, } impl Publisher { @@ -3199,7 +3199,7 @@ mod session_tests { broadcast, catalog, video, - start: moq_clock::now(), + start: kio::clock::now(), } } @@ -3359,7 +3359,7 @@ mod session_tests { cancel, }; super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), super::RUNTIME.spawn(reader.run())).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), super::RUNTIME.spawn(reader.run())).await }) .expect("a push on a pad added after the flush blocked") .unwrap(); } @@ -3540,7 +3540,7 @@ mod session_tests { panic!("the origin closed"); }; super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), next).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), next).await }) .expect("the announcement never arrived"); } @@ -3549,7 +3549,7 @@ mod session_tests { let mut demand = publisher.video.demand(); let changed = async { while demand.wanted_changed().await.expect("the track closed").is_some() != wanted {} }; super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), changed).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), changed).await }) .expect("the demand never changed"); } @@ -3658,7 +3658,7 @@ mod session_tests { let pool = origin.requests("").unwrap(); let session = follow(&element, &origin); let pending = super::RUNTIME.block_on(async { - moq_clock::timeout(Duration::from_secs(10), pool.requested_broadcast()) + kio::clock::timeout(Duration::from_secs(10), pool.requested_broadcast()) .await .unwrap() .unwrap() @@ -3839,7 +3839,7 @@ mod session_tests { room.catalog.finish().unwrap(); super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), run).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), run).await }) .expect("the sibling's follower outlived the catalog") .unwrap() .unwrap(); @@ -3876,7 +3876,7 @@ mod session_tests { moq_net::Result::Ok(()) }; super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), unwanted).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), unwanted).await }) .expect("the sibling outlived its catalog's broadcast") .expect("the sibling track closed"); stop(session); @@ -3927,7 +3927,7 @@ mod session_tests { ); while track.read().await.unwrap().is_some() {} }; - moq_clock::timeout(Duration::from_secs(10), finished) + kio::clock::timeout(Duration::from_secs(10), finished) .await .expect("the track never finished"); }); @@ -4595,7 +4595,7 @@ mod session_tests { let (_shutdown, session) = follow(&element, &origin); let err = super::RUNTIME - .block_on(async { moq_clock::timeout(Duration::from_secs(10), session).await }) + .block_on(async { kio::clock::timeout(Duration::from_secs(10), session).await }) .expect("the refusal held the session") .unwrap() .expect_err("the refusal did not fail the session"); @@ -4793,7 +4793,7 @@ mod session_tests { )) ); assert!(video.send_event(gst::event::Segment::new(&gst::FormattedSegment::::new()))); - let start = moq_clock::now(); + let start = kio::clock::now(); let frame = || { let mut frame = gst::Buffer::from_slice(crate::sink::h264_keyframe_au()); frame @@ -4822,7 +4822,7 @@ mod session_tests { let mut dropped = relay.dropped.subscribe(); super::RUNTIME .block_on(async { - moq_clock::timeout(Duration::from_secs(30), dropped.wait_for(|dropped| *dropped >= 4)).await + kio::clock::timeout(Duration::from_secs(30), dropped.wait_for(|dropped| *dropped >= 4)).await }) .expect("the elements stopped redialing") .unwrap(); diff --git a/rs/moq-hls/Cargo.toml b/rs/moq-hls/Cargo.toml index 143ee06b55a..a79f84cd46c 100644 --- a/rs/moq-hls/Cargo.toml +++ b/rs/moq-hls/Cargo.toml @@ -22,9 +22,8 @@ axum = { workspace = true, optional = true } bytes = { workspace = true } hang = { workspace = true } humantime = { workspace = true } -kio = { workspace = true } +kio = { workspace = true, features = ["runtime"] } m3u8-rs = "6" -moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } percent-encoding = { workspace = true } diff --git a/rs/moq-hls/src/export/archive_tests.rs b/rs/moq-hls/src/export/archive_tests.rs index 770e6ddd92e..5146e888736 100644 --- a/rs/moq-hls/src/export/archive_tests.rs +++ b/rs/moq-hls/src/export/archive_tests.rs @@ -164,7 +164,7 @@ impl Recording { // Subscribed before anything is published, so every group is recorded live. for source in sources.values() { while source.media.subscription().is_none() || source.track.subscription().is_none() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } } Self { @@ -207,7 +207,7 @@ impl Recording { /// Wait until the recorder subscribed to every track and stored what was published. async fn stored(&self) { - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; } /// End the source cleanly, then wait for the recorder to mark the archive complete. @@ -285,7 +285,7 @@ impl Replay { broadcast.announce(Default::default()).unwrap(); let broadcaster = Broadcaster::new(crate::resolved(&origin, "rec").await, Config::default()); - moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()) .await .expect("a rendition becomes playable or fails"); @@ -305,7 +305,7 @@ impl Replay { async fn playlist(&self, kind: Kind, name: &str) -> String { let rendition = self.rendition(kind, name); - moq_clock::timeout(Duration::from_secs(5), rendition.playlist(None)) + kio::clock::timeout(Duration::from_secs(5), rendition.playlist(None)) .await .expect("playlist renders") .unwrap() @@ -319,7 +319,7 @@ impl Replay { if ready(&playlist) { return playlist; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } panic!("{name} playlist never became ready"); } diff --git a/rs/moq-hls/src/export/mod.rs b/rs/moq-hls/src/export/mod.rs index b0f38f57d3f..7b7f4ceafa0 100644 --- a/rs/moq-hls/src/export/mod.rs +++ b/rs/moq-hls/src/export/mod.rs @@ -333,7 +333,7 @@ impl Broadcaster { &mpd::Manifest { instance: self.instance.clone(), availability_start, - publish: moq_clock::wall(), + publish: kio::clock::wall(), window: self.renditions.window(), finished, video, @@ -404,7 +404,7 @@ async fn watch_catalog(source: moq_mux::Source, renditions: renditions::Producer let wait = delay.mul_f64(0.5 + rand::rng().random::() / 2.0); delay = (delay * 2).min(CATALOG_RETRY_MAX); tokio::select! { - _ = moq_clock::sleep(wait) => {} + _ = kio::clock::sleep(wait) => {} _ = kio::wait(|waiter| broadcast.poll_closed(waiter)) => { renditions.close(); return; @@ -542,7 +542,7 @@ mod tests { /// The next rendition event, or `None` if the set is quiet. async fn next_event(cursor: &mut renditions::Consumer) -> Option { - moq_clock::timeout(Duration::from_millis(50), cursor.next()) + kio::clock::timeout(Duration::from_millis(50), cursor.next()) .await .ok() .and_then(Result::unwrap) @@ -923,7 +923,7 @@ mod tests { let mut media = video(&catalog, &broadcast, "video0", video_config()); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let rendition = moq_clock::timeout(Duration::from_secs(5), async { + let rendition = kio::clock::timeout(Duration::from_secs(5), async { loop { if let Some(rendition) = broadcaster.rendition(Kind::Video, "video0") { break rendition; @@ -943,7 +943,7 @@ mod tests { "master advertised a media playlist that would return 404" ); assert!( - moq_clock::timeout(Duration::from_millis(10), broadcaster.ready()) + kio::clock::timeout(Duration::from_millis(10), broadcaster.ready()) .await .is_err(), "broadcaster became ready before it had a playable rendition" @@ -952,7 +952,7 @@ mod tests { media.write(vp8_frame(0, true)).unwrap(); media.write(vp8_frame(2_000_000, true)).unwrap(); media.write(vp8_frame(4_000_000, true)).unwrap(); - moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()) .await .expect("broadcaster becomes ready with a complete segment"); assert!(broadcaster.master_playlist(None).contains("video/video0/media.m3u8")); @@ -1006,7 +1006,7 @@ mod tests { } } let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - moq_clock::timeout(Duration::from_secs(5), broadcaster.advertised()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.advertised()) .await .expect("video0 is advertised"); @@ -1039,7 +1039,7 @@ mod tests { } let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - moq_clock::timeout(Duration::from_secs(5), broadcaster.advertised()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.advertised()) .await .expect("the rendition is advertised"); let rendition = broadcaster.rendition(Kind::Video, "video0").unwrap(); @@ -1057,7 +1057,7 @@ mod tests { let mut disabled = video_config(); disabled.enabled = false; media.set(disabled).unwrap(); - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { while listed() { tokio::task::yield_now().await; } @@ -1073,10 +1073,10 @@ mod tests { let broadcaster = broadcaster.clone(); async move { broadcaster.advertised().await } }); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; assert!(!waiting.is_finished(), "nothing enabled is advertised"); media.set(video_config()).unwrap(); - moq_clock::timeout(Duration::from_secs(5), waiting) + kio::clock::timeout(Duration::from_secs(5), waiting) .await .expect("a re-enable wakes the master's long-poll") .unwrap(); @@ -1124,7 +1124,7 @@ mod tests { while !rendition.snapshot().finished { tokio::task::yield_now().await; } - let init = moq_clock::timeout(Duration::from_secs(1), rendition.latest_init()) + let init = kio::clock::timeout(Duration::from_secs(1), rendition.latest_init()) .await .expect("init must not wait for the unfinished trailing group") .unwrap() @@ -1152,7 +1152,7 @@ mod tests { until_listed(&rendition, 1).await; let mut blocked = std::pin::pin!(rendition.latest_init()); assert!( - moq_clock::timeout(Duration::from_millis(10), blocked.as_mut()) + kio::clock::timeout(Duration::from_millis(10), blocked.as_mut()) .await .is_err(), "the bootstrap reads the open group" @@ -1178,7 +1178,7 @@ mod tests { .unwrap() .expect("completed segment"); assert!(!segment.is_empty()); - moq_clock::timeout(Duration::from_secs(1), rendition.latest_init()) + kio::clock::timeout(Duration::from_secs(1), rendition.latest_init()) .await .expect("init must not wait behind the blocked bootstrap") .unwrap() @@ -1252,9 +1252,9 @@ mod tests { /// Wait until `rendition` lists at least `count` segments. async fn until_listed(rendition: &Rendition, count: usize) { - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { while rendition.snapshot().segments.len() < count { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -1263,13 +1263,13 @@ mod tests { /// Render the manifest until it lists `video1`. async fn listed_in_manifest(broadcaster: &Broadcaster) -> String { - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { loop { let manifest = broadcaster.manifest(None).unwrap().unwrap(); if manifest.contains("id=\"video/video1\"") { return manifest; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -1310,7 +1310,7 @@ mod tests { let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); broadcaster.advertised().await; until_listed(&broadcaster.rendition(Kind::Video, "video0").unwrap(), 3).await; - moq_clock::timeout(Duration::from_millis(1), broadcaster.video_init()) + kio::clock::timeout(Duration::from_millis(1), broadcaster.video_init()) .await .expect("one video init is enough to render"); let manifest = broadcaster.manifest(None).unwrap().expect("video0 renders"); @@ -1318,7 +1318,7 @@ mod tests { assert!(!manifest.contains("id=\"video/video1\""), "{manifest}"); // The background build is parked on the open group, and every render stays current. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let manifest = broadcaster.manifest(None).unwrap().expect("video0 renders"); assert!(!manifest.contains("id=\"video/video1\""), "{manifest}"); @@ -1371,12 +1371,12 @@ mod tests { assert!(broadcaster.manifest(None).unwrap().is_none()); open.finish().unwrap(); - let manifest = moq_clock::timeout(Duration::from_secs(5), async { + let manifest = kio::clock::timeout(Duration::from_secs(5), async { loop { if let Some(manifest) = broadcaster.manifest(None).unwrap() { return manifest; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -1400,7 +1400,7 @@ mod tests { until_listed(&broadcaster.rendition(Kind::Video, "video0").unwrap(), 3).await; let stuck = broadcaster.rendition(Kind::Video, "video1").unwrap(); stuck.start_init(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(stuck.init_pending(), "the build is parked on the open group"); let weak = Arc::downgrade(&stuck); drop(stuck); @@ -1448,11 +1448,11 @@ mod tests { until_listed(&broadcaster.rendition(Kind::Video, "video0").unwrap(), 3).await; let stuck = broadcaster.rendition(Kind::Video, "video1").unwrap(); stuck.start_init(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(stuck.init_pending(), "the build is parked on the open group"); broadcaster.set_generation(Some("run2")).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(!stuck.init_pending(), "the old run's build still holds the init lock"); drop(open); } @@ -1476,9 +1476,9 @@ mod tests { records.finish().unwrap(); } catalog.finish().unwrap(); - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { while !rendition.snapshot().finished { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -1509,20 +1509,20 @@ mod tests { write_keyframe(&mut open, 1); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; until_listed(&broadcaster.rendition(Kind::Video, "video0").unwrap(), 2).await; catalog.finish().unwrap(); settle().await; let mut waiting = std::pin::pin!(broadcaster.video_init()); assert!( - moq_clock::timeout(Duration::from_secs(1), waiting.as_mut()) + kio::clock::timeout(Duration::from_secs(1), waiting.as_mut()) .await .is_err(), "resolved without a listable video" ); open.finish().unwrap(); - moq_clock::timeout(Duration::from_secs(1), waiting) + kio::clock::timeout(Duration::from_secs(1), waiting) .await .expect("video0 is listable once its init is built"); } @@ -1536,11 +1536,11 @@ mod tests { let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); while broadcaster.rendition(Kind::Video, "video0").is_none() { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } let mut waiting = std::pin::pin!(broadcaster.video_init()); assert!( - moq_clock::timeout(Duration::from_secs(1), waiting.as_mut()) + kio::clock::timeout(Duration::from_secs(1), waiting.as_mut()) .await .is_err(), "resolved without a listable video" @@ -1552,7 +1552,7 @@ mod tests { group.finish().unwrap(); records[0].push(&gop(sequence)).unwrap(); } - moq_clock::timeout(Duration::from_secs(1), waiting) + kio::clock::timeout(Duration::from_secs(1), waiting) .await .expect("the wait builds video0's init once its records arrive"); } @@ -1576,7 +1576,7 @@ mod tests { until_listed(&broadcaster.rendition(Kind::Video, "video0").unwrap(), 3).await; for _ in 0..3 { assert!(broadcaster.manifest(None).unwrap().is_some()); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } let disabled = broadcaster.rendition(Kind::Video, "video1").unwrap(); assert!(!disabled.snapshot().segments.is_empty()); @@ -1602,7 +1602,7 @@ mod tests { let (_catalog, mut media) = publish_vp8(&mut broadcast.broadcast().clone(), video_config()); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let old = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); let old_playlist = old .media_playlist(None) @@ -1619,20 +1619,20 @@ mod tests { media.write(vp8_frame(micros, true)).unwrap(); } - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); let new = loop { let current = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); if !Arc::ptr_eq(¤t, &old) { break current; } assert!( - moq_clock::now() < deadline, + kio::clock::now() < deadline, "the reconfigure never rebuilt the rendition" ); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; }; let new_init = new.latest_init().await.unwrap().expect("init segment"); - let _ = moq_clock::timeout(Duration::from_secs(5), new.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), new.playable()).await; let new_playlist = new.media_playlist(None).unwrap().expect("playable"); let new_hash = init_hash(&new_playlist); assert_ne!(new_hash, old_hash, "different init bytes get a different URL"); @@ -1651,7 +1651,7 @@ mod tests { let (_catalog, mut media) = publish_vp8(&mut broadcast.broadcast().clone(), video_config()); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); let tag = rendition.tag().to_string(); let unversioned = rendition.media_playlist(None).unwrap().expect("playable"); @@ -1686,7 +1686,7 @@ mod tests { ); media.write(vp8_frame(6_000_000, true)).unwrap(); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let restarted = rendition.media_playlist(None).unwrap().expect("the new run lists"); assert!(restarted.contains(&format!("\nseg/run-2.{tag}.2.m4s\n")), "{restarted}"); assert!(!restarted.contains("run-1")); @@ -1713,9 +1713,9 @@ mod tests { } let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let old = rendition.latest_init().await.unwrap().expect("init segment"); broadcaster.set_generation(Some("run-1")).unwrap(); broadcaster.set_generation(Some("run-2")).unwrap(); @@ -1731,7 +1731,7 @@ mod tests { }) .unwrap(); } - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let new = rendition.latest_init().await.unwrap().expect("init segment"); assert_ne!(new, old, "the new run's init is built from its own media"); let playlist = rendition.media_playlist(None).unwrap().expect("playable"); @@ -1748,11 +1748,11 @@ mod tests { let (catalog, media) = publish_vp8(&mut broadcast.broadcast().clone(), inline_vp8()); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster .rendition(Kind::Video, "video0") .expect("rendition discovered from the catalog"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let master = broadcaster.master_playlist(None); assert!(master.contains("video/video0/media.m3u8"), "master lists the rendition"); @@ -1810,9 +1810,9 @@ mod tests { let (catalog, media) = publish_vp8(&mut broadcast.broadcast().clone(), video_config()); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; // Segment 0 holds a keyframe at 0s and a delta at 1s; segment 1 starts at 2s. let segment = rendition.listed_segment(0).await.unwrap().expect("segment 0"); @@ -1848,9 +1848,9 @@ mod tests { media.write(vp8_frame(4_000_000, true)).unwrap(); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let segment = rendition.listed_segment(0).await.unwrap().expect("segment 0"); let timescale = rendition.muxer().unwrap().timescale().as_u64(); @@ -1887,11 +1887,11 @@ mod tests { audio_write(4_000_000); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let video_rendition = broadcaster.rendition(Kind::Video, "video0").expect("video discovered"); let audio_rendition = broadcaster.rendition(Kind::Audio, "audio0").expect("audio discovered"); - let _ = moq_clock::timeout(Duration::from_secs(5), video_rendition.playable()).await; - let _ = moq_clock::timeout(Duration::from_secs(5), audio_rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), video_rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), audio_rendition.playable()).await; let manifest = broadcaster .manifest(None) @@ -1958,7 +1958,7 @@ mod tests { settle().await; // PTS zero at exactly the moq epoch, so every timestamp maps to a fixed string. - let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); + let wall = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); let config = catalog_config() .with_clock(moq_mux::Clock::at(moq_net::time::Instant::now(), wall).expect("a representable wall")); let catalog = moq_mux::catalog::Producer::new(&mut broadcast.broadcast().clone(), config).unwrap(); @@ -1968,9 +1968,9 @@ mod tests { media.write(frame(4_000_000, true)).unwrap(); // live edge let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("video discovered"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let snapshot = rendition.snapshot(); assert_eq!(snapshot.segments[0].program_date_time, Some(wall)); @@ -2029,9 +2029,9 @@ mod tests { } let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Video, "video0").expect("video discovered"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; assert_eq!(rendition.snapshot().segments[0].program_date_time, None); let playlist = rendition.media_playlist(None).unwrap().expect("playlist renders"); @@ -2082,7 +2082,7 @@ mod tests { import.decode(&fragments).unwrap(); let anchored = catalog.snapshot().clock.expect("the catalog advertises a clock"); - moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()) .await .expect("a rendition becomes playable"); let video = catalog @@ -2093,7 +2093,7 @@ mod tests { .next() .expect("a video rendition"); let rendition = broadcaster.rendition(Kind::Video, &video).expect("video discovered"); - let playlist = moq_clock::timeout(Duration::from_secs(5), rendition.playlist(None)) + let playlist = kio::clock::timeout(Duration::from_secs(5), rendition.playlist(None)) .await .expect("a listed segment") .unwrap() @@ -2220,7 +2220,7 @@ mod tests { settle().await; } let broadcaster = broadcaster.unwrap_or_else(|| Broadcaster::new(source, Config::default())); - moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()) + kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()) .await .unwrap(); for (kind, name) in [ @@ -2234,7 +2234,7 @@ mod tests { ), ] { let rendition = broadcaster.rendition(kind, &name).unwrap(); - moq_clock::timeout(Duration::from_secs(5), rendition.playlist(None)) + kio::clock::timeout(Duration::from_secs(5), rendition.playlist(None)) .await .unwrap() .unwrap() @@ -2247,7 +2247,7 @@ mod tests { assert!(media.is_some(), "listed segment {} must have media", row.segment); } let mut cursor = rendition.segments(); - let segment = moq_clock::timeout(Duration::from_secs(5), cursor.next()) + let segment = kio::clock::timeout(Duration::from_secs(5), cursor.next()) .await .expect("a live recording produces a media segment") .unwrap(); @@ -2269,21 +2269,21 @@ mod tests { media.write(frame(2_000_000, true)).unwrap(); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.playable()).await; // A clean finish stops the open segment and ends the records. media.finish().unwrap(); catalog.finish().unwrap(); - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); let manifest = loop { let manifest = broadcaster.manifest(None).unwrap().expect("manifest renders"); if manifest.contains(" type=\"static\"") { break manifest; } - assert!(moq_clock::now() < deadline, "manifest never turned static"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "manifest never turned static"); + kio::clock::sleep(Duration::from_millis(50)).await; }; // The trailing segment holds one frame that nothing bounds, so it lasts no time. HLS // lists it, but a SegmentTimeline entry at the presentation end would never be @@ -2317,9 +2317,9 @@ mod tests { } let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster.rendition(Kind::Audio, "audio0").expect("audio discovered"); - let _ = moq_clock::timeout(Duration::from_secs(5), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), rendition.playable()).await; let playlist = rendition.snapshot(); assert_eq!(numbers(&playlist), [0, 1, 2]); @@ -2362,11 +2362,11 @@ mod tests { audio_write(4_000_000); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let video_rendition = broadcaster.rendition(Kind::Video, "video0").expect("video discovered"); let audio_rendition = broadcaster.rendition(Kind::Audio, "audio0").expect("audio discovered"); - let _ = moq_clock::timeout(Duration::from_secs(5), video_rendition.playable()).await; - let _ = moq_clock::timeout(Duration::from_secs(5), audio_rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), video_rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), audio_rendition.playable()).await; // Both playlists list the same segment numbers over the same spans. let video_playlist = video_rendition.snapshot(); @@ -2411,7 +2411,7 @@ mod tests { media.write(frame(3_000_000, false)).unwrap(); let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); - let _ = moq_clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; + let _ = kio::clock::timeout(Duration::from_secs(5), broadcaster.ready()).await; let rendition = broadcaster .rendition(Kind::Video, "video0") .expect("rendition discovered"); @@ -2424,7 +2424,7 @@ mod tests { catalog.finish().unwrap(); let mut listed = Vec::new(); - while let Some(segment) = moq_clock::timeout(Duration::from_secs(5), segments.next()) + while let Some(segment) = kio::clock::timeout(Duration::from_secs(5), segments.next()) .await .expect("the cursor drains without parking") .unwrap() @@ -2671,7 +2671,7 @@ mod tests { settle().await; let (_renditions, rendition) = export(&upstream, &video_config()); - let _ = moq_clock::timeout(Duration::from_secs(1), rendition.playable()).await; + let _ = kio::clock::timeout(Duration::from_secs(1), rendition.playable()).await; let served = rendition.listed_segment(0).await.unwrap(); if let Some(served) = &served { assert!( @@ -2689,7 +2689,7 @@ mod tests { // that happens to be unreadable. let fresh = crate::resolved(&origin, "live").await; let (_renditions, rendition) = export(&fresh, &video_config()); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the new publisher's records arrive"); let served = rendition @@ -2748,7 +2748,7 @@ mod tests { config.broadcast = Some(moq_net::path::Relative::new("media").unwrap()); let (_renditions, rendition) = export(&upstream, &config); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); @@ -2775,7 +2775,7 @@ mod tests { // Control: an export started after the takeover does serve the new publisher's media. let fresh = crate::resolved(&origin, "live").await; let (_renditions, rendition) = export(&fresh, &config); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the fresh rendition"); let served = rendition @@ -2804,12 +2804,12 @@ mod tests { } async fn until_finished(rendition: &Rendition) { - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); loop { if rendition.snapshot().finished { return; } - assert!(moq_clock::now() < deadline, "the playlist did not end"); + assert!(kio::clock::now() < deadline, "the playlist did not end"); tokio::task::yield_now().await; } } @@ -2877,7 +2877,7 @@ mod tests { settle().await; let (_renditions, rendition) = export(&test.upstream, &test.config); old_media.announce(sibling_route(10)).unwrap(); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); let served = rendition @@ -2905,7 +2905,7 @@ mod tests { // A publisher serving the path afterwards, with records written for it, is never bound. let (new_media, new_track) = test.media(NEW, 3, 6_000_000); new_media.announce(sibling_route(11)).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let snapshot = rendition.snapshot(); assert_eq!(snapshot.segments.len(), before, "nothing of the replacement is listed"); assert!(snapshot.finished); @@ -2926,14 +2926,14 @@ mod tests { let (media, _track) = test.media(KEYFRAME, 0, 0); settle().await; let (renditions, rendition) = export(&test.upstream, &test.config); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); // The sibling is unannounced, so the segment waits for its media broadcast. let mut segment = std::pin::pin!(rendition.listed_segment(0)); assert!( - moq_clock::timeout(Duration::from_millis(10), segment.as_mut()) + kio::clock::timeout(Duration::from_millis(10), segment.as_mut()) .await .is_err() ); @@ -2963,7 +2963,7 @@ mod tests { settle().await; let (_renditions, rendition) = export(&test.upstream, &test.config); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); let served = rendition @@ -2988,7 +2988,7 @@ mod tests { settle().await; let (_renditions, rendition) = export(&test.upstream, &test.config); old_media.announce(sibling_route(10)).unwrap(); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); assert!(rendition.listed_segment(0).await.unwrap().is_some()); @@ -3000,7 +3000,7 @@ mod tests { let (new_media, new_track) = test.media(NEW, 3, 6_000_000); new_media.announce(sibling_route(11)).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let snapshot = rendition.snapshot(); assert_eq!(snapshot.segments.len(), before, "only the old rows remain listed"); assert!(snapshot.finished, "the playlist ended with its sibling"); @@ -3026,13 +3026,13 @@ mod tests { settle().await; let (_renditions, rendition) = export(&test.upstream, &test.config); media.announce(sibling_route(10)).unwrap(); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the records reach the rendition"); let mut cursor = rendition.segments(); loop { - match moq_clock::timeout(Duration::from_secs(1), cursor.next()).await { + match kio::clock::timeout(Duration::from_secs(1), cursor.next()).await { Ok(Ok(Some(_))) => continue, Err(_) => break, other => panic!( @@ -3044,7 +3044,7 @@ mod tests { // Only the sibling broadcast goes: its records stay quiet. drop(media); - let end = moq_clock::timeout(Duration::from_secs(5), cursor.next()) + let end = kio::clock::timeout(Duration::from_secs(5), cursor.next()) .await .expect("the cursor wakes when its sibling ends") .unwrap(); @@ -3063,7 +3063,7 @@ mod tests { let (media, _track) = test.media(OLD, 0, 0); settle().await; let (_renditions, rendition) = export(&test.upstream, &test.config); - moq_clock::timeout(Duration::from_secs(5), rendition.playable()) + kio::clock::timeout(Duration::from_secs(5), rendition.playable()) .await .expect("the catalog's rows are listed before the sibling resolves"); @@ -3093,7 +3093,7 @@ mod tests { // The catalog drops the rendition: its cursor must run dry rather than park. renditions.sync(&upstream, &moq_mux::catalog::hang::Catalog::default()); - let ended = moq_clock::timeout(Duration::from_secs(5), segments.next()) + let ended = kio::clock::timeout(Duration::from_secs(5), segments.next()) .await .expect("a removed rendition's cursor ends instead of parking") .unwrap(); @@ -3118,7 +3118,7 @@ mod tests { let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); let mut renditions = broadcaster.renditions(); - let added = moq_clock::timeout(Duration::from_secs(5), renditions.next()) + let added = kio::clock::timeout(Duration::from_secs(5), renditions.next()) .await .expect("a rendition is discovered"); let Ok(Some(renditions::Event::Added(_rendition))) = added else { @@ -3128,7 +3128,7 @@ mod tests { // The cursor and the handed-out rendition both outlive the broadcaster. drop(broadcaster); - let next = moq_clock::timeout(Duration::from_secs(5), renditions.next()) + let next = kio::clock::timeout(Duration::from_secs(5), renditions.next()) .await .expect("the cursor resolves after the broadcaster drops"); assert!( @@ -3137,7 +3137,7 @@ mod tests { ); // ...and the cursor then reaches a terminal state rather than parking. - let ended = moq_clock::timeout(Duration::from_secs(5), renditions.next()) + let ended = kio::clock::timeout(Duration::from_secs(5), renditions.next()) .await .expect("the cursor terminates after the broadcaster drops"); assert!(matches!(ended, Err(crate::Error::IncompleteRecording))); @@ -3164,7 +3164,7 @@ mod tests { let broadcaster = Broadcaster::new(crate::resolved(&origin, "live").await, Config::default()); let mut renditions = broadcaster.renditions(); - let rendition = match moq_clock::timeout(Duration::from_secs(5), renditions.next()) + let rendition = match kio::clock::timeout(Duration::from_secs(5), renditions.next()) .await .expect("a rendition is discovered") .unwrap() @@ -3178,7 +3178,7 @@ mod tests { let mut segments = rendition.segments(); assert!(segments.init().await.unwrap().is_some(), "init is buildable"); - let first = moq_clock::timeout(Duration::from_secs(5), segments.next()) + let first = kio::clock::timeout(Duration::from_secs(5), segments.next()) .await .expect("first segment finalizes") .unwrap() @@ -3198,7 +3198,7 @@ mod tests { drop((catalog, media)); broadcast.close(); - let end = moq_clock::timeout(Duration::from_secs(5), segments.next()) + let end = kio::clock::timeout(Duration::from_secs(5), segments.next()) .await .expect("segment cursor resolves after the source is lost"); assert!( @@ -3208,7 +3208,7 @@ mod tests { ); // The renditions cursor also fails when the source closes abruptly. - let ended = moq_clock::timeout(Duration::from_secs(5), renditions.next()) + let ended = kio::clock::timeout(Duration::from_secs(5), renditions.next()) .await .expect("renditions cursor resolves"); assert!(ended.is_err(), "an abrupt broadcast close fails the renditions cursor"); @@ -3332,7 +3332,7 @@ mod tests { if snapshot.segments.last().is_some_and(|s| s.segment >= last) { return snapshot; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } panic!("{name} never listed segment {last}"); } @@ -3344,7 +3344,7 @@ mod tests { if snapshot.finished { return snapshot; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } panic!("{name} never ended"); } @@ -3359,7 +3359,7 @@ mod tests { async fn drain(&self, name: &str) -> (Vec, crate::Result<()>) { let mut segments = self.rendition(name).segments(); let mut drained = Vec::new(); - let end = moq_clock::timeout(Duration::from_secs(5), async { + let end = kio::clock::timeout(Duration::from_secs(5), async { loop { match segments.next().await { Ok(Some(segment)) => drained.push(segment.segment), @@ -3400,7 +3400,7 @@ mod tests { assert!(matches!(err, crate::Error::RecordsFailed { .. }), "{err}"); return err; } - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } panic!("{} never failed", rendition.name); } @@ -3520,7 +3520,7 @@ mod tests { let broken = broadcaster.rendition(Kind::Video, "video1").unwrap(); for rendition in [&healthy, &broken] { while rendition.snapshot().segments.len() < 3 { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } } let before = broadcaster.manifest(None).unwrap().expect("both renditions are listed"); @@ -3548,11 +3548,11 @@ mod tests { let (track, video1) = test.publish("video1"); let rendition = test.rendition("video1"); let pending = tokio::spawn(async move { rendition.playlist(None).await }); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(!pending.is_finished(), "nothing is listed yet"); cut(track, video1); - let answer = moq_clock::timeout(Duration::from_secs(5), pending).await; + let answer = kio::clock::timeout(Duration::from_secs(5), pending).await; let err = answer.expect("the failure wakes the request").unwrap().unwrap_err(); assert!(matches!(err, crate::Error::RecordsFailed { .. }), "{err}"); } @@ -3578,7 +3578,7 @@ mod tests { let test = Records::new(); // A handler keeps the unpublished records' requests waiting rather than refused. let _handler = test.broadcast.requests(); - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; assert!(!test.rendition("video0").snapshot().finished); test.broadcast.close(); diff --git a/rs/moq-hls/src/export/mpd.rs b/rs/moq-hls/src/export/mpd.rs index 6b5cb9c4a8d..d82235c1796 100644 --- a/rs/moq-hls/src/export/mpd.rs +++ b/rs/moq-hls/src/export/mpd.rs @@ -14,7 +14,7 @@ //! `Representation` id keeps the raw name. The resources are shared byte-for-byte with the //! HLS routes; only the time-addressed segment alias `seg/t.m4s` is DASH's own. -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::BTreeMap; use std::fmt::Write; use std::sync::Arc; diff --git a/rs/moq-hls/src/export/playlist.rs b/rs/moq-hls/src/export/playlist.rs index fd656d4c5dd..1495586b051 100644 --- a/rs/moq-hls/src/export/playlist.rs +++ b/rs/moq-hls/src/export/playlist.rs @@ -6,7 +6,7 @@ //! (`////media.m3u8`), so they resolve against the rendition //! directory. -use moq_clock::Wall; +use kio::clock::Wall; use std::fmt::Write; use std::sync::Arc; use std::time::Duration; diff --git a/rs/moq-hls/src/export/rendition.rs b/rs/moq-hls/src/export/rendition.rs index f873c8d9cc7..f87107e9c80 100644 --- a/rs/moq-hls/src/export/rendition.rs +++ b/rs/moq-hls/src/export/rendition.rs @@ -1,6 +1,6 @@ //! One rendition: playlists from its own HLS records, and segments fetched on demand. -use moq_clock::Wall; +use kio::clock::Wall; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock, Weak}; use std::task::Poll; @@ -1722,10 +1722,10 @@ mod tests { let rendition = rendition.clone(); async move { kio::wait(|waiter| rendition.poll_refused(waiter)).await } }); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; assert!(!refused.is_finished(), "the records have not failed yet"); rendition.fail(crate::Error::Moq(moq_net::Error::Transport("connection lost".into()))); - moq_clock::timeout(Duration::from_secs(1), refused) + kio::clock::timeout(Duration::from_secs(1), refused) .await .expect("the failure wakes the wait") .unwrap(); diff --git a/rs/moq-hls/src/export/renditions.rs b/rs/moq-hls/src/export/renditions.rs index d276fc51800..ac7b094dae1 100644 --- a/rs/moq-hls/src/export/renditions.rs +++ b/rs/moq-hls/src/export/renditions.rs @@ -9,7 +9,7 @@ //! set as [`Added`](Event::Added) when first consumed, and returning `None` once the catalog //! finishes cleanly, or an error when the recording is incomplete. -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Weak}; use std::task::Poll; @@ -270,7 +270,7 @@ impl Fanout { pub fn stamp(&self, key: &Key, broken: bool, end: Duration) -> u64 { let mut feed = self.feed.write().unwrap_or_else(|_| unreachable!("fanout is open")); if feed.anchor.is_none() { - feed.anchor = Some(moq_clock::wall().checked_sub(end).unwrap_or(Wall::UNIX_EPOCH)); + feed.anchor = Some(kio::clock::wall().checked_sub(end).unwrap_or(Wall::UNIX_EPOCH)); } feed.discontinuities.stamp(key, broken) } diff --git a/rs/moq-hls/src/export/segments.rs b/rs/moq-hls/src/export/segments.rs index 8f0aaff9182..dc4a78ba78b 100644 --- a/rs/moq-hls/src/export/segments.rs +++ b/rs/moq-hls/src/export/segments.rs @@ -15,7 +15,7 @@ //! rendition numbers its own segments, so a number means the same on every edge and reload of //! that rendition, but nothing across renditions: players match renditions by timestamp. -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, ready}; diff --git a/rs/moq-hls/src/import.rs b/rs/moq-hls/src/import.rs index 21a01e82208..1ac3fdd1b25 100644 --- a/rs/moq-hls/src/import.rs +++ b/rs/moq-hls/src/import.rs @@ -742,7 +742,7 @@ impl Import { /// amount of waiting changes either. pub async fn run(&mut self) -> Result<()> { let mut delay = STEP_RETRY_MIN; - let mut deadline = moq_clock::now() + STEP_RETRY_BUDGET; + let mut deadline = kio::clock::now() + STEP_RETRY_BUDGET; loop { // A step where *nothing* ingested while a rendition was failing is a failed pass wearing @@ -766,7 +766,7 @@ impl Import { Ok(outcome) => { // The source is alive, so the earlier failures no longer describe it. delay = STEP_RETRY_MIN; - deadline = moq_clock::now() + STEP_RETRY_BUDGET; + deadline = kio::clock::now() + STEP_RETRY_BUDGET; outcome } Err(err @ Error::ResourceRefused) => return Err(err), @@ -778,7 +778,7 @@ impl Import { // The source rewound its timestamps, which no later pass can import. Err(err @ Error::Rewind { .. }) => return Err(err), Err(err) => { - let now = moq_clock::now(); + let now = kio::clock::now(); if now >= deadline { return Err(err); } @@ -790,7 +790,7 @@ impl Import { .mul_f64(0.5 + rand::rng().random::() / 2.0) .min(deadline - now); delay = (delay * 2).min(STEP_RETRY_MAX); - moq_clock::sleep(wait).await; + kio::clock::sleep(wait).await; continue; } }; @@ -807,7 +807,7 @@ impl Import { "HLS import step complete" ); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; } } @@ -1972,7 +1972,7 @@ mod tests { assert!(import.video[0].importer.is_none(), "nothing was imported"); assert!(catalog.snapshot().video.renditions.is_empty()); - let run = moq_clock::timeout(Duration::from_secs(5), import.run()) + let run = kio::clock::timeout(Duration::from_secs(5), import.run()) .await .expect("a settled refusal skips the retry budget"); assert!(matches!(run, Err(Error::PlaylistEnded))); @@ -1999,7 +1999,7 @@ mod tests { let cfg = Config::new(Url::from_file_path(dir.join("master.m3u8")).unwrap()); let mut import = Import::new(broadcast, catalog, cfg).unwrap(); - let run = moq_clock::timeout(Duration::from_secs(5), import.run()) + let run = kio::clock::timeout(Duration::from_secs(5), import.run()) .await .expect("the ended rendition ends the import"); assert!(matches!(run, Err(Error::PlaylistEnded)), "{run:?}"); @@ -2032,7 +2032,7 @@ mod tests { let (_, ended) = recording(4, true); std::fs::write(dir.join("media.m3u8"), ended).unwrap(); - moq_clock::timeout(Duration::from_secs(10), import.run()) + kio::clock::timeout(Duration::from_secs(10), import.run()) .await .expect("an ended playlist ends the import") .unwrap(); @@ -2426,7 +2426,7 @@ mod tests { "audio", "#EXTINF:1,\naudio0.m4s\n#EXT-X-DISCONTINUITY\n#EXTINF:1,\naudio1.m4s\n", ); - let run = moq_clock::timeout(Duration::from_secs(5), import.run()) + let run = kio::clock::timeout(Duration::from_secs(5), import.run()) .await .expect("a rewind is not retried"); assert!( @@ -2462,8 +2462,8 @@ mod tests { let mut track = consumer.track(name).unwrap().subscribe(replay).await.unwrap(); let wait = std::time::Duration::from_millis(100); let mut out = Vec::new(); - while let Ok(Ok(Some(mut group))) = moq_clock::timeout(wait, track.recv_group()).await { - while let Ok(Ok(Some(frame))) = moq_clock::timeout(wait, group.read_frame()).await { + while let Ok(Ok(Some(mut group))) = kio::clock::timeout(wait, track.recv_group()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(wait, group.read_frame()).await { out.push(frame.timestamp.unwrap().as_micros()); } } @@ -2513,7 +2513,7 @@ mod tests { let before = published(&consumer, &catalog).await; // Let the clock run on, so a fresh offset could not land back on the source's timestamps. - moq_clock::sleep(std::time::Duration::from_millis(50)).await; + kio::clock::sleep(std::time::Duration::from_millis(50)).await; let mut second = sink.importer(&select_muxed()); second.decode(&init).unwrap(); drop(first); diff --git a/rs/moq-hls/src/server/mod.rs b/rs/moq-hls/src/server/mod.rs index bc5e2430816..a648959c15f 100644 --- a/rs/moq-hls/src/server/mod.rs +++ b/rs/moq-hls/src/server/mod.rs @@ -212,7 +212,7 @@ impl Server { // A request answers once the origin has synced with the relay, so a path with no route // fails now rather than waiting out a publisher that has gone. The source resolves a // rendition's sibling `broadcast` reference through the same origin. - let broadcast = match moq_clock::timeout(RESOLVE_TIMEOUT, self.inner.origin.request(name, None)).await { + let broadcast = match kio::clock::timeout(RESOLVE_TIMEOUT, self.inner.origin.request(name, None)).await { Ok(Ok(broadcast)) => broadcast, Ok(Err(moq_net::Error::Unroutable)) => return None, Ok(Err(err)) => { @@ -421,7 +421,7 @@ mod tests { let origin = produce_origin(); let server = Server::new(origin.consume(), Config::default()); - let start = moq_clock::now(); + let start = kio::clock::now(); assert!(server.broadcaster("live").await.is_none()); assert_eq!(start.elapsed(), Duration::ZERO); } @@ -495,7 +495,7 @@ mod tests { if ready().await { return; } - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; } panic!("never happened"); } diff --git a/rs/moq-hls/src/server/routes.rs b/rs/moq-hls/src/server/routes.rs index e4f1e070329..75a11a96ce8 100644 --- a/rs/moq-hls/src/server/routes.rs +++ b/rs/moq-hls/src/server/routes.rs @@ -72,7 +72,7 @@ async fn master(server: &Server, broadcast: &str, query: Option<&str>) -> Respon }; // A master listing no variant is unplayable: wait for one that can start, else answer // unavailable. - let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.advertised()).await; + let _ = kio::clock::timeout(READY_TIMEOUT, broadcaster.advertised()).await; let (video, audio) = broadcaster.variants(query); if video.is_empty() && audio.is_empty() { return not_found(); @@ -84,17 +84,17 @@ async fn manifest(server: &Server, broadcast: &str, query: Option<&str>) -> Resp let Some(broadcaster) = server.broadcaster(broadcast).await else { return not_found(); }; - let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; + let _ = kio::clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; if broadcaster.is_empty() { return not_found(); } // A manifest whose renditions are all empty confuses players; give the broadcast a moment // to index its first complete segment before answering. - let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.playable()).await; + let _ = kio::clock::timeout(READY_TIMEOUT, broadcaster.playable()).await; // Each representation names its init by hash, which an inline codec only learns from media. // A player keeps the adaptation sets of the first manifest it loads, so wait for one video // init rather than every init: a stuck rendition never holds a sibling that can play. - let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.video_init()).await; + let _ = kio::clock::timeout(READY_TIMEOUT, broadcaster.video_init()).await; match broadcaster.manifest(query) { Ok(Some(manifest)) => mpd(manifest), Ok(None) => not_found(), @@ -106,7 +106,7 @@ async fn media(server: &Server, at: At<'_>, query: Option<&str>) -> Response { let Some(rendition) = rendition_for(server, at).await else { return not_found(); }; - match moq_clock::timeout(READY_TIMEOUT, rendition.playlist(query)).await { + match kio::clock::timeout(READY_TIMEOUT, rendition.playlist(query)).await { Ok(Ok(Some(playlist))) => m3u8(playlist), Ok(Ok(None)) | Err(_) => not_found(), Ok(Err(err)) => server_error(err), @@ -150,7 +150,7 @@ impl<'a> At<'a> { /// Resolve a rendition, waiting for the catalog to populate. async fn rendition_for(server: &Server, at: At<'_>) -> Option> { let broadcaster = server.instance(at.broadcast, at.instance).await?; - let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; + let _ = kio::clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; broadcaster.rendition(at.kind, at.rendition) } @@ -277,7 +277,7 @@ mod tests { } async fn wait_listed(app: &axum::Router, playlist: &str, segment: &str) { - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; let mut last = String::new(); loop { let response = oneshot(app.clone(), playlist).await; @@ -288,8 +288,11 @@ mod tests { return; } } - assert!(moq_clock::now() < deadline, "{playlist} never listed {segment}: {last}"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!( + kio::clock::now() < deadline, + "{playlist} never listed {segment}: {last}" + ); + kio::clock::sleep(Duration::from_millis(50)).await; } } @@ -411,7 +414,7 @@ mod tests { ) .unwrap(); let app = Server::new(restricted, Default::default()).router(); - let start = moq_clock::now(); + let start = kio::clock::now(); let response = oneshot(app, "/room/live/manifest.mpd").await; assert!(start.elapsed() < READY_TIMEOUT, "waited {:?}", start.elapsed()); assert_eq!(response.status(), StatusCode::OK); @@ -458,10 +461,10 @@ mod tests { assert_eq!(status(&app, &old_segment).await, StatusCode::OK); drop((old_catalog, old_track, old_media, old)); - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; while status(&app, &old_playlist).await != StatusCode::NOT_FOUND { - assert!(moq_clock::now() < deadline, "the closed instance kept serving"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "the closed instance kept serving"); + kio::clock::sleep(Duration::from_millis(50)).await; } assert_eq!(status(&app, &old_segment).await, StatusCode::NOT_FOUND); assert_eq!(status(&app, &new_playlist).await, StatusCode::OK); @@ -500,14 +503,14 @@ mod tests { .abort(moq_net::Error::Transport("connection lost".into())) .unwrap(); for uri in [&format!("/live/@{RUN}/video/video0/media.m3u8"), "/live/manifest.mpd"] { - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; let response = loop { let response = oneshot(app.clone(), uri).await; if response.status() != StatusCode::OK { break response; } - assert!(moq_clock::now() < deadline, "{uri} never failed"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "{uri} never failed"); + kio::clock::sleep(Duration::from_millis(50)).await; }; assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR, "{uri}"); assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store", "{uri}"); diff --git a/rs/moq-hls/tests/integration/disconnect.rs b/rs/moq-hls/tests/integration/disconnect.rs index f04f7c70634..e0b83d6dc83 100644 --- a/rs/moq-hls/tests/integration/disconnect.rs +++ b/rs/moq-hls/tests/integration/disconnect.rs @@ -32,7 +32,7 @@ async fn disconnect(at: At) { let media = media_uri(&app, "live").await; let playlist = listed(&app, &media, ".2.m4s").await; assert_eq!(numbers(&playlist), [0, 1, 2], "{playlist}"); - let first = moq_clock::timeout(TIMEOUT, cursor.next()) + let first = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the first segment") .expect("records") @@ -67,7 +67,7 @@ async fn disconnect(at: At) { ); // The failure is final: every later call answers it again. for _ in 0..2 { - let again = moq_clock::timeout(TIMEOUT, cursor.next()) + let again = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the cursor stalled"); let Err(again) = again else { diff --git a/rs/moq-hls/tests/integration/finish.rs b/rs/moq-hls/tests/integration/finish.rs index bd0cb1bae01..38ff344aefc 100644 --- a/rs/moq-hls/tests/integration/finish.rs +++ b/rs/moq-hls/tests/integration/finish.rs @@ -28,7 +28,7 @@ async fn finish(order: Order) { let media = media_uri(&app, "live").await; listed(&app, &media, ".2.m4s").await; // Reading, as a recorder does, so the cursor's subscription carries every group across. - let first = moq_clock::timeout(TIMEOUT, cursor.next()) + let first = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the first segment") .expect("records") @@ -47,10 +47,10 @@ async fn finish(order: Order) { publisher.media.finish().expect("finish media"); publisher.broadcast.close(); // The server stops serving the instance once `End` reaches it. - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; while get(&app, &media).await.status() != StatusCode::NOT_FOUND { - assert!(moq_clock::now() < deadline, "End never reached the export"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "End never reached the export"); + kio::clock::sleep(Duration::from_millis(50)).await; } // `End` alone confirms nothing: the recording stays open until the catalog's EOF. let playlist = rendition.media_playlist(None).expect("live").expect("listed"); @@ -64,7 +64,7 @@ async fn finish(order: Order) { let (read, end) = drain(&mut cursor).await; end.unwrap_or_else(|err| panic!("{order:?}: {err}")); assert_eq!(read, [1, 2, 3, 4], "{order:?}"); - let again = moq_clock::timeout(TIMEOUT, cursor.next()) + let again = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the cursor stalled"); assert!(matches!(again, Ok(None)), "{order:?}: a finished cursor stays finished"); diff --git a/rs/moq-hls/tests/integration/restart.rs b/rs/moq-hls/tests/integration/restart.rs index 2e7112dfe04..d2c3826ad1f 100644 --- a/rs/moq-hls/tests/integration/restart.rs +++ b/rs/moq-hls/tests/integration/restart.rs @@ -48,7 +48,7 @@ async fn takeover(version: &str, case: Case) { assert_old(&app, uri).await; } // Read as a recorder does. A cached segment can return while the live feed is still opening. - let first = moq_clock::timeout(TIMEOUT, cursor.next()) + let first = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the first segment") .expect("records") @@ -60,7 +60,7 @@ async fn takeover(version: &str, case: Case) { )); match case { // Paused, the clock only moves once every task is idle, so the feed has its answer. - Case::Answered => moq_clock::sleep(Duration::from_millis(500)).await, + Case::Answered => kio::clock::sleep(Duration::from_millis(500)).await, Case::FinishedFirst => old.finish(), Case::Unanswered | Case::UnansweredUnfinished => {} } @@ -68,14 +68,14 @@ async fn takeover(version: &str, case: Case) { // The new instance numbers its groups and segments from zero again. let route = moq_net::origin::Route::default().with_epoch(moq_net::Epoch::mint()); let mut new = Publisher::new(&pair.publisher, "live", route); - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; let current = loop { let current = server.broadcaster("live").await.expect("announced"); if !std::sync::Arc::ptr_eq(¤t, &replaced) { break current; } - assert!(moq_clock::now() < deadline, "the new instance never took over"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "the new instance never took over"); + kio::clock::sleep(Duration::from_millis(50)).await; }; current.set_generation(Some("run-2")).expect("generation"); new.write(0, 13, NEW); @@ -164,7 +164,7 @@ async fn finished_first() { async fn drain_old(cursor: &mut segments::Consumer) -> (Vec, moq_hls::Result<()>) { let mut read = Vec::new(); loop { - let next = moq_clock::timeout(TIMEOUT, cursor.next()) + let next = kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the replaced run's cursor stalled"); let segment = match next { diff --git a/rs/moq-hls/tests/integration/server.rs b/rs/moq-hls/tests/integration/server.rs index 083358e29a1..b4c6c93256e 100644 --- a/rs/moq-hls/tests/integration/server.rs +++ b/rs/moq-hls/tests/integration/server.rs @@ -18,7 +18,7 @@ async fn respond_serves_a_route_rewritten_into_scope() { let mut route = Route::parse(&format!("/tenant{media}")).expect("media route"); route.broadcast = route.broadcast.strip_prefix("tenant/").expect("scoped").to_string(); - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; let body = loop { let response = server.respond(&route, Some("jwt=abc")).await; if response.status() == StatusCode::OK { @@ -28,8 +28,8 @@ async fn respond_serves_a_route_rewritten_into_scope() { break body; } } - assert!(moq_clock::now() < deadline, "media playlist never listed a segment"); - moq_clock::sleep(std::time::Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "media playlist never listed a segment"); + kio::clock::sleep(std::time::Duration::from_millis(50)).await; }; assert!(body.contains(".mp4?jwt=abc\""), "{body}"); assert!(body.contains(".0.m4s?jwt=abc"), "{body}"); @@ -50,14 +50,14 @@ async fn a_cursor_records_a_publisher_without_fetch() { let mut publisher = Publisher::new(&pair.publisher, "live", Default::default()); let origin = pair.subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, origin.follow("live", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, origin.follow("live", None).unwrap().available()) .await .expect("request timed out") .expect("remote broadcast"); let broadcaster = Broadcaster::new(moq_mux::Source::new(origin, remote), Default::default()); // Recorded as soon as the catalog lists it with its records, as a recorder does. let mut renditions = broadcaster.renditions(); - let rendition = match moq_clock::timeout(TIMEOUT, renditions.next()).await { + let rendition = match kio::clock::timeout(TIMEOUT, renditions.next()).await { Ok(Ok(Some(renditions::Event::Added(rendition)))) => rendition, _ => panic!("{version}: the catalog never listed the rendition"), }; @@ -69,7 +69,7 @@ async fn a_cursor_records_a_publisher_without_fetch() { while demand.wanted_changed().await?.is_none() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { tokio::select! { _ = next.as_mut() => panic!("{version}: a segment before any media"), wanted = wanted => wanted.expect("track open"), @@ -79,7 +79,7 @@ async fn a_cursor_records_a_publisher_without_fetch() { .unwrap_or_else(|_| panic!("{version}: the cursor never subscribed")); publisher.write(0, 5, 1); - let segment = moq_clock::timeout(TIMEOUT, next) + let segment = kio::clock::timeout(TIMEOUT, next) .await .unwrap_or_else(|_| panic!("{version}: no segment recorded")) .unwrap_or_else(|err| panic!("{version}: {err}")) @@ -115,12 +115,12 @@ async fn a_disconnected_publisher_on_the_catalog_broadcast_answers_404() { let media = media_uri(&app, "live").await; let first = segment(&listed(&app, &media, ".0.m4s").await, 0); - let remote = moq_clock::timeout(TIMEOUT, pair.subscriber.consume().request("live", None)) + let remote = kio::clock::timeout(TIMEOUT, pair.subscriber.consume().request("live", None)) .await .expect("remote resolve timed out") .expect("remote broadcast"); drop(publisher); - moq_clock::timeout(TIMEOUT, remote.closed()) + kio::clock::timeout(TIMEOUT, remote.closed()) .await .expect("publisher close timed out"); @@ -136,7 +136,7 @@ async fn lookups_ride_the_servers_scope_watch() { other.announce(Default::default()).expect("announce other"); let server = pair.server(); - let missing = moq_clock::timeout(TIMEOUT, server.broadcaster("room/missing")) + let missing = kio::clock::timeout(TIMEOUT, server.broadcaster("room/missing")) .await .expect("lookup timed out"); assert!(missing.is_none()); @@ -170,12 +170,12 @@ async fn a_sibling_resolves_through_a_client_session() { media.announce(Default::default()).expect("announce media"); let origin = pair.subscriber.consume(); - let broadcast = moq_clock::timeout(TIMEOUT, origin.follow("room/live", None).unwrap().available()) + let broadcast = kio::clock::timeout(TIMEOUT, origin.follow("room/live", None).unwrap().available()) .await .expect("catalog resolve timed out") .expect("catalog broadcast"); let source = moq_mux::Source::new(origin, broadcast); - let sibling = moq_clock::timeout( + let sibling = kio::clock::timeout( TIMEOUT, source.resolve(Some(&moq_net::path::Relative::new("./source").unwrap()), None), ) @@ -219,7 +219,7 @@ async fn a_disconnected_sibling_publisher_answers_404() { let first = segment(&listed(&app, &uri, ".0.m4s").await, 0); // Waited on rather than requested once: a client only asks about what it watches. - let remote_media = moq_clock::timeout( + let remote_media = kio::clock::timeout( TIMEOUT, pair.subscriber .consume() @@ -233,7 +233,7 @@ async fn a_disconnected_sibling_publisher_answers_404() { // Only the sibling goes: the catalog keeps listing the rendition, so the request reaches the // media fetch rather than missing the rendition. media_broadcast.close(); - moq_clock::timeout(TIMEOUT, remote_media.closed()) + kio::clock::timeout(TIMEOUT, remote_media.closed()) .await .expect("sibling close timed out"); diff --git a/rs/moq-hls/tests/integration/support.rs b/rs/moq-hls/tests/integration/support.rs index 1ce48d9d523..66e65ea2365 100644 --- a/rs/moq-hls/tests/integration/support.rs +++ b/rs/moq-hls/tests/integration/support.rs @@ -47,7 +47,7 @@ impl Pair { let (client, server) = tokio::join!( async { let (session, driver) = client - .connect(moq_clock::now(), client_transport) + .connect(kio::clock::now(), client_transport) .await .expect("client session"); tokio::spawn(moq_net::time::run(driver)); @@ -55,7 +55,7 @@ impl Pair { }, async { let (session, driver) = server - .accept(moq_clock::now(), server_transport) + .accept(kio::clock::now(), server_transport) .await .expect("server session"); tokio::spawn(moq_net::time::run(driver)); @@ -179,13 +179,13 @@ pub fn frame(second: u64, payload: u8) -> moq_mux::container::Frame { /// The rendition `server` exports for `path` once its catalog lists it. pub async fn rendition(server: &Server, path: &str) -> std::sync::Arc { - let broadcaster = moq_clock::timeout(TIMEOUT, server.broadcaster(path)) + let broadcaster = kio::clock::timeout(TIMEOUT, server.broadcaster(path)) .await .expect("resolve timed out") .expect("announced"); let mut renditions = broadcaster.renditions(); loop { - match moq_clock::timeout(TIMEOUT, renditions.next()).await { + match kio::clock::timeout(TIMEOUT, renditions.next()).await { Ok(Ok(Some(moq_hls::export::renditions::Event::Added(rendition)))) if rendition.name == TRACK => { return rendition; } @@ -199,7 +199,7 @@ pub async fn rendition(server: &Server, path: &str) -> std::sync::Arc pub async fn drain(cursor: &mut segments::Consumer) -> (Vec, moq_hls::Result<()>) { let mut read = Vec::new(); loop { - match moq_clock::timeout(TIMEOUT, cursor.next()) + match kio::clock::timeout(TIMEOUT, cursor.next()) .await .expect("the cursor stalled") { @@ -224,7 +224,7 @@ pub async fn get(app: &axum::Router, uri: &str) -> Response { /// Poll `uri` until it answers 200 with a body containing `needle`, returning the body. pub async fn listed(app: &axum::Router, uri: &str, needle: &str) -> String { - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; loop { let response = get(app, uri).await; let body = String::from_utf8_lossy(response.body()).into_owned(); @@ -232,11 +232,11 @@ pub async fn listed(app: &axum::Router, uri: &str, needle: &str) -> String { return body; } assert!( - moq_clock::now() < deadline, + kio::clock::now() < deadline, "{uri} never listed {needle}: {} {body}", response.status() ); - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } } diff --git a/rs/moq-ice/Cargo.toml b/rs/moq-ice/Cargo.toml index 58956326500..905c603487f 100644 --- a/rs/moq-ice/Cargo.toml +++ b/rs/moq-ice/Cargo.toml @@ -13,7 +13,7 @@ keywords = ["webrtc", "ice", "stun", "str0m", "moq"] categories = ["network-programming", "multimedia"] [dependencies] -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } str0m = { workspace = true } stun-types = { workspace = true } thiserror = { workspace = true } diff --git a/rs/moq-ice/src/agent.rs b/rs/moq-ice/src/agent.rs index d93ed360453..2ef83e50807 100644 --- a/rs/moq-ice/src/agent.rs +++ b/rs/moq-ice/src/agent.rs @@ -4,7 +4,7 @@ use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use str0m::net::{Protocol, Receive}; use str0m::{Candidate, IceConnectionState, Input, Output, Rtc}; use stun_types::attribute::XorMappedAddress; @@ -250,7 +250,7 @@ impl Agent { self.receive(&data, src); continue; } - _ = moq_clock::sleep_until(deadline) => {} + _ = kio::clock::sleep_until(deadline) => {} } } diff --git a/rs/moq-mux/Cargo.toml b/rs/moq-mux/Cargo.toml index 129f159a31c..4b24fcbd150 100644 --- a/rs/moq-mux/Cargo.toml +++ b/rs/moq-mux/Cargo.toml @@ -21,9 +21,8 @@ ebml-iterable = { workspace = true } h264-parser = { version = "0.4.2" } h264-reader = "0.9.0" hang = { workspace = true } -kio = { workspace = true } +kio = { workspace = true, features = ["runtime"] } memchr = "2" -moq-clock = { workspace = true } moq-json = { workspace = true } moq-loc = { workspace = true } moq-msf = { workspace = true } @@ -47,7 +46,7 @@ webm-iterable = "0.7" [dev-dependencies] criterion = { package = "bench-harness", path = "../bench-harness" } futures = { workspace = true } -moq-clock = { workspace = true, features = ["sim"] } +kio = { workspace = true, features = ["sim"] } proptest = { workspace = true } tokio = { workspace = true, features = ["test-util"] } tracing-test = { workspace = true } diff --git a/rs/moq-mux/benches/decode_clock.rs b/rs/moq-mux/benches/decode_clock.rs index e0c4e745d93..f3ddb0567a3 100644 --- a/rs/moq-mux/benches/decode_clock.rs +++ b/rs/moq-mux/benches/decode_clock.rs @@ -4,7 +4,7 @@ use std::time::Duration; use bytes::Bytes; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use moq_clock::Instant; +use kio::clock::Instant; #[path = "../src/container/decode.rs"] #[allow( diff --git a/rs/moq-mux/benches/jitter.rs b/rs/moq-mux/benches/jitter.rs index d5185674bde..0d7e40e3a68 100644 --- a/rs/moq-mux/benches/jitter.rs +++ b/rs/moq-mux/benches/jitter.rs @@ -15,13 +15,13 @@ mod jitter; /// Every track sends a frame a second as it decodes, for as many two-second steering steps as /// fill the rate window with `floors`, each step measuring every track heard. async fn steer(tracks: u16, floors: u64) -> u64 { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = jitter::Buffer::new(Duration::from_millis(500)); buffer.expect(1..=tracks); let waiter = kio::Waiter::noop(); for second in 0..floors * 2 { let at = start + Duration::from_secs(second); - tokio::time::advance(at.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; for track in 1..=tracks { let arrival = jitter::Arrival { arrived: at, @@ -76,7 +76,7 @@ fn acquisition(c: &mut Criterion) { group.bench_function(BenchmarkId::new(tracks.to_string(), frames), |b| { b.iter(|| { runtime.block_on(async { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = jitter::Buffer::new(Duration::from_millis(500)); buffer.expect(1..=tracks); for track in 1..=tracks { @@ -123,7 +123,7 @@ fn handoff(c: &mut Criterion) { group.bench_function(BenchmarkId::new(tracks.to_string(), frames), |b| { b.iter(|| { runtime.block_on(async { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = jitter::Buffer::new(Duration::from_millis(500)); buffer.expect(1..=tracks); for instance in 0..2 { @@ -186,13 +186,13 @@ fn admission(c: &mut Criterion) { group.bench_function(BenchmarkId::new(tracks.to_string(), backlog), |b| { b.iter(|| { runtime.block_on(async { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = jitter::Buffer::new(delay); buffer.expect(1..=tracks); let frame = |decode| jitter::Arrival { arrived: start, - read: moq_clock::now(), + read: kio::clock::now(), decode: Timestamp::from_millis(decode).unwrap().into(), restart: 0, sync: true, diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index 9164dd30f72..5741ef5981b 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -98,7 +98,7 @@ const ESTIMATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(1); #[derive(Default)] struct Throttle { /// When the last publish carrying an estimate went out. - last: Option, + last: Option, /// An estimate is in the catalog but not yet on the wire. pending: bool, } @@ -107,7 +107,7 @@ impl Throttle { /// A publish is going out: any held estimate rides it and opens a new window. fn fold(&mut self) { if std::mem::take(&mut self.pending) { - self.last = Some(moq_clock::now()); + self.last = Some(kio::clock::now()); } } } @@ -679,7 +679,7 @@ impl Producer { &mut self, timebase: &std::sync::OnceLock, pts: moq_net::Timestamp, - wall: Option, + wall: Option, ) -> crate::Result { let mut guard = self.modify()?; // Another clone of the timebase may have anchored first; the lock orders them. A placement @@ -1246,7 +1246,7 @@ impl Guard<'_, E> { if !estimates.pending { return Ok(()); } - let now = moq_clock::now(); + let now = kio::clock::now(); if throttle && estimates.last.is_some_and(|last| now < last + ESTIMATE_WINDOW) { return Ok(()); } @@ -2278,8 +2278,8 @@ mod test { fn sibling_broadcasts_share_a_clock_and_capture_time() { use std::time::Duration; - let captured = moq_clock::now(); - let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); + let captured = kio::clock::now(); + let wall = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); let clock = crate::Clock::at(captured, wall).unwrap(); let (origin, _driver) = moq_net::origin::Producer::new(Default::default()); let front = origin.create_broadcast("robot/front.hang").unwrap(); @@ -2332,14 +2332,14 @@ mod test { /// A `with_clock` catalog is fixed from the start: even the first importer shifts onto it, /// landing at the clock's reading on arrival, and the advertised mapping never moves. - #[moq_clock::test] + #[kio::test] async fn with_clock_shifts_the_first_importer() { use std::time::Duration; - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; let mut broadcast = moq_net::broadcast::Info::new().produce(); - let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); - let start = moq_clock::now() - Duration::from_secs(5); + let wall = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); + let start = kio::clock::now() - Duration::from_secs(5); let config = Config::default().with_clock(crate::Clock::at(start, wall).expect("a representable wall")); let catalog = Producer::new(&mut broadcast, config).unwrap(); @@ -2375,7 +2375,7 @@ mod test { let clock = catalog.clock(); assert_eq!(catalog.snapshot().clock, clock.wall(), "the anchor is advertised"); let actual = clock.wall_clock(first).unwrap(); - let now = moq_clock::wall(); + let now = kio::clock::wall(); let drift = actual.max(now).saturating_duration_since(actual.min(now)); assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival"); @@ -2446,7 +2446,7 @@ mod test { fn a_placed_input_lands_where_it_says() { use std::time::Duration; - let wall = moq_clock::Wall::now() - Duration::from_secs(2); + let wall = kio::clock::Wall::now() - Duration::from_secs(2); let pts = moq_net::Timestamp::from_micros(100_000_000).unwrap(); let later = moq_net::Timestamp::from_micros(101_000_000).unwrap(); @@ -2482,7 +2482,7 @@ mod test { fn a_placement_alone_publishes_nothing() { use std::time::Duration; - let wall = moq_clock::Wall::now() - Duration::from_secs(2); + let wall = kio::clock::Wall::now() - Duration::from_secs(2); let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap(); catalog.timebase().place(moq_net::Timestamp::ZERO, wall).unwrap(); @@ -2508,7 +2508,7 @@ mod test { let now = Duration::from_secs(86_400); crate::clock::fake_host_wall( - moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + now, + kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + now, ); let zero = moq_net::Timestamp::from_secs(now.as_secs() - 3600).unwrap(); hang::catalog::Clock::new(zero.convert(scale).unwrap()).unwrap() @@ -2561,12 +2561,12 @@ mod test { // The same mapping from `with_clock` agrees in any units, without reading the host's wall // clock, which may be unset. - let zero = moq_clock::Wall::UNIX_EPOCH + let zero = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + Duration::from_micros(input.wall.as_micros() as u64); - let fixed = crate::Clock::at(moq_clock::now(), zero).unwrap(); + let fixed = crate::Clock::at(kio::clock::now(), zero).unwrap(); seed.clock = Some(an_hour_ago(moq_net::Timescale::MILLI)); - crate::clock::fake_host_wall(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let config = Config::default().with_catalog(seed.clone()).with_clock(fixed); let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = Producer::new(&mut broadcast, config).unwrap(); @@ -2575,7 +2575,7 @@ mod test { assert_eq!(catalog.snapshot().clock, Some(input)); // A different one is refused before any catalog track exists. - let other = crate::Clock::at(moq_clock::now(), zero + Duration::from_secs(1)).unwrap(); + let other = crate::Clock::at(kio::clock::now(), zero + Duration::from_secs(1)).unwrap(); let config = Config::default().with_catalog(seed).with_clock(other); let mut broadcast = moq_net::broadcast::Info::new().produce(); assert!(matches!( @@ -2645,12 +2645,12 @@ mod test { fn an_unset_host_clock_publishes_without_a_wall() { use std::time::Duration; - crate::clock::fake_host_wall(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = Producer::new(&mut broadcast, Config::default()).unwrap(); assert_eq!(catalog.snapshot().clock, None); - let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); + let wall = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); let pts = moq_net::Timestamp::from_micros(1_000_000).unwrap(); assert!(matches!( catalog.timebase().place(pts, wall), diff --git a/rs/moq-mux/src/catalog/timebase.rs b/rs/moq-mux/src/catalog/timebase.rs index 0b74b2d3f71..d8bb1eefdd9 100644 --- a/rs/moq-mux/src/catalog/timebase.rs +++ b/rs/moq-mux/src/catalog/timebase.rs @@ -50,7 +50,7 @@ impl Timebase { /// A placement alone publishes nothing: the clock goes out with the catalog's first track. /// Refused once this timebase has an offset, and when the host's wall clock was unset, leaving no /// wall to place it on. - pub fn place(&self, pts: moq_net::Timestamp, wall: moq_clock::Wall) -> crate::Result<()> { + pub fn place(&self, pts: moq_net::Timestamp, wall: kio::clock::Wall) -> crate::Result<()> { self.catalog.clone().anchor(&self.offset, pts, Some(wall))?; Ok(()) } diff --git a/rs/moq-mux/src/clock.rs b/rs/moq-mux/src/clock.rs index 0bdf0679d49..142ffeba6a4 100644 --- a/rs/moq-mux/src/clock.rs +++ b/rs/moq-mux/src/clock.rs @@ -17,11 +17,11 @@ //! anything fixes the clock places the mapping so that frame is live on arrival; any other shifts //! onto the clock (see [`catalog::Timebase`](crate::catalog::Timebase)). -use moq_clock::Wall; +use kio::clock::Wall; use std::time::Duration; use hang::catalog::{MAX_SAFE_INTEGER, MOQ_EPOCH_UNIX_MILLIS}; -use moq_clock::Instant; +use kio::clock::Instant; /// Microseconds from the moq epoch (2020) to `wall`, negative before it. fn moq_micros(wall: Wall) -> i128 { @@ -31,7 +31,7 @@ fn moq_micros(wall: Wall) -> i128 { /// The host's wall clock, or `None` while it reads before the moq epoch (2020): unset. pub(crate) fn host_wall() -> Option { - let now = moq_clock::wall(); + let now = kio::clock::wall(); #[cfg(test)] let now = HOST_WALL.get().unwrap_or(now); (moq_micros(now) >= 0).then_some(now) @@ -98,7 +98,7 @@ impl Clock { /// name: media needs only the monotonic timeline. pub fn new() -> Self { Self { - instant: moq_clock::now(), + instant: kio::clock::now(), reading: Self::LEAD.as_micros() as u64, wall: host_wall().and_then(|now| wall_clock(now.checked_sub(Self::LEAD)?).ok()), } @@ -121,7 +121,7 @@ impl Clock { /// Refuses a `since` so large that PTS zero lands before the moq epoch (2020), which the wall /// mapping cannot name. On a host whose wall clock is unset, the clock has no wall mapping. pub(crate) fn arrival(since: Duration) -> crate::Result { - let instant = moq_clock::now(); + let instant = kio::clock::now(); let unmappable = || crate::Error::UnmappableTimestamp(format!("{since:?} puts PTS zero before 2020")); let wall = match host_wall() { Some(now) => { @@ -183,7 +183,7 @@ impl Clock { /// /// No `Instant` arithmetic, so a PTS zero before this host booted still maps. fn mapped(zero: hang::catalog::Clock, unmappable: impl Fn(&str) -> crate::Error) -> crate::Result { - let instant = moq_clock::now(); + let instant = kio::clock::now(); let now = host_wall().ok_or_else(|| unmappable("needs the host wall clock, which is unset"))?; // Saturating would stamp everything early by the skew without saying so. let reading = u64::try_from(moq_micros(now) - zero.wall.as_micros() as i128) @@ -221,7 +221,7 @@ impl Clock { /// Refuses an instant ahead of now, which would claim the payload reached the transport before /// it existed, and one before PTS zero, which no timestamp can name. pub fn capture(&self, at: Instant) -> crate::Result { - if at > moq_clock::now() { + if at > kio::clock::now() { return Err(crate::Error::InvalidCapture); } let micros = match at.checked_duration_since(self.instant) { @@ -265,7 +265,7 @@ mod tests { use super::*; fn epoch() -> Instant { - moq_clock::now() + kio::clock::now() } fn moq_epoch() -> Wall { @@ -278,15 +278,15 @@ mod tests { /// A capture maps onto the clock's own timeline, and one ahead of now or before the epoch is /// refused rather than clamped. - #[moq_clock::test] + #[kio::test] async fn a_capture_maps_onto_the_clock() { - moq_clock::sleep(Duration::from_secs(6)).await; - let now = moq_clock::now(); + kio::clock::sleep(Duration::from_secs(6)).await; + let now = kio::clock::now(); let clock = Clock::at(now - Duration::from_secs(5), moq_epoch()).unwrap(); assert_eq!(clock.capture(now - Duration::from_secs(2)).unwrap(), us(3_000_000)); assert!(matches!( - clock.capture(moq_clock::now() + Duration::from_secs(1)), + clock.capture(kio::clock::now() + Duration::from_secs(1)), Err(crate::Error::InvalidCapture) )); assert!(matches!( @@ -295,16 +295,16 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] async fn simulated_clock_preserves_logical_boundaries() { - moq_clock::sleep(Duration::from_secs(10)).await; - let epoch = moq_clock::now(); + kio::clock::sleep(Duration::from_secs(10)).await; + let epoch = kio::clock::now(); let clock = Clock::at(epoch, moq_epoch()).unwrap(); let fresh = Clock::new(); let before = fresh.now(); let wall = clock.wall(); - moq_clock::sleep(Duration::from_secs(3)).await; + kio::clock::sleep(Duration::from_secs(3)).await; assert_eq!(clock.now(), us(3_000_000)); assert_eq!(fresh.now().as_micros() - before.as_micros(), 3_000_000); assert_eq!(clock.wall(), wall); @@ -313,8 +313,8 @@ mod tests { moq_epoch() + Duration::from_secs(3) ); - let stepped = moq_clock::Manual::WALL_START + Duration::from_secs(3600); - moq_clock::sim::step_wall(stepped); + let stepped = kio::clock::Manual::WALL_START + Duration::from_secs(3600); + kio::clock::sim::step_wall(stepped); assert_eq!(clock.wall(), wall, "a wall correction does not retime archived media"); assert_eq!( Clock::new().wall(), @@ -366,26 +366,26 @@ mod tests { // and the mapping still names the current wall time. assert!(clock.now().as_micros() >= Clock::LEAD.as_micros()); let now = clock.wall_clock(clock.now()).unwrap(); - let host = moq_clock::wall(); + let host = kio::clock::wall(); let drift = now.max(host).saturating_duration_since(now.min(host)); assert!(drift < Duration::from_secs(1), "wall + now is the current wall time"); } /// A source whose first timestamp is ten hours in reads that timestamp now, mapped to now. - #[moq_clock::test] + #[kio::test] async fn arrival_maps_the_first_timestamp_to_now() { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let since = Duration::from_secs(10 * 3600); let clock = Clock::arrival(since).unwrap(); let now = clock.now(); assert!(now.as_micros() >= since.as_micros()); let actual = clock.wall_clock(now).unwrap(); - let host = moq_clock::wall(); + let host = kio::clock::wall(); let drift = actual.max(host).saturating_duration_since(actual.min(host)); assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival"); // A capture from before the arrival still maps, down to PTS zero. - let earlier = clock.capture(moq_clock::now() - Duration::from_secs(1)).unwrap(); + let earlier = clock.capture(kio::clock::now() - Duration::from_secs(1)).unwrap(); assert!(earlier.as_micros() < now.as_micros()); // PTS zero before 2020 cannot be named on the wire. diff --git a/rs/moq-mux/src/codec/annexb/export.rs b/rs/moq-mux/src/codec/annexb/export.rs index c4296388efe..32aea9f3248 100644 --- a/rs/moq-mux/src/codec/annexb/export.rs +++ b/rs/moq-mux/src/codec/annexb/export.rs @@ -181,7 +181,7 @@ mod tests { use bytes::Bytes; async fn next(export: &mut Export) -> Bytes { - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .expect("a frame is ready") .unwrap() @@ -241,13 +241,13 @@ mod tests { moving.point("b", None, SPS); moving.b.write(marked_frame(0, 0xb1)).unwrap(); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .is_err() ); moving.b.write(marked_frame(30, 0xb2)).unwrap(); assert!(matches!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .unwrap(), Err(crate::Error::RenditionRewound { .. }) diff --git a/rs/moq-mux/src/codec/av1/split.rs b/rs/moq-mux/src/codec/av1/split.rs index b41aaa51fad..ca95fa9d1a9 100644 --- a/rs/moq-mux/src/codec/av1/split.rs +++ b/rs/moq-mux/src/codec/av1/split.rs @@ -20,7 +20,7 @@ use crate::Result; /// stdin); call [`flush`](Self::flush) to emit the final in-flight temporal unit. pub struct Split { current: Au, - zero: Option, + zero: Option, pending: Vec, // Bytes carried across calls: a partial OBU at the tail of one `decode` waits // here for the rest to arrive on the next call. @@ -169,7 +169,7 @@ impl Split { if let Some(pts) = hint { return Ok(pts); } - let zero = self.zero.get_or_insert_with(moq_clock::Instant::now); + let zero = self.zero.get_or_insert_with(kio::clock::Instant::now); Ok(moq_net::Timestamp::from_micros(zero.elapsed().as_micros() as u64)?) } } diff --git a/rs/moq-mux/src/codec/h264/export.rs b/rs/moq-mux/src/codec/h264/export.rs index 1b6d00b6912..7beebe83b98 100644 --- a/rs/moq-mux/src/codec/h264/export.rs +++ b/rs/moq-mux/src/codec/h264/export.rs @@ -270,7 +270,7 @@ mod tests { } /// The next chunk, required to be ready without another frame arriving. async fn next(export: &mut Export) -> Bytes { - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .expect("a frame is ready") .unwrap() @@ -313,7 +313,7 @@ mod tests { set_enabled(&mut live, true); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .is_err(), "the stale group the primary stopped on is not replayed" diff --git a/rs/moq-mux/src/codec/h264/split.rs b/rs/moq-mux/src/codec/h264/split.rs index 1863173c07e..1e687cfa04e 100644 --- a/rs/moq-mux/src/codec/h264/split.rs +++ b/rs/moq-mux/src/codec/h264/split.rs @@ -38,7 +38,7 @@ pub struct Split { /// Retained PPS NALs. A keyframe may carry several (slices reference them by /// id); all are kept and re-injected, but a new GOP's set supersedes them. pps: ParameterSets, - zero: Option, + zero: Option, pending: Vec, } @@ -267,7 +267,7 @@ impl Split { if let Some(pts) = hint { return Ok(pts); } - let zero = self.zero.get_or_insert_with(moq_clock::Instant::now); + let zero = self.zero.get_or_insert_with(kio::clock::Instant::now); Ok(moq_net::Timestamp::from_micros(zero.elapsed().as_micros() as u64)?) } } diff --git a/rs/moq-mux/src/codec/h265/export.rs b/rs/moq-mux/src/codec/h265/export.rs index 1dc0e2aad8e..bd2e4bc1438 100644 --- a/rs/moq-mux/src/codec/h265/export.rs +++ b/rs/moq-mux/src/codec/h265/export.rs @@ -249,7 +249,7 @@ mod tests { } /// The next chunk, required to be ready without another frame arriving. async fn next(export: &mut Export) -> Bytes { - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .expect("a frame is ready") .unwrap() @@ -306,7 +306,7 @@ mod tests { set_enabled(&mut live, true); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .is_err(), "the stale group the primary stopped on is not replayed" diff --git a/rs/moq-mux/src/codec/h265/split.rs b/rs/moq-mux/src/codec/h265/split.rs index db8adaa714d..1da2fde3c75 100644 --- a/rs/moq-mux/src/codec/h265/split.rs +++ b/rs/moq-mux/src/codec/h265/split.rs @@ -36,7 +36,7 @@ pub struct Split { /// Retained PPS NALs. A keyframe may carry several (slices reference them by /// id); all are kept and re-injected, but a new GOP's set supersedes them. pps: ParameterSets, - zero: Option, + zero: Option, pending: Vec, } @@ -274,7 +274,7 @@ impl Split { if let Some(pts) = hint { return Ok(pts); } - let zero = self.zero.get_or_insert_with(moq_clock::Instant::now); + let zero = self.zero.get_or_insert_with(kio::clock::Instant::now); Ok(moq_net::Timestamp::from_micros(zero.elapsed().as_micros() as u64)?) } } diff --git a/rs/moq-mux/src/codec/opus/import.rs b/rs/moq-mux/src/codec/opus/import.rs index b085a9f01e0..9f8aee1ad26 100644 --- a/rs/moq-mux/src/codec/opus/import.rs +++ b/rs/moq-mux/src/codec/opus/import.rs @@ -197,7 +197,7 @@ mod tests { subscriber, crate::catalog::hang::Container::Loc(crate::container::Kind::Data), ); - let frame = moq_clock::timeout(Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() diff --git a/rs/moq-mux/src/codec/vp8/import.rs b/rs/moq-mux/src/codec/vp8/import.rs index 936b2f7453c..7a20db2a6b4 100644 --- a/rs/moq-mux/src/codec/vp8/import.rs +++ b/rs/moq-mux/src/codec/vp8/import.rs @@ -197,7 +197,7 @@ mod tests { subscriber, crate::catalog::hang::Container::Loc(crate::container::Kind::Data), ); - let frame = moq_clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() diff --git a/rs/moq-mux/src/container/consumer.rs b/rs/moq-mux/src/container/consumer.rs index ce818570038..3f566a91a93 100644 --- a/rs/moq-mux/src/container/consumer.rs +++ b/rs/moq-mux/src/container/consumer.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Poll, ready}; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::Timestamp; use super::{Container, Frame, Read, TimestampRewind}; @@ -150,7 +150,7 @@ pub struct Consumer { max_delay: std::time::Duration, // Wakes the reader once the hole at the cursor expires. - hole_timer: Option>>, + hole_timer: Option>>, // The furthest presentation point delivered so far: max(timestamp + duration), endpoints // included. `None` until the first item, so a loss before it is no gap. @@ -528,7 +528,7 @@ impl Consumer { // Said now rather than with the gap, which waits for the next group: what // the caller holds of this one need not wait for a successor. return Poll::Ready(Ok(Some(Event::Cut { - observed: moq_clock::now(), + observed: kio::clock::now(), }))); } // Cleanly finished group: advance to the next sequence. @@ -653,7 +653,7 @@ impl Consumer { if let Some(wake) = since.checked_add(self.max_delay) { let timer = self .hole_timer - .get_or_insert_with(|| Box::pin(moq_clock::sleep_until(wake))); + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(wake))); timer.as_mut().reset(wake); let _ = waiter.poll_future(timer.as_mut()); } @@ -919,7 +919,7 @@ struct GroupBuffer { // From then on, any sequence missing below this group is late: the earliest arrival among it // and the groups past it, kept on insert so a hole reads it without scanning the backlog. - late: moq_clock::Instant, + late: kio::clock::Instant, // The current frame index within the group. index: usize, @@ -1317,7 +1317,7 @@ mod tests { async fn read_all(consumer: &mut Consumer) -> Result, crate::Error> { let mut frames = Vec::new(); loop { - match moq_clock::timeout(Duration::from_millis(200), consumer.read_frame()).await { + match kio::clock::timeout(Duration::from_millis(200), consumer.read_frame()).await { Ok(Ok(Some(frame))) => frames.push(frame), Ok(Ok(None)) => break, Ok(Err(e)) => return Err(e), @@ -1427,7 +1427,7 @@ mod tests { write_marker_group(&mut track, 16, ts(1_000_000)); let mut read = async || { - moq_clock::timeout(Duration::from_secs(1), reader.read()) + kio::clock::timeout(Duration::from_secs(1), reader.read()) .await .expect("the end is read while the track stays open") .unwrap() @@ -1504,8 +1504,8 @@ mod tests { assert!(reader.poll_read(&kio::Waiter::noop()).is_pending()); tokio::time::advance(budget - Duration::from_millis(1)).await; assert!(reader.poll_read(&kio::Waiter::noop()).is_pending()); - let before = moq_clock::now(); - let read = moq_clock::timeout(Duration::from_millis(2), reader.read()) + let before = kio::clock::now(); + let read = kio::clock::timeout(Duration::from_millis(2), reader.read()) .await .unwrap() .unwrap(); @@ -2015,7 +2015,7 @@ mod tests { // Finish group 0 after consumer has had time to accumulate pending groups let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; group0.finish().unwrap(); }); @@ -2054,7 +2054,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; group0.finish().unwrap(); }); @@ -2090,7 +2090,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; group0.finish().unwrap(); }); @@ -2509,7 +2509,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; group0.finish().unwrap(); }); @@ -2550,7 +2550,7 @@ mod tests { track.finish().unwrap(); - let result = moq_clock::timeout(Duration::from_millis(200), consumer.read()).await; + let result = kio::clock::timeout(Duration::from_millis(200), consumer.read()).await; match result { Ok(Ok(None)) => {} // expected: track ended Ok(Ok(Some(_))) => panic!("expected None for empty track, got Some"), @@ -2573,7 +2573,7 @@ mod tests { // The groups already here drain before the track's error, as in JS. let mut frames = Vec::new(); let end = loop { - let read = moq_clock::timeout(Duration::from_millis(500), consumer.read()) + let read = kio::clock::timeout(Duration::from_millis(500), consumer.read()) .await .expect("Consumer should not hang after track error"); match read { @@ -2749,7 +2749,7 @@ mod tests { // Must skip the evicted group + the gap and reach the live group, without // hanging on a track that never finishes. - let next = moq_clock::timeout(Duration::from_secs(1), consumer.read()) + let next = kio::clock::timeout(Duration::from_secs(1), consumer.read()) .await .expect("consumer hung on an evicted group / gap") .unwrap() @@ -2794,7 +2794,7 @@ mod tests { // The age budget alone closes the gap: the deadline sits short of the 100ms // hole timer, so waiting it out fails the test. - let frame = moq_clock::timeout(Duration::from_millis(50), consumer.read_frame()) + let frame = kio::clock::timeout(Duration::from_millis(50), consumer.read_frame()) .await .expect("consumer hung on a missing sequence on a live track") .unwrap() @@ -2824,7 +2824,7 @@ mod tests { // Group 0 is done; group 1's stream is still racing. Within the budget the // consumer waits at the gap rather than skipping to group 2. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "the gap at sequence 1 is within budget and must be waited for" @@ -2856,7 +2856,7 @@ mod tests { // Group 1's stream wins the race, and the consumer polls before group 0 lands. write_group(&mut track, 1, &[ts(100_000)]); assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "the requested head is within budget and must be waited for" @@ -2887,7 +2887,7 @@ mod tests { // Startup latches onto the lowest arrived sequence and waits under the budget. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "group 0's frames are within budget and must be waited for" @@ -2970,7 +2970,7 @@ mod tests { let first = consumer.read_frame().await; assert!(matches!(first, Ok(Some(_))), "first frame should decode, got {first:?}"); - let second = moq_clock::timeout(Duration::from_millis(200), consumer.read()) + let second = kio::clock::timeout(Duration::from_millis(200), consumer.read()) .await .expect("consumer hung on a decode error"); assert!( @@ -2991,7 +2991,7 @@ mod tests { /// Read until something other than a frame, failing if the reader stalls. async fn read_past_frames(consumer: &mut Consumer) -> Result, crate::Error> { loop { - let read = moq_clock::timeout(Duration::from_millis(200), consumer.read()) + let read = kio::clock::timeout(Duration::from_millis(200), consumer.read()) .await .expect("consumer hung"); match read { @@ -3086,7 +3086,7 @@ mod tests { assert_eq!(first.timestamp, ts(0)); // Lookahead finds the error while the reader waits on the open group, which comes first. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err() ); @@ -3094,10 +3094,10 @@ mod tests { slow.finish().unwrap(); let frame = consumer.read_frame().await.unwrap().unwrap(); assert_eq!(frame.timestamp, ts(10_000)); - let read = moq_clock::timeout(Duration::from_millis(50), consumer.read()).await; + let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await; assert!(matches!(read, Ok(Err(crate::Error::UnknownFormat(_)))), "{read:?}"); // The reader stays ended rather than resuming with the group's later frames. - let read = moq_clock::timeout(Duration::from_millis(50), consumer.read()).await; + let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await; assert!(matches!(read, Ok(Ok(None))), "{read:?}"); } @@ -3155,7 +3155,7 @@ mod tests { rewound.finish().unwrap(); // The reader looks ahead into both while it waits on the open group. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err() ); @@ -3205,7 +3205,7 @@ mod tests { write_failing(&mut later, None); // The reader looks ahead into the later group while it waits on the open one. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err() ); @@ -3238,7 +3238,7 @@ mod tests { group.abort(moq_net::Error::Cancel).unwrap(); track.finish().unwrap(); - let read = moq_clock::timeout(Duration::from_millis(50), consumer.read()).await; + let read = kio::clock::timeout(Duration::from_millis(50), consumer.read()).await; assert!(matches!(read, Ok(Err(crate::Error::UnknownFormat(_)))), "{read:?}"); } @@ -3334,15 +3334,15 @@ mod tests { write_group(&mut track, 1, &[ts(100_000)]); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; // Write group 2: recv_group fires, drops current buffer_until for group 1 write_group(&mut track, 2, &[ts(200_000)]); - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; group0.finish().unwrap(); track.finish().unwrap(); }); - let frames = moq_clock::timeout(Duration::from_secs(2), async { + let frames = kio::clock::timeout(Duration::from_secs(2), async { let mut frames = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { frames.push(frame); @@ -3422,11 +3422,11 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; group0.finish().unwrap(); }); - let frames = moq_clock::timeout(Duration::from_secs(2), async { + let frames = kio::clock::timeout(Duration::from_secs(2), async { let mut frames = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { frames.push(frame); @@ -3471,7 +3471,7 @@ mod tests { .unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; Container::Legacy(crate::container::Kind::Data) .write( &mut group7, @@ -3487,7 +3487,7 @@ mod tests { track.finish().unwrap(); }); - let _frames = moq_clock::timeout(Duration::from_secs(2), async { + let _frames = kio::clock::timeout(Duration::from_secs(2), async { let mut frames = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { frames.push(frame); @@ -3516,7 +3516,7 @@ mod tests { // Group 5 is open and within budget: its frames may still arrive, so wait. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "an open frameless group within budget must be waited for" @@ -3549,7 +3549,7 @@ mod tests { // While group 1 is open its frames may still come, so the consumer waits. assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "an open frameless group must be waited for" @@ -3557,7 +3557,7 @@ mod tests { // The abort (an eviction) settles it, and the finished track ends cleanly. group1.abort(moq_net::Error::Old).unwrap(); - let end = moq_clock::timeout(Duration::from_millis(200), consumer.read()) + let end = kio::clock::timeout(Duration::from_millis(200), consumer.read()) .await .expect("an aborted frameless group must not park the consumer"); assert!(end.unwrap().is_none(), "the track ends cleanly"); @@ -3581,7 +3581,7 @@ mod tests { track.finish().unwrap(); assert!( - moq_clock::timeout(Duration::from_millis(50), consumer.read()) + kio::clock::timeout(Duration::from_millis(50), consumer.read()) .await .is_err(), "the open head group is within budget and must be waited for" @@ -3628,7 +3628,7 @@ mod tests { let mut micros = Vec::new(); for _ in 0..2 { - let frame = moq_clock::timeout(Duration::from_millis(200), consumer.read_frame()) + let frame = kio::clock::timeout(Duration::from_millis(200), consumer.read_frame()) .await .expect("the open track still delivers the later range") .unwrap() @@ -3692,7 +3692,7 @@ mod tests { // group is served, and nothing else arrives. write_group(&mut track, 100, &[ts(3_000_000)]); - let frame = moq_clock::timeout(Duration::from_millis(200), consumer.read_frame()) + let frame = kio::clock::timeout(Duration::from_millis(200), consumer.read_frame()) .await .expect("an unfloored join must not wait out a gap below the served start") .unwrap() @@ -3728,7 +3728,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; group0.finish().unwrap(); }); @@ -3763,7 +3763,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; group0.finish().unwrap(); }); @@ -3802,7 +3802,7 @@ mod tests { track.finish().unwrap(); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; group0.finish().unwrap(); }); @@ -3928,13 +3928,13 @@ mod tests { write_group(&mut track, 0, &[ts(0)]); let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; write_group(&mut track, 1, &[ts(30_000)]); - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; track.finish().unwrap(); }); - let frames = moq_clock::timeout(Duration::from_secs(2), async { + let frames = kio::clock::timeout(Duration::from_secs(2), async { let mut frames = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { frames.push(frame); @@ -4033,7 +4033,7 @@ mod tests { track.finish().unwrap(); - let frames = moq_clock::timeout(Duration::from_secs(2), async { continuous_frames(&mut consumer).await }) + let frames = kio::clock::timeout(Duration::from_secs(2), async { continuous_frames(&mut consumer).await }) .await .expect("consumer hung — duration skip regression"); @@ -4092,12 +4092,12 @@ mod tests { // A second frame lands on group 0 and finishes it after the consumer has // had a chance to (incorrectly) skip. let finisher = tokio::spawn(async move { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; write_duration_frame(&mut group0, ts(20_000), ts(10_000)); group0.finish().unwrap(); }); - let frames = moq_clock::timeout(Duration::from_secs(2), async { + let frames = kio::clock::timeout(Duration::from_secs(2), async { let mut frames = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { frames.push(frame); @@ -4130,7 +4130,7 @@ mod tests { }], ) .unwrap(); - let frame = moq_clock::timeout(Duration::from_secs(1), consumer.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), consumer.read_frame()) .await .unwrap() .unwrap() @@ -4170,7 +4170,7 @@ mod tests { let slack = 4 * std::mem::size_of::>() + 1024; let mut reads = Vec::new(); loop { - let read = moq_clock::timeout(Duration::from_secs(5), consumer.read()) + let read = kio::clock::timeout(Duration::from_secs(5), consumer.read()) .await .expect("consumer hung") .unwrap(); @@ -4552,7 +4552,7 @@ mod tests { } /// A paused payload reader must not retain metadata for cache entries that were evicted. - #[moq_clock::test] + #[kio::test] async fn receiving_under_backpressure_releases_aborted_group_handles() { let track = track_producer("backpressured", timed()); let mut consumer = Consumer::new( @@ -4584,7 +4584,7 @@ mod tests { } /// A finished track may still have bytes in flight on a group already received. - #[moq_clock::test] + #[kio::test] async fn received_input_waits_for_group_fin_without_consuming_payload() { let mut track = track_producer("finite", timed()); let mut consumer = Consumer::new( diff --git a/rs/moq-mux/src/container/decode.rs b/rs/moq-mux/src/container/decode.rs index 122a176cbab..a12813e770f 100644 --- a/rs/moq-mux/src/container/decode.rs +++ b/rs/moq-mux/src/container/decode.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; /// The largest supported reorder span in 90 kHz ticks. pub(crate) const MAX_REORDER: u64 = 2 * 90_000; diff --git a/rs/moq-mux/src/container/flv/export.rs b/rs/moq-mux/src/container/flv/export.rs index 668ce16d331..93e1d71e23b 100644 --- a/rs/moq-mux/src/container/flv/export.rs +++ b/rs/moq-mux/src/container/flv/export.rs @@ -182,7 +182,7 @@ struct FlvTrack { source: ExportSource, pending: Option>, /// When the source was last empty, bounding the next frame's arrival. - empty: moq_clock::Instant, + empty: kio::clock::Instant, finished: bool, /// The FLV payload shape (legacy CodecID vs enhanced FourCC) to mux this /// track as, fixed from its catalog codec when it's bound. @@ -209,7 +209,7 @@ impl FlvTrack { fn rebind(&mut self, source: ExportSource) { self.source = source.continuing(&self.source); self.finished = false; - self.empty = moq_clock::now(); + self.empty = kio::clock::now(); } /// The tag timestamp of a frame presented at `pts` on the tag clock, on the inferred clock. @@ -226,7 +226,7 @@ impl FlvTrack { fn start_group( &mut self, key: (u8, usize), - arrived: moq_clock::Instant, + arrived: kio::clock::Instant, shift: u32, jitter: &mut crate::jitter::Buffer<(u8, usize), Tag>, ) -> anyhow::Result<()> { @@ -244,7 +244,7 @@ impl FlvTrack { fn release( &mut self, key: (u8, usize), - settled: Option, + settled: Option, shift: u32, flush: bool, jitter: &mut crate::jitter::Buffer<(u8, usize), Tag>, @@ -446,7 +446,7 @@ impl Export { } #[cfg(test)] - pub(super) fn next_deadline(&self) -> Option { + pub(super) fn next_deadline(&self) -> Option { self.jitter.next_deadline() } @@ -499,7 +499,7 @@ impl Export { break; } Poll::Pending => { - track.empty = moq_clock::now(); + track.empty = kio::clock::now(); break; } }; @@ -509,7 +509,7 @@ impl Export { } crate::jitter::Arrival { arrived: track.empty, - read: moq_clock::now(), + read: kio::clock::now(), decode: frame.timestamp.into(), restart: track.source.markers(), sync: kind == 1 || frame.keyframe, @@ -679,7 +679,7 @@ impl Export { track_id, source, pending: None, - empty: moq_clock::now(), + empty: kio::clock::now(), finished: false, flavor, fallback_description, @@ -728,7 +728,7 @@ impl Export { track_id, source, pending: None, - empty: moq_clock::now(), + empty: kio::clock::now(), finished: false, flavor, fallback_description: None, diff --git a/rs/moq-mux/src/container/flv/export_test.rs b/rs/moq-mux/src/container/flv/export_test.rs index ffbb159f006..020b1f64dd2 100644 --- a/rs/moq-mux/src/container/flv/export_test.rs +++ b/rs/moq-mux/src/container/flv/export_test.rs @@ -131,13 +131,13 @@ async fn drain_export(mut exporter: Export, import let mut exported = Vec::new(); let mut importer = Some(importer); for _ in 0..64 { - match moq_clock::timeout(Duration::from_millis(100), exporter.next()).await { + match kio::clock::timeout(Duration::from_millis(100), exporter.next()).await { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => break, Ok(Err(e)) => panic!("exporter error: {e}"), Err(_) => { if let Some(deadline) = exporter.next_deadline() { - tokio::time::advance(deadline.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(deadline.saturating_duration_since(kio::clock::now())).await; } else { importer = None; // No scheduled frames remain; close the broadcast. } @@ -618,7 +618,7 @@ async fn drain_to_end(mut exporter: Export, keepal let mut exported = Vec::new(); let mut keepalive = Some(keepalive); for _ in 0..64 { - match moq_clock::timeout(Duration::from_millis(100), exporter.next()).await { + match kio::clock::timeout(Duration::from_millis(100), exporter.next()).await { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => break, Ok(Err(e)) => panic!("exporter error: {e}"), @@ -897,7 +897,7 @@ async fn export_rebinds_to_a_better_rendition_before_the_header() { let mut exporter = open_export(crate::source::announced(&consumer).await).await; assert!( - moq_clock::timeout(Duration::from_millis(100), exporter.next()) + kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .is_err(), "the header waits on the small rendition's config" @@ -935,7 +935,7 @@ async fn export_rebinds_to_a_better_rendition_before_the_header() { }) .unwrap(); - let header = moq_clock::timeout(Duration::from_millis(100), exporter.next()) + let header = kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .expect("the header follows the better rendition") .unwrap() @@ -945,7 +945,7 @@ async fn export_rebinds_to_a_better_rendition_before_the_header() { "the sequence header carries the better rendition's avcC" ); - let frame = moq_clock::timeout(Duration::from_millis(100), exporter.next()) + let frame = kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .expect("the better rendition's frame follows") .unwrap() @@ -1019,7 +1019,7 @@ async fn export_unbinds_a_rendition_disabled_before_the_header() { let mut exporter = open_export(crate::source::announced(&consumer).await).await; assert!( - moq_clock::timeout(Duration::from_millis(100), exporter.next()) + kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .is_err(), "the header waits on the small rendition's config" @@ -1036,14 +1036,14 @@ async fn export_unbinds_a_rendition_disabled_before_the_header() { .unwrap() .enabled = false; assert!( - moq_clock::timeout(Duration::from_millis(100), exporter.next()) + kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .is_err(), "nothing enabled" ); small.write(crate::container::test_util::video_frame(0, true)).unwrap(); assert!( - moq_clock::timeout(Duration::from_millis(100), exporter.next()) + kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .is_err(), "the disabled rendition's keyframe writes no header" @@ -1065,7 +1065,7 @@ async fn export_unbinds_a_rendition_disabled_before_the_header() { keyframe: true, }) .unwrap(); - let header = moq_clock::timeout(Duration::from_millis(100), exporter.next()) + let header = kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .expect("the header follows the enabled rendition") .unwrap() @@ -1143,7 +1143,7 @@ async fn export_rebinds_to_a_better_audio_rendition_before_the_header() { let mut exporter = open_export(crate::source::announced(&consumer).await).await; assert!( - moq_clock::timeout(Duration::from_millis(100), exporter.next()) + kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .is_err(), "the header waits on the video config" @@ -1174,7 +1174,7 @@ async fn export_rebinds_to_a_better_audio_rendition_before_the_header() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); - let header = moq_clock::timeout(Duration::from_millis(100), exporter.next()) + let header = kio::clock::timeout(Duration::from_millis(100), exporter.next()) .await .expect("the header resolves") .unwrap() @@ -1552,13 +1552,13 @@ async fn drain_until_idle( out: &mut Vec, ) -> Option> { loop { - match moq_clock::timeout(Duration::from_millis(100), exporter.next()).await { + match kio::clock::timeout(Duration::from_millis(100), exporter.next()).await { Ok(Ok(Some(chunk))) => out.extend_from_slice(&chunk), Ok(Ok(None)) => return Some(Ok(())), Ok(Err(e)) => return Some(Err(e)), Err(_) => { let deadline = exporter.next_deadline()?; - tokio::time::advance(deadline.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(deadline.saturating_duration_since(kio::clock::now())).await; } } } @@ -1702,7 +1702,7 @@ async fn a_track_leaving_the_catalog_is_read_to_its_end() { async fn drain_exporter_chunks(mut exporter: Export, chunks: usize) -> Vec { let mut exported = Vec::new(); for _ in 0..chunks { - match moq_clock::timeout(Duration::from_millis(100), exporter.next()).await { + match kio::clock::timeout(Duration::from_millis(100), exporter.next()).await { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => panic!("exporter ended early"), Ok(Err(e)) => panic!("exporter error: {e}"), @@ -1725,7 +1725,7 @@ async fn configured_delay_holds_live_frames() { assert!(export.next().await.unwrap().is_some(), "container header"); live.track.write(raw_frame(0, &[0xde, 0xad], true)).unwrap(); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .is_err(), "the release delay must hold a live frame instead of emitting on arrival" @@ -1743,7 +1743,7 @@ async fn delay_drops_late_frames_and_drains_the_final_frame() { let delay = std::time::Duration::from_millis(100); let mut export = super::Export::new(live.source().await, live.catalog_stream().await).with_delay(delay); export.next().await.unwrap().unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); live.track.write(raw_frame(0, b"first", true)).unwrap(); let first = export.next().await.unwrap().unwrap(); assert!(first.windows(5).any(|part| part == b"first")); diff --git a/rs/moq-mux/src/container/flv/import_test.rs b/rs/moq-mux/src/container/flv/import_test.rs index d3598f51206..5099833b942 100644 --- a/rs/moq-mux/src/container/flv/import_test.rs +++ b/rs/moq-mux/src/container/flv/import_test.rs @@ -203,7 +203,7 @@ async fn public_container_preserves_loc_for_flv() { track, crate::catalog::hang::Container::Loc(crate::container::Kind::Data), ); - let frame = moq_clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() @@ -853,7 +853,7 @@ struct Imported { video: String, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// Why a chunk was refused, if one was. refused: Option, } @@ -866,7 +866,7 @@ async fn import(chunks: &[Vec]) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut importer = Import::new(broadcast, catalog.reserve()); - let before = moq_clock::wall(); + let before = kio::clock::wall(); let mut after = before; let mut refused = None; for (i, chunk) in chunks.iter().enumerate() { @@ -875,7 +875,7 @@ async fn import(chunks: &[Vec]) -> Imported { break; } if i == 0 { - after = moq_clock::wall(); + after = kio::clock::wall(); } } importer.finish().unwrap(); diff --git a/rs/moq-mux/src/container/fmp4/export_test.rs b/rs/moq-mux/src/container/fmp4/export_test.rs index fce60d86547..2d97ebd1793 100644 --- a/rs/moq-mux/src/container/fmp4/export_test.rs +++ b/rs/moq-mux/src/container/fmp4/export_test.rs @@ -215,7 +215,7 @@ async fn dimensionless_video_waits_for_catalog_geometry() { live.track.write(raw_frame(0, &[0x31, 0x00, 0x00], true)).unwrap(); let mut exporter = crate::container::fmp4::Export::new(live.source().await, live.catalog_stream().await); - let pending = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()).await; + let pending = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()).await; assert!( pending.is_err(), "exporter emitted an init without geometry: {pending:?}" @@ -427,7 +427,7 @@ async fn cmaf_source_to_cmaf_export_passthrough() { .expect("catalog consumer"); let mut exporter = crate::container::fmp4::Export::new(crate::source::announced(&consumer).await, catalog_stream); - let init = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let init = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -488,7 +488,7 @@ async fn single_track_export_init_matches_fragment_track_id() { let mut exporter = crate::container::fmp4::Export::new(crate::source::announced(&consumer).await, selected) .with_max_delay(RECORDING_MAX_DELAY); - let init = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let init = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -497,7 +497,7 @@ async fn single_track_export_init_matches_fragment_track_id() { // A fragment is a group, and ending the track is what closes the last one. The // next non-init fragment is a moof+mdat for the same (only) track. importer.finish().unwrap(); - let fragment = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let fragment = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -1270,7 +1270,7 @@ async fn drain_now( exporter: &mut crate::container::fmp4::Export, ) -> Vec { let mut fragments = Vec::new(); - while let Ok(next) = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { + while let Ok(next) = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { match next.expect("exporter failed") { Some(chunk) => fragments.push(chunk.fragment().expect("a media fragment after the init")), None => break, @@ -1350,7 +1350,7 @@ fn wait_for_sps(live: &mut Live) { async fn chunk_now( exporter: &mut crate::container::fmp4::Export, ) -> crate::container::fmp4::Chunk { - moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) + kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) .await .expect("waited for a successor frame") .expect("exporter failed") @@ -1399,7 +1399,7 @@ fn samples_per_track(fragments: &[crate::container::fmp4::Fragment]) -> std::col /// The first error the exporter returns, skipping any chunks before it. async fn error_now(exporter: &mut crate::container::fmp4::Export) -> crate::Error { loop { - match moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) + match kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) .await .expect("the exporter stalled instead of failing") { @@ -1426,7 +1426,7 @@ async fn audio_before_the_first_keyframe_is_kept() { // Two seconds of audio, published live with no video yet. for i in 0..20u64 { write_audio(&mut audio, i * 100_000, 5); - let pending = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; + let pending = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; assert!(pending.is_err(), "a chunk before the video could be described"); } live.track.write(video_frame(2_000_000, true)).unwrap(); @@ -1629,7 +1629,7 @@ async fn an_opus_head_before_the_init_is_written() { write_audio(&mut audio, 0, 6); let mut exporter = crate::container::fmp4::Export::new(live.source().await, live.catalog_stream().await); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) + kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()) .await .is_err(), "the init waits for the video" @@ -2021,7 +2021,7 @@ async fn a_track_that_never_describes_itself_fails() { assert!(second < 40, "the queue outgrew its bound"); write_audio(&mut audio, second * 1_000_000, 50); second += 1; - match moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { + match kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { Err(_) => continue, Ok(Ok(chunk)) => panic!("a chunk before the video could be described: {chunk:?}"), Ok(Err(err)) => break err, @@ -2056,7 +2056,7 @@ async fn an_uncut_audio_backlog_is_bounded() { .unwrap(); } second += 1; - match moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { + match kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await { Err(_) => continue, Ok(Ok(chunk)) => panic!("a chunk before the video could be described: {chunk:?}"), Ok(Err(err)) => break err, @@ -2101,7 +2101,7 @@ async fn hevc_main10_is_described_from_its_sps() { catalog.modify().unwrap().video.renditions.insert(name, config); }); let mut exporter = crate::container::fmp4::Export::new(live.source().await, live.catalog_stream().await); - let pending = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; + let pending = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; assert!(pending.is_err(), "an init before the SPS: {pending:?}"); let mut keyframe = BytesMut::new(); @@ -2320,7 +2320,7 @@ async fn high10_waits_for_its_sps() { let mut live = Live::avc3(); wait_for_sps(&mut live); let mut exporter = crate::container::fmp4::Export::new(live.source().await, live.catalog_stream().await); - let pending = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; + let pending = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; assert!(pending.is_err(), "an init before the SPS: {pending:?}"); live.track.write(video_frame(0, true)).unwrap(); @@ -2381,7 +2381,7 @@ async fn annexb_without_dimensions_waits_for_the_sps() { catalog.modify().unwrap().video.renditions.insert(name, config); }); let mut exporter = crate::container::fmp4::Export::new(live.source().await, live.catalog_stream().await); - let pending = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; + let pending = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next_chunk()).await; assert!(pending.is_err(), "an init before dimensions: {pending:?}"); let sps = crate::codec::h264::fixtures::SPS_IPB; diff --git a/rs/moq-mux/src/container/fmp4/import_test.rs b/rs/moq-mux/src/container/fmp4/import_test.rs index 55222d4191d..319dde90631 100644 --- a/rs/moq-mux/src/container/fmp4/import_test.rs +++ b/rs/moq-mux/src/container/fmp4/import_test.rs @@ -2597,7 +2597,7 @@ struct Imported { video: String, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// Where the video's first HLS segment starts. record: moq_net::Timestamp, /// Why a chunk was refused, if one was. @@ -2618,7 +2618,7 @@ async fn import_session(chunks: &[Vec]) -> Imported { let video = snapshot.video.renditions.keys().next().unwrap().clone(); let mut records = subscribe(&consumer, &video).await; - let before = moq_clock::wall(); + let before = kio::clock::wall(); let mut after = before; let mut refused = None; for (i, chunk) in chunks.iter().enumerate() { @@ -2627,7 +2627,7 @@ async fn import_session(chunks: &[Vec]) -> Imported { break; } if i == 0 { - after = moq_clock::wall(); + after = kio::clock::wall(); } } fmp4.finish().unwrap(); @@ -3498,7 +3498,7 @@ async fn ttml_samples_become_timed_text_with_source_metadata() { /// The source joins a catalog clock another input already fixed, so its TTML times move with it. #[tokio::test(start_paused = true)] async fn ttml_follows_a_shifted_source_clock() { - let wall = moq_clock::wall(); + let wall = kio::clock::wall(); let mut broadcast = moq_net::broadcast::Info::new().produce(); let consumer = broadcast.consume(); let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); diff --git a/rs/moq-mux/src/container/mkv/export.rs b/rs/moq-mux/src/container/mkv/export.rs index 4ae587d6fd4..ff3541df7d7 100644 --- a/rs/moq-mux/src/container/mkv/export.rs +++ b/rs/moq-mux/src/container/mkv/export.rs @@ -83,9 +83,9 @@ struct MkvTrack { source: ExportSource, pending: Option>, // When the source was subscribed: nothing it delivers reached the export before then. - subscribed: moq_clock::Instant, + subscribed: kio::clock::Instant, // The latest arrival read from the source, which settles the frames held for their DTS. - latest: moq_clock::Instant, + latest: kio::clock::Instant, finished: bool, track_number: u64, kind: TrackKind, @@ -107,8 +107,8 @@ impl MkvTrack { reorder: None, source, pending: None, - subscribed: moq_clock::now(), - latest: moq_clock::Instant::ZERO, + subscribed: kio::clock::now(), + latest: kio::clock::Instant::ZERO, finished: false, track_number, kind, @@ -131,7 +131,7 @@ impl MkvTrack { self.reorder = None; self.source = source.continuing(&self.source); self.finished = false; - self.subscribed = moq_clock::now(); + self.subscribed = kio::clock::now(); self.moved = true; Ok(()) } @@ -453,7 +453,7 @@ impl Export { } #[cfg(test)] - pub(super) fn next_deadline(&self) -> Option { + pub(super) fn next_deadline(&self) -> Option { self.jitter.next_deadline() } @@ -535,7 +535,7 @@ impl Export { } crate::jitter::Arrival { arrived, - read: moq_clock::now(), + read: kio::clock::now(), decode: frame.timestamp.into(), restart: track.source.markers(), sync: track.kind == TrackKind::Audio || frame.keyframe, diff --git a/rs/moq-mux/src/container/mkv/export_test.rs b/rs/moq-mux/src/container/mkv/export_test.rs index 4d28b619f3a..ada094e8118 100644 --- a/rs/moq-mux/src/container/mkv/export_test.rs +++ b/rs/moq-mux/src/container/mkv/export_test.rs @@ -158,7 +158,7 @@ async fn export_header_roundtrip_vp9_opus() { let mut exporter = crate::container::mkv::Export::new(crate::source::announced(&consumer).await, catalog_stream); // First `next()` should give us the header (EBML + Segment-start + Info + Tracks). - let header = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let header = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -385,7 +385,7 @@ async fn export_header_roundtrip_mp3() { .expect("catalog consumer"); let mut exporter = crate::container::mkv::Export::new(crate::source::announced(&consumer).await, catalog_stream); - let header = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let header = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -466,7 +466,7 @@ async fn export_waits_for_catalog_before_header() { // next() must remain pending (timing out), not surface a "no catalog // snapshot" error from a vacuously-ready empty track set. - let result = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()).await; + let result = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()).await; assert!( result.is_err(), "exporter should stay pending before any rendition arrives, got {result:?}" @@ -499,7 +499,7 @@ async fn export_derives_video_geometry_before_header() { live.track.finish().unwrap(); let mut exporter = crate::container::mkv::Export::new(live.source().await, live.catalog_stream().await); - let header = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let header = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out") .expect("exporter result") @@ -544,14 +544,14 @@ async fn export_emits_blocks_for_each_frame() { let mut importer = Some(importer); for _ in 0..32 { - let next = moq_clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; + let next = kio::clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; match next { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => break, Ok(Err(e)) => panic!("exporter error: {e}"), Err(_) => { if let Some(deadline) = exporter.next_deadline() { - tokio::time::advance(deadline.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(deadline.saturating_duration_since(kio::clock::now())).await; } else { importer = None; } @@ -619,7 +619,7 @@ async fn export_rejects_cmaf_track() { }); let mut exporter = crate::container::mkv::Export::new(live.source().await, live.catalog_stream().await); - let result = moq_clock::timeout(std::time::Duration::from_secs(1), exporter.next()) + let result = kio::clock::timeout(std::time::Duration::from_secs(1), exporter.next()) .await .expect("exporter timed out"); @@ -649,7 +649,7 @@ async fn export_avc3_source_synthesizes_avcc_and_length_prefixes() { let mut live = Some(live); for _ in 0..32 { - let next = moq_clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; + let next = kio::clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; match next { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => break, @@ -787,14 +787,14 @@ async fn export_fragment_duration_batches_blocks() { let mut importer = Some(importer); for _ in 0..32 { - let next = moq_clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; + let next = kio::clock::timeout(std::time::Duration::from_millis(100), exporter.next()).await; match next { Ok(Ok(Some(chunk))) => exported.extend_from_slice(&chunk), Ok(Ok(None)) => break, Ok(Err(e)) => panic!("exporter error: {e}"), Err(_) => { if let Some(deadline) = exporter.next_deadline() { - tokio::time::advance(deadline.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(deadline.saturating_duration_since(kio::clock::now())).await; } else { importer = None; } @@ -843,7 +843,7 @@ async fn reconfigured_zero_duration_drains_open_cluster() { // Default per-GOP clustering: both frames land in one open cluster. let mut exporter = crate::container::mkv::Export::new(live.source().await, live.catalog_stream().await); let header = chunk_now(&mut exporter).await; - moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next()) .await .expect_err("the GOP cluster must stay open while the producer is live"); @@ -862,7 +862,7 @@ async fn reconfigured_zero_duration_drains_open_cluster() { /// The next chunk, required to be ready without another frame arriving. async fn chunk_now(exporter: &mut crate::container::mkv::Export) -> Bytes { - moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next()) .await .expect("waited for a successor frame") .expect("exporter failed") @@ -872,7 +872,7 @@ async fn chunk_now(exporter: &mut crate::container::mkv::Export) -> crate::Result> { let mut out = Vec::new(); - while let Ok(next) = moq_clock::timeout(std::time::Duration::from_millis(1), exporter.next()).await { + while let Ok(next) = kio::clock::timeout(std::time::Duration::from_millis(1), exporter.next()).await { match next? { Some(chunk) => out.extend_from_slice(&chunk), None => break, @@ -1127,7 +1127,7 @@ async fn configured_delay_holds_live_frames() { assert!(export.next().await.unwrap().is_some(), "container header"); live.track.write(raw_frame(0, &[0xde, 0xad], true)).unwrap(); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), export.next()) + kio::clock::timeout(std::time::Duration::from_millis(1), export.next()) .await .is_err(), "the release delay must hold a live frame instead of emitting on arrival" @@ -1147,7 +1147,7 @@ async fn delay_drops_late_frames_and_drains_the_final_frame() { .with_delay(delay) .with_fragment_duration(std::time::Duration::ZERO); export.next().await.unwrap().unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); live.track.write(raw_frame(0, b"first", true)).unwrap(); let first = export.next().await.unwrap().unwrap(); assert!(first.windows(5).any(|part| part == b"first")); diff --git a/rs/moq-mux/src/container/mkv/import.rs b/rs/moq-mux/src/container/mkv/import.rs index 944d55238ee..431ec0720cf 100644 --- a/rs/moq-mux/src/container/mkv/import.rs +++ b/rs/moq-mux/src/container/mkv/import.rs @@ -1609,7 +1609,7 @@ mod tests { // The Legacy timestamp prefix and the first chunk are readable while the rest is in flight. let mut read = Vec::new(); while read.len() < 1 + 1024 { - let chunk = moq_clock::timeout(WAIT, frame.read_chunk()).await.unwrap().unwrap(); + let chunk = kio::clock::timeout(WAIT, frame.read_chunk()).await.unwrap().unwrap(); read.extend_from_slice(&chunk.expect("the frame is still open")); } assert_eq!(read, [&[0][..], &[1; 1024]].concat()); @@ -1618,7 +1618,7 @@ mod tests { import.decode(&[1; 1024]).unwrap(); assert!(import.reader.retained() <= 12, "{}", import.reader.retained()); } - while let Some(chunk) = moq_clock::timeout(WAIT, frame.read_chunk()).await.unwrap().unwrap() { + while let Some(chunk) = kio::clock::timeout(WAIT, frame.read_chunk()).await.unwrap().unwrap() { read.extend_from_slice(&chunk); } assert_eq!(read.len(), 1 + SIZE); @@ -1810,7 +1810,7 @@ mod tests { let mut frame = first_frame(&catalog, &consumer).await; assert!(matches!(import.finish(), Err(crate::Error::Mkv(Error::Truncated)))); // The importer is still owned, and the frame fails rather than waiting on it. - let read = moq_clock::timeout(WAIT, frame.read_all()).await.unwrap(); + let read = kio::clock::timeout(WAIT, frame.read_all()).await.unwrap(); assert!(read.is_err(), "a truncated frame must not read as complete: {read:?}"); drop(import); } @@ -1827,7 +1827,7 @@ mod tests { true => std::mem::drop(import), false => import.abort(moq_net::Error::Cancel), } - let read = moq_clock::timeout(WAIT, frame.read_all()).await.unwrap(); + let read = kio::clock::timeout(WAIT, frame.read_all()).await.unwrap(); assert!(read.is_err(), "a frame cut short must not read as complete: {read:?}"); } } diff --git a/rs/moq-mux/src/container/mkv/import_test.rs b/rs/moq-mux/src/container/mkv/import_test.rs index b1e9deb6f8c..37d34517ec2 100644 --- a/rs/moq-mux/src/container/mkv/import_test.rs +++ b/rs/moq-mux/src/container/mkv/import_test.rs @@ -838,7 +838,7 @@ async fn public_container_preserves_loc_for_mkv() { track, crate::catalog::hang::Container::Loc(crate::container::Kind::Data), ); - let frame = moq_clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() @@ -1002,7 +1002,7 @@ struct Imported { published: std::collections::BTreeMap>, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// Why a chunk was refused, if one was. refused: Option, } @@ -1015,7 +1015,7 @@ async fn import_chunked(data: &[u8], chunk: usize) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut mkv = crate::container::mkv::Import::new(broadcast, catalog.reserve()); - let before = moq_clock::wall(); + let before = kio::clock::wall(); let mut refused = None; for piece in data.chunks(chunk) { if let Err(err) = mkv.decode(piece) { @@ -1023,7 +1023,7 @@ async fn import_chunked(data: &[u8], chunk: usize) -> Imported { break; } } - let after = moq_clock::wall(); + let after = kio::clock::wall(); mkv.finish().unwrap(); let snapshot = catalog.snapshot(); diff --git a/rs/moq-mux/src/container/producer.rs b/rs/moq-mux/src/container/producer.rs index ec668a1b0cb..0e9d39d633a 100644 --- a/rs/moq-mux/src/container/producer.rs +++ b/rs/moq-mux/src/container/producer.rs @@ -1809,7 +1809,7 @@ mod tests { assert!(producer.cut(Some(Timestamp::from_micros(10_000).unwrap())).is_err()); assert!(!producer.needs_keyframe()); assert!( - moq_clock::timeout(std::time::Duration::from_millis(1), group.read_frame()) + kio::clock::timeout(std::time::Duration::from_millis(1), group.read_frame()) .await .is_err() ); diff --git a/rs/moq-mux/src/container/source.rs b/rs/moq-mux/src/container/source.rs index de2cdf1dc9e..f0805a0db38 100644 --- a/rs/moq-mux/src/container/source.rs +++ b/rs/moq-mux/src/container/source.rs @@ -892,7 +892,7 @@ mod tests { .unwrap() .unwrap(); let mut read = async || { - moq_clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) + kio::clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) .await .ok() .map(|frame| frame.unwrap().map(|frame| frame.timestamp.as_micros())) @@ -919,7 +919,7 @@ mod tests { let mut late = ExportSource::for_audio(&source, "late", &config, Duration::from_secs(10)) .unwrap() .unwrap(); - let ended = moq_clock::timeout(Duration::from_secs(1), kio::wait(|waiter| late.poll_read(waiter))).await; + let ended = kio::clock::timeout(Duration::from_secs(1), kio::wait(|waiter| late.poll_read(waiter))).await; assert!( matches!(ended, Ok(Ok(None))), "{:?}", @@ -951,7 +951,7 @@ mod tests { .unwrap(); // Subscribe before anything is written, so the failure and the instance's end arrive // together. - let settle = moq_clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))); + let settle = kio::clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))); assert!(settle.await.is_err(), "nothing is written yet"); let mut group = track.append_group().unwrap(); let held = match failure { @@ -972,10 +972,10 @@ mod tests { } }; drop(sibling); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; assert!(export.instance_ended(&kio::Waiter::noop()), "the instance has gone"); - let read = moq_clock::timeout(Duration::from_secs(1), kio::wait(|waiter| export.poll_read(waiter))) + let read = kio::clock::timeout(Duration::from_secs(1), kio::wait(|waiter| export.poll_read(waiter))) .await .expect("the read settles"); assert!( @@ -1013,7 +1013,7 @@ mod tests { .unwrap() .unwrap(); let mut read = async || { - moq_clock::timeout(Duration::from_secs(1), kio::wait(|waiter| export.poll_read(waiter))) + kio::clock::timeout(Duration::from_secs(1), kio::wait(|waiter| export.poll_read(waiter))) .await .expect("the read settles") .unwrap() @@ -1116,7 +1116,7 @@ mod tests { group.finish().unwrap(); }; let mut read = async || { - moq_clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) + kio::clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) .await .ok() .map(|frame| frame.unwrap().map(|frame| frame.timestamp.as_micros())) @@ -1124,7 +1124,7 @@ mod tests { assert_eq!(read().await, None, "subscribed, with nothing published yet"); write(0); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; // A PES carrying several frames publishes them in one pass, before the publisher's // session runs again, and the export reads the first group in the meantime. for sequence in 1..4 { @@ -1193,7 +1193,7 @@ mod tests { // About two seconds of it, so the budget's backlog reaches back about 450 ms. for n in 0..17 { pes(n); - moq_clock::sleep(Duration::from_millis(120)).await; + kio::clock::sleep(Duration::from_millis(120)).await; } let mut export = ExportSource::for_audio(&source, "audio", &audio(None), Duration::from_millis(450)) @@ -1201,7 +1201,7 @@ mod tests { .unwrap() .live(); let mut read = async || { - moq_clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) + kio::clock::timeout(Duration::from_millis(100), kio::wait(|waiter| export.poll_read(waiter))) .await .ok() .map(|frame| frame.unwrap().map(|frame| frame.timestamp.as_micros())) @@ -1213,7 +1213,7 @@ mod tests { } // The next PES moves the live edge on before the rest of the backlog lands. pes(17); - moq_clock::sleep(Duration::from_millis(120)).await; + kio::clock::sleep(Duration::from_millis(120)).await; pes(18); held.open(); while let Some(Some(timestamp)) = read().await { @@ -1254,7 +1254,7 @@ mod tests { .unwrap() .continuing(&previous); let mut poll = async || { - moq_clock::timeout(Duration::from_millis(100), kio::wait(|waiter| next.poll_read(waiter))).await + kio::clock::timeout(Duration::from_millis(100), kio::wait(|waiter| next.poll_read(waiter))).await }; // A keyframe at zero then deltas up to 967 ms, past 900 ms but no place to start. diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index eb5973aa253..d1cd44333bc 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -257,7 +257,7 @@ pub(crate) async fn published( let track = consumer.track(&name).unwrap().subscribe(replay).await.unwrap(); let mut reader = crate::container::Consumer::new(track, container); let mut timestamps = Vec::new(); - while let Some(frame) = moq_clock::timeout(std::time::Duration::from_secs(5), reader.read_frame()) + while let Some(frame) = kio::clock::timeout(std::time::Duration::from_secs(5), reader.read_frame()) .await .expect("the importer finished its tracks") .unwrap() diff --git a/rs/moq-mux/src/container/ts/damage.rs b/rs/moq-mux/src/container/ts/damage.rs index be10d694e54..9676a913628 100644 --- a/rs/moq-mux/src/container/ts/damage.rs +++ b/rs/moq-mux/src/container/ts/damage.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; -use moq_clock::Instant; +use kio::clock::Instant; use super::stats; @@ -28,7 +28,7 @@ impl Burst { impl Log { pub fn record(&mut self, pid: u16, error: &anyhow::Error) { - let now = moq_clock::now(); + let now = kio::clock::now(); self.flush(now); let first = match self.bursts.entry(pid) { std::collections::btree_map::Entry::Occupied(mut entry) => { @@ -122,7 +122,7 @@ mod tests { tokio::time::advance(stats::Log::INTERVAL / 2).await; log.record(97, &error); tokio::time::advance(stats::Log::INTERVAL / 2).await; - log.flush(moq_clock::now()); + log.flush(kio::clock::now()); // This PID is quiet for a full interval before the next global summary tick. tokio::time::advance(stats::Log::INTERVAL / 2).await; log.record(97, &error); diff --git a/rs/moq-mux/src/container/ts/export.rs b/rs/moq-mux/src/container/ts/export.rs index 4c94790fb08..26204530a82 100644 --- a/rs/moq-mux/src/container/ts/export.rs +++ b/rs/moq-mux/src/container/ts/export.rs @@ -122,8 +122,8 @@ where pending: Option>>, next_program: u64, active_program: u64, - follow_until: Option, - follow_timer: Option>>, + follow_until: Option, + follow_timer: Option>>, } /// Input and mux state belonging to one publisher instance. The release clock @@ -202,7 +202,7 @@ where /// edge: a test exporting a broadcast it wrote whole. replay: bool, /// Wakes the export when the next grid slot is due on the jitter buffer's clock. - slot_timer: Option>>, + slot_timer: Option>>, /// Output frames ready to hand out, one per grid slot, each with what it tells /// [`Export::stats`] once returned. queue: VecDeque<(Frame, Tally)>, @@ -261,9 +261,9 @@ struct Pending { cut: u64, /// When it landed in this node's cache ([`moq_net::frame::Frame::arrived`]), so a stall /// that holds the export back too does not hide that it came late. - arrived: moq_clock::Instant, + arrived: kio::clock::Instant, /// When it was read. - read: moq_clock::Instant, + read: kio::clock::Instant, } /// A frame waiting in the jitter buffer, with what it needs from the moment it was read. @@ -306,9 +306,9 @@ struct Track { pending: Option, /// When the source was subscribed. Nothing it delivers reached the export before then, /// however long the cache held it. - subscribed: moq_clock::Instant, + subscribed: kio::clock::Instant, /// The latest frame arrival or observed loss, which settles frames held for their DTS. - latest: moq_clock::Instant, + latest: kio::clock::Instant, /// The marker count the decode clock runs under. restart: u64, /// The marker, skip and cut counts of the sources the track read before this one, so the @@ -387,8 +387,8 @@ impl Track { key: TrackKey::default(), source, pending: None, - subscribed: moq_clock::now(), - latest: moq_clock::Instant::ZERO, + subscribed: kio::clock::now(), + latest: kio::clock::Instant::ZERO, restart: 0, base: (0, 0, 0), finished: false, @@ -529,7 +529,7 @@ impl Track { match self.source.poll_event(waiter)? { Poll::Ready(Some(Event::Frame { frame, arrived })) => { if is_video && frame.keyframe && input.waiting_for_header { - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "keyframe", now = ?moq_clock::now(), program = self.key.program, ?arrived); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "keyframe", now = ?kio::clock::now(), program = self.key.program, ?arrived); } let arrived = arrived.max(self.subscribed); // The frame settles what its group's end left held, so they are ready as it lands. @@ -548,7 +548,7 @@ impl Track { skip: self.base.1 + self.source.skips(), cut: self.base.2 + self.source.cuts(), arrived, - read: moq_clock::now(), + read: kio::clock::now(), }; // A new timeline must reach the reset before tune-in alignment can drop it. if let Some(start) = input.video_start @@ -818,8 +818,8 @@ impl Track { }; // Logical clocks can begin at zero. Shift both readings by the same representable amount so // their ordering survives even when the full replay lead would precede the clock's origin. - let ahead = ahead.min(arrived.duration_since(moq_clock::Instant::ZERO)); - let ahead = ahead.min(read.duration_since(moq_clock::Instant::ZERO)); + let ahead = ahead.min(arrived.duration_since(kio::clock::Instant::ZERO)); + let ahead = ahead.min(read.duration_since(kio::clock::Instant::ZERO)); let arrival = Arrival { arrived: arrived - ahead, read: read - ahead, @@ -1628,7 +1628,7 @@ where for (name, track) in &mut self.program.tracks { track.release(name, &mut self.jitter, true)?; } - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "commit-program", now = ?moq_clock::now(), old = self.program.id, new = ready.track.program, generation = ready.generation, pts = ?ready.item.frame.timestamp, key = ?ready.item.key, decode = ?ready.item.decode); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "commit-program", now = ?kio::clock::now(), old = self.program.id, new = ready.track.program, generation = ready.generation, pts = ?ready.item.frame.timestamp, key = ?ready.item.key, decode = ?ready.item.decode); self.jitter.commit(ready)?; break; } @@ -1994,7 +1994,7 @@ where } } if self.program.id != self.active_program && !self.jitter.has_pending() && !self.jitter.is_committed() { - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "prepared", now = ?moq_clock::now(), program = self.program.id, old = self.active_program, tracks = self.program.tracks.len(), video_start = ?self.program.video_start); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "prepared", now = ?kio::clock::now(), program = self.program.id, old = self.active_program, tracks = self.program.tracks.len(), video_start = ?self.program.video_start); self.jitter.start( self.program.tracks.values().map(|track| track.key.clone()), self.program.expected.clone(), @@ -2004,7 +2004,7 @@ where // Hand the held frames to the jitter buffer in arrival order, so the // earliest anchors its clock, then read on. - let mut held: Vec<(moq_clock::Instant, String)> = self + let mut held: Vec<(kio::clock::Instant, String)> = self .program .tracks .iter() @@ -2033,7 +2033,7 @@ where if !super::follower::left(&err) { return Err(err); } - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "left", now = ?moq_clock::now(), program = self.program.id, committed = self.jitter.is_committed(), %err); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "left", now = ?kio::clock::now(), program = self.program.id, committed = self.jitter.is_committed(), %err); if self.pending.is_none() { self.program.left = Some(err); } @@ -2047,12 +2047,12 @@ where return Ok(()); } - let expired = self.follow_until.is_some_and(|until| moq_clock::now() >= until); + let expired = self.follow_until.is_some_and(|until| kio::clock::now() >= until); if !expired { if let Some(until) = self.follow_until { let timer = self .follow_timer - .get_or_insert_with(|| Box::pin(moq_clock::sleep_until(until))); + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(until))); if timer.deadline() != until { timer.as_mut().reset(until); } @@ -2060,7 +2060,7 @@ where } return Ok(()); } - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow-expired", now = ?moq_clock::now(), program = self.program.id, committed = self.jitter.is_committed()); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow-expired", now = ?kio::clock::now(), program = self.program.id, committed = self.jitter.is_committed()); self.follow_timer = None; self.follow_until = None; self.program.catalog = None; @@ -2095,7 +2095,7 @@ where return Ok(()); } let mut next = self.pending.take().expect("checked above"); - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "adopt", now = ?moq_clock::now(), old = self.program.id, new = next.id, generation = ready.generation, old_pts = ?self.program.last_timestamp, new_pts = ?ready.item.frame.timestamp, new_key = ?ready.item.key); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "adopt", now = ?kio::clock::now(), old = self.program.id, new = next.id, generation = ready.generation, old_pts = ?self.program.last_timestamp, new_pts = ?ready.item.frame.timestamp, new_key = ?ready.item.key); let out = self .program .psi @@ -2472,7 +2472,7 @@ where track.base.1 += track.source.skips() + 1; track.base.2 += track.source.cuts() + 1; track.source = source; - track.subscribed = moq_clock::now(); + track.subscribed = kio::clock::now(); track.finished = false; } Ok(()) @@ -2520,7 +2520,7 @@ where track.declared = None; track.source = source.continuing(&track.source); track.finished = false; - track.subscribed = moq_clock::now(); + track.subscribed = kio::clock::now(); } Ok(()) } @@ -2626,7 +2626,7 @@ where /// When the next queued frame is due, or the next grid slot while media is queued or /// every source has finished and the tail runs out. #[cfg(test)] - pub(super) fn next_due(&self) -> Option { + pub(super) fn next_due(&self) -> Option { let finished = !self.program.tracks.is_empty() && self.program.tracks.values().all(|track| track.finished); let slot = self .slot_due() @@ -2682,7 +2682,7 @@ where catalog: S, follow: Duration, ) -> Result<(), crate::Error> { - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow", now = ?moq_clock::now(), program = self.program.id, pending = ?self.pending.as_ref().map(|pending| pending.id), old_epoch = ?self.program.instance, new_epoch = ?broadcast.info().epoch, ?follow); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow", now = ?kio::clock::now(), program = self.program.id, pending = ?self.pending.as_ref().map(|pending| pending.id), old_epoch = ?self.program.instance, new_epoch = ?broadcast.info().epoch, ?follow); if self.pending.is_some() && self.program.instance.is_some() && broadcast.info().epoch == self.program.instance { self.cancel_pending(); @@ -2695,7 +2695,7 @@ where self.cancel_pending(); let next = self.replacement(self.program.source.switched(broadcast), catalog); self.pending = Some(Box::new(next)); - self.follow_until.get_or_insert_with(|| moq_clock::now() + follow); + self.follow_until.get_or_insert_with(|| kio::clock::now() + follow); return Ok(()); } if let Some(mut pending) = self.pending.take() { @@ -3670,7 +3670,7 @@ where /// never on when they arrived, and the output keeps the clock's pace while media is queued /// (in the schedule or still in the jitter buffer) or still to decode. `None` without a /// delay, where frames settle the slots instead. - fn slot_due(&self) -> Option<(u128, moq_clock::Instant)> { + fn slot_due(&self) -> Option<(u128, kio::clock::Instant)> { let (known, settled) = self.slot_settled()?; let settled = Timestamp::from_micros(u64::try_from(settled / 1_000).ok()?).ok()?; // The tail of the generation still going out keeps its own clock after the next is acquired. @@ -3723,11 +3723,11 @@ where /// Lay out every grid slot whose time has come, and wake when the next one is due. fn lay_due(&mut self, waiter: &kio::Waiter) -> anyhow::Result<()> { while let Some((known, at)) = self.slot_due() { - if moq_clock::now() < at { + if kio::clock::now() < at { let timer = self .program .slot_timer - .get_or_insert_with(|| Box::pin(moq_clock::sleep_until(at))); + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(at))); if timer.deadline() != at { timer.as_mut().reset(at); } @@ -4999,7 +4999,7 @@ mod tests { payload: bytes::Bytes::from_static(b"frame"), keyframe: at % 600 == 0, }; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut jitter = super::jitter::Buffer::new(Duration::from_millis(500)); jitter.expect([super::TrackKey::new(0, "video"), super::TrackKey::new(0, "audio")]); let mut trimmed = 0; @@ -5171,7 +5171,7 @@ mod tests { let mut clock = DecodeClock::default(); let mut dts = vec![0; pts.len()]; for (i, &p) in pts.iter().enumerate() { - clock.push(i, p, moq_clock::Instant::ZERO, 0); + clock.push(i, p, kio::clock::Instant::ZERO, 0); while let Some((i, d)) = clock.pop(jitter, floor, Settle::Due) { dts[i] = d; } @@ -5187,7 +5187,7 @@ mod tests { #[test] fn a_decode_clock_burst_sharing_a_pts_settles_at_the_byte_budget() { const MAX_BYTES: usize = 10_000; - let start = moq_clock::Instant::ZERO; + let start = kio::clock::Instant::ZERO; let delay = Duration::from_millis(500); let mut clock = DecodeClock::default(); let (mut held, mut most) = (0, 0); @@ -5213,7 +5213,7 @@ mod tests { #[test] fn a_frame_filling_the_byte_budget_keeps_the_reorder() { const MAX_BYTES: usize = 1_000_000; - let start = moq_clock::Instant::ZERO; + let start = kio::clock::Instant::ZERO; let delay = Duration::from_millis(500); let mut clock = DecodeClock::default(); let mut dts = vec![0; 5]; @@ -5235,7 +5235,7 @@ mod tests { #[test] fn a_budget_filled_past_the_reorder_depth_keeps_the_delay() { const MAX_BYTES: usize = 1_000_000; - let start = moq_clock::Instant::ZERO; + let start = kio::clock::Instant::ZERO; let delay = Duration::from_millis(500); let ranks = [0, 4, 2, 1, 3].into_iter().chain(5..=40); let mut clock = DecodeClock::default(); diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index d30b77a9183..5ec8bceba7e 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -117,7 +117,7 @@ where let mut exporter = exporter.with_delay(RECORDING_MAX_AGE).with_replay(); let mut out = BytesMut::new(); // `while let Ok` stops on the first timeout (`Pending`: no more output). - while let Ok(res) = moq_clock::timeout(DRAIN, exporter.next()).await { + while let Ok(res) = kio::clock::timeout(DRAIN, exporter.next()).await { let Some(frame) = res.expect("exporter error") else { break; }; @@ -247,7 +247,7 @@ async fn a_follower_keeps_msf_after_catalog_eof() { assert!(export.next().await.unwrap().is_none()); assert_eq!(export.catalog_format(), CatalogFormat::Msf); // The routed subscription is released when the origin driver observes the local drop. - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { while track.subscription().is_some() { track.subscription_changed().await.unwrap(); } @@ -260,7 +260,7 @@ async fn a_follower_keeps_msf_after_catalog_eof() { .with_follow(Duration::from_secs(1)); let (broadcast, track) = publish(); // Only the MSF catalog exists, so falling back to the default encoding cannot subscribe. - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(1), kio::wait(|waiter| { if let Poll::Ready(Err(err)) = follower.poll_next(waiter) { @@ -1054,7 +1054,7 @@ async fn export_trims_leading_pictures_after_a_late_drop() { .await .unwrap() .with_delay(Duration::from_millis(500)); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut out = Vec::new(); // (arrival, PTS) in milliseconds, in decode order. The second group acquires the clock. // Its 160 ms picture stalls past its deadline, before the next group exists for the @@ -1073,7 +1073,7 @@ async fn export_trims_leading_pictures_after_a_late_drop() { (2080, 2060, false), (2120, 2120, false), ] { - moq_clock::sleep_until(start + Duration::from_millis(at)).await; + kio::clock::sleep_until(start + Duration::from_millis(at)).await; // Finding the source empty dates the next frame's arrival. out.extend(poll_frames(&mut export)); video @@ -1153,12 +1153,12 @@ async fn export_resumes_whole_mpeg2_video_at_a_sequence_header() { (2080, 2080, true), (2120, 2120, false), ]; - let start = moq_clock::now(); + let start = kio::clock::now(); let (mut out, mut sample) = (Vec::new(), 0); for (index, (at, pts, sequence)) in pictures.into_iter().enumerate() { // The audio arrives on time throughout, so only the video is late. while sample * AUDIO_US <= at * 1_000 { - moq_clock::sleep_until(start + Duration::from_micros(sample * AUDIO_US)).await; + kio::clock::sleep_until(start + Duration::from_micros(sample * AUDIO_US)).await; out.extend(poll_frames(&mut export)); audio .write(Frame { @@ -1170,7 +1170,7 @@ async fn export_resumes_whole_mpeg2_video_at_a_sequence_header() { .unwrap(); sample += 1; } - moq_clock::sleep_until(start + Duration::from_millis(at)).await; + kio::clock::sleep_until(start + Duration::from_millis(at)).await; out.extend(poll_frames(&mut export)); let mut payload = if sequence { vec![0, 0, 1, 0xb3] } else { Vec::new() }; payload.extend_from_slice(&[0, 0, 1, 0x00, index as u8]); @@ -1402,7 +1402,7 @@ async fn export_declared_zero_reorder_decodes_at_presentation() { let (mut export, _keep) = export_declared(0, &[&[0, 80, 40, 120]]).await; let err = loop { - match moq_clock::timeout(DRAIN, export.next()).await { + match kio::clock::timeout(DRAIN, export.next()).await { Ok(Ok(Some(_))) => {} Ok(Ok(None)) | Err(_) => panic!("a frame reordered past the declared depth was exported"), Ok(Err(err)) => break err, @@ -1519,7 +1519,7 @@ async fn export_pcr_wraps_below_zero_at_start() { .with_delay(RECORDING_MAX_AGE); // Every slot up to the last decode time, the clock laying them out at theirs. let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(DRAIN, exporter.next()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(DRAIN, exporter.next()).await { frames.push(frame); } @@ -2263,7 +2263,7 @@ async fn read_frames(consumer: &moq_net::broadcast::Consumer, name: &str, kind: .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy(kind)); let mut frames = Vec::new(); - while let Ok(res) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(res) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { let Some(frame) = res.unwrap() else { break }; frames.push(frame.payload.to_vec()); } @@ -2873,7 +2873,7 @@ async fn aac_export_refuses_what_adts_cannot_label() { let mut exporter = open_export(crate::source::announced(&consumer).await).await.unwrap(); let err = loop { - match moq_clock::timeout(DRAIN, exporter.next()).await { + match kio::clock::timeout(DRAIN, exporter.next()).await { Ok(Ok(Some(_))) => continue, Ok(Ok(None)) => panic!("export completed; expected a refusal naming {refusal}"), Ok(Err(e)) => break e, @@ -3058,7 +3058,7 @@ async fn read_cues(consumer: &moq_net::broadcast::Consumer, name: &str) -> Vec<( .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy(crate::container::Kind::Data)); let mut cues = Vec::new(); - while let Ok(res) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(res) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { let Some(frame) = res.unwrap() else { break }; cues.push((frame.payload.to_vec(), frame.timestamp)); } @@ -3676,7 +3676,7 @@ async fn a_reimport_keeps_the_first_si_across_a_gap() { export = export.with_mux_rate(rate); } let mut ts = BytesMut::new(); - while let Ok(frame) = moq_clock::timeout(DRAIN, export.next()).await { + while let Ok(frame) = kio::clock::timeout(DRAIN, export.next()).await { let Some(frame) = frame.expect("exporter error") else { break; }; @@ -4389,7 +4389,7 @@ async fn discontinuity_flags_the_break_once_across_tracks() { // generation, so it lapses twice. let mut marked = drain_frames(&mut export).await; for _ in 0..2 { - moq_clock::sleep(RECORDING_MAX_AGE).await; + kio::clock::sleep(RECORDING_MAX_AGE).await; marked.extend(drain_frames(&mut export).await); } assert_eq!(export.discontinuity(), 1, "local marker counts are not program epochs"); @@ -5204,7 +5204,7 @@ async fn stale_si_entry_does_not_block_output() { .unwrap(); // The timeout distinguishes "produced output promptly" from "held dark"; // under paused time a wedged exporter would hit it instantly. - let frame = moq_clock::timeout(DRAIN, exporter.next()) + let frame = kio::clock::timeout(DRAIN, exporter.next()) .await .expect("a stale SI entry must not hold output dark") .unwrap() @@ -5455,7 +5455,7 @@ async fn export_opus_track(channel_count: u32, description: Option) -> Re .with_replay(); let mut out = BytesMut::new(); loop { - match moq_clock::timeout(DRAIN, exporter.next()).await { + match kio::clock::timeout(DRAIN, exporter.next()).await { Ok(Ok(Some(frame))) => out.extend_from_slice(&frame.payload), Ok(Ok(None)) => return Ok(out), Ok(Err(err)) => return Err(err.to_string()), @@ -5715,10 +5715,10 @@ where // Run the paused clock only as far as the next frame due, so a test that writes // more afterwards is still on time for it. if let Some(deadline) = export.next_due() { - moq_clock::sleep_until(deadline).await; + kio::clock::sleep_until(deadline).await; continue; } - match moq_clock::timeout(Duration::from_millis(10), export.next()).await { + match kio::clock::timeout(Duration::from_millis(10), export.next()).await { Ok(Ok(Some(frame))) => out.push(frame), Ok(Ok(None)) => break, Err(_) if export.next_due().is_none() => break, @@ -5820,7 +5820,7 @@ struct Interleave { /// Audio frames per group. audio_group: u64, /// The paused clock's instant at media time zero, set by the first [`Self::at`]. - start: Option, + start: Option, } impl Interleave { @@ -5889,8 +5889,8 @@ impl Interleave { /// Run the paused clock to `micros` of media time, as a live source would. async fn at(&mut self, micros: u64) { - let start = *self.start.get_or_insert_with(moq_clock::now); - moq_clock::sleep_until(start + Duration::from_micros(micros)).await; + let start = *self.start.get_or_insert_with(kio::clock::now); + kio::clock::sleep_until(start + Duration::from_micros(micros)).await; } fn video(&mut self, tick: u64) { @@ -6492,7 +6492,7 @@ async fn repointed_si_entry_resubscribes() { // that should carry the new sections, or the exporter drains them all first. let mut after = BytesMut::new(); write_key(&mut producer, 2); - let frame = moq_clock::timeout(DRAIN, exporter.next()) + let frame = kio::clock::timeout(DRAIN, exporter.next()) .await .expect("a frame after the switch") .unwrap() @@ -6504,7 +6504,7 @@ async fn repointed_si_entry_resubscribes() { write_key(&mut producer, 3); write_key(&mut producer, 4); producer.finish().unwrap(); - while let Ok(res) = moq_clock::timeout(DRAIN, exporter.next()).await { + while let Ok(res) = kio::clock::timeout(DRAIN, exporter.next()).await { let Some(frame) = res.unwrap() else { break }; after.extend_from_slice(&frame.payload); } @@ -6593,7 +6593,7 @@ async fn si_revision_after_final_media_frame_is_flushed() { // v1 goes out with the media frame's slices, once the export's PCR interval is out. let contains = |haystack: &[u8], needle: &[u8]| haystack.windows(needle.len()).any(|w| w == needle); loop { - let frame = moq_clock::timeout(DRAIN, exporter.next()) + let frame = kio::clock::timeout(DRAIN, exporter.next()) .await .expect("v1 goes out (control)") .unwrap() @@ -6610,7 +6610,7 @@ async fn si_revision_after_final_media_frame_is_flushed() { .unwrap(); catalog.finish().unwrap(); - let tail = moq_clock::timeout(DRAIN, exporter.next()) + let tail = kio::clock::timeout(DRAIN, exporter.next()) .await .expect("a trailing SI frame rather than an immediate end") .unwrap() @@ -6620,7 +6620,7 @@ async fn si_revision_after_final_media_frame_is_flushed() { contains(&tail.payload, &sdt_v2), "the trailing flush carries the revision" ); - let end = moq_clock::timeout(DRAIN, exporter.next()) + let end = kio::clock::timeout(DRAIN, exporter.next()) .await .expect("the stream ends after the flush") .unwrap(); @@ -7337,14 +7337,14 @@ async fn slices_go_out_on_the_clock() { for ms in (0..1_000).step_by(20) { write_aac(&mut audio, second * 1_000 + ms); } - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } audio.finish().unwrap(); (broadcast, catalog) }); let mut handed = Vec::new(); - while let Ok(Ok(Some(_))) = moq_clock::timeout(Duration::from_secs(5), export.next()).await { - handed.push(moq_clock::now()); + while let Ok(Ok(Some(_))) = kio::clock::timeout(Duration::from_secs(5), export.next()).await { + handed.push(kio::clock::now()); } writer.await.unwrap(); assert!(handed.len() > 100, "too few slices to judge: {}", handed.len()); @@ -7926,11 +7926,11 @@ async fn export_reordered( None => export, }; let mut a = padded(rig.export(delay).await); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut b = None; let (mut out_a, mut out_b) = (Vec::new(), Vec::new()); for tick in 0..TICKS { - moq_clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; if let Some((at, jitter)) = jitter && at == tick { @@ -8082,10 +8082,10 @@ async fn reordered_video_loses_nothing_on_a_clean_path() { let delay = Duration::from_millis(500); let mut rig = Reordered::new(SPS, PPS, &[0, 1, 2, 3, 4]).await; let mut export = rig.export(delay).await; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut out = Vec::new(); for tick in 0..TICKS / 2 { - moq_clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; rig.video(tick); while rig.audio_before(tick + 1) {} out.extend(poll_frames(&mut export)); @@ -8120,11 +8120,11 @@ async fn padded_video_needs_the_delay_its_hrd_declares() { for (delay, refused) in [(Duration::from_millis(500), true), (Duration::from_secs(1), false)] { let mut rig = Reordered::new(SPS_HRD, PPS, &[]).await; let mut export = rig.export(delay).await.with_mux_rate(2_000_000); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut out = Vec::new(); let mut failed = None; 'run: for tick in 0..TICKS / 2 { - moq_clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; rig.video(tick); while rig.audio_before(tick + 1) {} while let std::task::Poll::Ready(frame) = export.poll_next(&waiter) { @@ -8253,11 +8253,11 @@ async fn a_skipped_group_keeps_the_clock() { .await .unwrap() .with_delay(delay); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut out = Vec::new(); // 100 ms groups of five 20 ms frames, a minute in; group 20 never arrives. for sequence in 0..60u64 { - moq_clock::sleep_until(start + Duration::from_millis(sequence * 100)).await; + kio::clock::sleep_until(start + Duration::from_millis(sequence * 100)).await; if sequence != 20 { let mut group = track.create_group(moq_net::group::Info { sequence }).unwrap(); for k in 0..5u64 { @@ -8316,11 +8316,11 @@ async fn a_timeline_restarting_at_zero_fails_the_export() { .await .unwrap() .with_delay(Duration::from_millis(500)); - let start = moq_clock::now(); + let start = kio::clock::now(); // One-second groups of 20 ms frames for 10 s, then a group back at zero. The track refuses // a group whose first frame rewinds, so that group opens at the previous start. for sequence in 0..11u64 { - moq_clock::sleep_until(start + Duration::from_secs(sequence)).await; + kio::clock::sleep_until(start + Duration::from_secs(sequence)).await; let base = if sequence < 10 { sequence * 1_000 } else { 0 }; let mut group = track.create_group(moq_net::group::Info { sequence }).unwrap(); for k in 0..50u64 { @@ -8356,12 +8356,12 @@ async fn a_late_join_starts_at_the_live_edge() { let consumer = broadcast.consume(); let mut catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap(); let mut audio = aac_rendition(&mut broadcast, &mut catalog, "a.aac"); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = None; let mut out = Vec::new(); // One-second groups of 20 ms frames; the exporter joins 5.5 s in with a 2 s delay. for k in 0..400u64 { - moq_clock::sleep_until(start + Duration::from_millis(k * 20)).await; + kio::clock::sleep_until(start + Duration::from_millis(k * 20)).await; if k % 50 == 0 && k > 0 { audio.cut(None).unwrap(); } @@ -8443,7 +8443,10 @@ where { let mut out = Vec::new(); loop { - match moq_clock::timeout(DRAIN, export.next()).await.expect("the export ends") { + match kio::clock::timeout(DRAIN, export.next()) + .await + .expect("the export ends") + { Ok(Some(frame)) => out.push(frame), Ok(None) => return (out, Ok(())), Err(err) => return (out, Err(err)), @@ -8586,7 +8589,7 @@ async fn a_rendition_moved_to_another_aac_configuration_fails() { config.sample_rate = 44_100; } write_aac(&mut next, 200); - let err = moq_clock::timeout(DRAIN, async { + let err = kio::clock::timeout(DRAIN, async { loop { if let Err(err) = export.next().await { break err; @@ -8750,7 +8753,7 @@ async fn same_instance_returns(finish: bool) { .unwrap() .with_delay(RECORDING_MAX_AGE) .with_replay(); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..200).step_by(20) { write_aac(&mut track, ms); } @@ -8766,7 +8769,7 @@ async fn same_instance_returns(finish: bool) { // Back under the same epoch a second later, its media as far on as the wall clock, its // catalog listing the track only in its second snapshot. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let (broadcast, mut catalog) = publish_live::<()>(&origin, route()); std::ops::DerefMut::deref_mut(&mut catalog.modify().unwrap()); let back = origin @@ -8817,9 +8820,9 @@ async fn the_same_instance_continues_after_a_drop() { /// A returning route serves the same publisher's catalog and monotonically numbered groups. #[tokio::test(start_paused = true)] async fn a_return_keeps_catalog_and_group_history() { - let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 86_400_000); + let wall = kio::clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 86_400_000); crate::clock::fake_host_wall(wall); - let start = moq_clock::now(); + let start = kio::clock::now(); let origin = crate::source::produce_origin(); let epoch = moq_net::Epoch::mint(); let route = moq_net::origin::Route::default().with_epoch(epoch.clone()); @@ -9493,14 +9496,14 @@ async fn a_follower_fails_at_once_on_its_own_failure() { let track = aac_rendition(&mut broadcast.broadcast().clone(), &mut catalog, "a.aac"); let mut follower = follower(&origin).await.with_follow(Duration::from_secs(10)); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "nothing to mux yet" ); track.abort(cause.clone()); - let start = moq_clock::now(); + let start = kio::clock::now(); let end = follower.next().await; assert!( matches!(&end, Err(crate::Error::Moq(err)) if err.to_string() == cause.to_string()), @@ -9529,14 +9532,14 @@ async fn a_follower_waits_out_the_follow_on_a_lost_route() { let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "nothing to mux yet" ); track.abort(cause.clone()); - let start = moq_clock::now(); + let start = kio::clock::now(); let end = follower.next().await; assert!( matches!(&end, Err(crate::Error::Moq(err)) if err.to_string() == cause.to_string()), @@ -9557,7 +9560,7 @@ async fn a_follower_awaits_a_replacement_catalog_past_the_follow() { let mut follower = follower(&origin).await.with_follow(follow).with_stitch(true); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" @@ -9572,12 +9575,12 @@ async fn a_follower_awaits_a_replacement_catalog_past_the_follow() { .unwrap(); let unanswered = second.requests(); assert!( - moq_clock::timeout(follow * 3, follower.next()).await.is_err(), + kio::clock::timeout(follow * 3, follower.next()).await.is_err(), "awaiting the replacement's catalog past the follow" ); drop((second, unanswered)); - let end = moq_clock::timeout(Duration::from_secs(1), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .expect("the replacement going ends the wait"); assert!(matches!(end, Ok(None)), "the original clean end: {end:?}"); @@ -9595,7 +9598,7 @@ async fn a_follower_awaits_a_return_catalog_until_it_fails() { let mut follower = follower(&origin).await.with_follow(follow); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" @@ -9606,12 +9609,12 @@ async fn a_follower_awaits_a_return_catalog_until_it_fails() { .unwrap(); let silent = second.create_track(hang::Catalog::DEFAULT_NAME, None).unwrap(); assert!( - moq_clock::timeout(follow * 3, follower.next()).await.is_err(), + kio::clock::timeout(follow * 3, follower.next()).await.is_err(), "awaiting the return's catalog past the follow" ); silent.abort(moq_net::Error::Unroutable).unwrap(); - let end = moq_clock::timeout(Duration::from_secs(1), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .expect("the failed return ends the wait"); assert!(matches!(end, Ok(None)), "the original clean end: {end:?}"); @@ -9627,10 +9630,10 @@ async fn a_follower_keeps_following_when_a_return_goes_before_it_resolves() { let first = publish_bare(&origin, Some(&epoch)); let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" @@ -9642,14 +9645,14 @@ async fn a_follower_keeps_following_when_a_return_goes_before_it_resolves() { .unwrap(); let unanswered = second.requests(); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "resolving the return" ); drop((second, unanswered)); - let end = moq_clock::timeout(follow * 3, follower.next()) + let end = kio::clock::timeout(follow * 3, follower.next()) .await .expect("the follow bounds the wait"); assert!(matches!(end, Ok(None)), "the original clean end: {end:?}"); @@ -9679,10 +9682,10 @@ async fn a_follower_keeps_following_through_a_refused_return() { let first = publish_bare(&origin, Some(&moq_net::Epoch::mint())); let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow).with_stitch(true); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" @@ -9691,7 +9694,7 @@ async fn a_follower_keeps_following_through_a_refused_return() { // Replaced, but the replacement refuses its catalog request. let refusing = publish_refusing(&origin, &moq_net::Epoch::mint()); assert!( - moq_clock::timeout(Duration::from_secs(2), follower.next()) + kio::clock::timeout(Duration::from_secs(2), follower.next()) .await .is_err(), "the refusal keeps it following" @@ -9701,7 +9704,7 @@ async fn a_follower_keeps_following_through_a_refused_return() { let mut second = publish_bare(&origin, Some(&moq_net::Epoch::mint())); std::ops::DerefMut::deref_mut(&mut second.1.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following the next replacement" @@ -9722,17 +9725,17 @@ async fn a_follower_reports_a_refused_return_at_the_follow() { let first = publish_bare(&origin, Some(&epoch)); let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" ); let _refusing = publish_refusing(&origin, &epoch); - let end = moq_clock::timeout(follow * 3, follower.next()) + let end = kio::clock::timeout(follow * 3, follower.next()) .await .expect("the follow bounds the wait"); assert!( @@ -9758,7 +9761,7 @@ async fn a_follower_stitches_onto_the_next_replacement_when_one_goes_before_it_r let second = origin.publish("live", route()).unwrap(); let unanswered = second.requests(); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "resolving the replacement" @@ -9767,7 +9770,7 @@ async fn a_follower_stitches_onto_the_next_replacement_when_one_goes_before_it_r let mut third = publish_bare(&origin, Some(&moq_net::Epoch::mint())); std::ops::DerefMut::deref_mut(&mut third.1.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following the next replacement" @@ -9777,7 +9780,7 @@ async fn a_follower_stitches_onto_the_next_replacement_when_one_goes_before_it_r // Once the first instance is gone too, the third one's end ends the export. finish(first); finish(third); - let end = moq_clock::timeout(Duration::from_secs(10), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(10), follower.next()) .await .expect("the third instance's end ends the export"); assert!(matches!(end, Ok(None)), "{end:?}"); @@ -9793,10 +9796,10 @@ async fn a_follower_keeps_a_return_awaiting_its_catalog_when_a_stitch_goes() { let first = publish_bare(&origin, Some(&epoch)); let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow).with_stitch(true); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following" @@ -9805,7 +9808,7 @@ async fn a_follower_keeps_a_return_awaiting_its_catalog_when_a_stitch_goes() { // Back, with a catalog yet to deliver its first snapshot. let second = publish_bare(&origin, Some(&epoch)); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "awaiting the return's catalog" @@ -9820,7 +9823,7 @@ async fn a_follower_keeps_a_return_awaiting_its_catalog_when_a_stitch_goes() { .unwrap(); let unanswered = third.requests(); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "resolving the replacement" @@ -9891,7 +9894,7 @@ async fn a_return_after_an_abandoned_switch_restores_priority() { /// Take what the follower muxes until it idles for a second, well within the follow. async fn pump(follower: &mut super::Follower) { - while let Ok(next) = moq_clock::timeout(Duration::from_secs(1), follower.next()).await { + while let Ok(next) = kio::clock::timeout(Duration::from_secs(1), follower.next()).await { assert!(next.unwrap().is_some(), "the follower keeps waiting"); } } @@ -9907,7 +9910,7 @@ async fn a_follower_follows_a_return_after_a_lost_route() { let track = aac_rendition(&mut broadcast.broadcast().clone(), &mut catalog, "a.aac"); let mut follower = follower(&origin).await.with_follow(Duration::from_secs(10)); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "nothing to mux yet" @@ -9919,7 +9922,7 @@ async fn a_follower_follows_a_return_after_a_lost_route() { let (broadcast, mut catalog) = publish_bare(&origin, Some(&epoch)); let mut track = aac_rendition(&mut broadcast.broadcast().clone(), &mut catalog, "a.aac"); assert!( - moq_clock::timeout(Duration::from_secs(3), follower.next()) + kio::clock::timeout(Duration::from_secs(3), follower.next()) .await .is_err(), "carried on into the return" @@ -9946,7 +9949,7 @@ async fn a_follower_fails_a_stitch_onto_a_replacement_that_refuses_its_catalog() moq_net::origin::Route::default().with_epoch(moq_net::Epoch::mint()), ) .unwrap(); - let end = moq_clock::timeout(Duration::from_secs(10), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(10), follower.next()) .await .expect("the refusal ends the export"); assert!(end.is_err(), "the refusal fails the export: {end:?}"); @@ -9962,14 +9965,14 @@ async fn a_follower_built_after_its_route_went_follows_the_return() { let export = open_export(crate::source::resolved(&origin, "live").await) .await .unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let follow = Duration::from_secs(10); let mut follower = super::Follower::new(export).unwrap().with_follow(follow); assert!( - moq_clock::timeout(Duration::from_secs(2), follower.next()) + kio::clock::timeout(Duration::from_secs(2), follower.next()) .await .is_err(), "following" @@ -9977,7 +9980,7 @@ async fn a_follower_built_after_its_route_went_follows_the_return() { let mut second = publish_bare(&origin, Some(&epoch)); std::ops::DerefMut::deref_mut(&mut second.1.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "carried on" @@ -10012,21 +10015,21 @@ async fn a_follower_takes_its_own_instance_winning_back_for_no_replacement() { // A cheaper route takes the path for a while, then goes. let cheaper = origin.publish("pool/job", route(1)).unwrap(); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "still on its own instance" ); drop(cheaper); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "its own instance wins back" ); catalog.finish().unwrap(); - let end = moq_clock::timeout(Duration::from_secs(10), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(10), follower.next()) .await .expect("its own end ends the export"); assert!(matches!(end, Ok(None)), "{end:?}"); @@ -10042,7 +10045,7 @@ async fn a_follower_fails_on_a_replacement_without_stitch() { finish(first); let _second = publish_bare(&origin, Some(&moq_net::Epoch::mint())); - let start = moq_clock::now(); + let start = kio::clock::now(); let err = follower.next().await.expect_err("a replacement fails the follower"); assert!(matches!(err, crate::Error::Replaced(_)), "{err}"); assert!(start.elapsed() < Duration::from_secs(1), "no wait for a return"); @@ -10073,10 +10076,10 @@ async fn a_follower_continues_on_the_same_instance_returning() { let first = publish_bare(&origin, Some(&epoch)); let follow = Duration::from_secs(10); let mut follower = follower(&origin).await.with_follow(follow); - let start = moq_clock::now(); + let start = kio::clock::now(); finish(first); assert!( - moq_clock::timeout(Duration::from_secs(2), follower.next()) + kio::clock::timeout(Duration::from_secs(2), follower.next()) .await .is_err(), "following" @@ -10085,7 +10088,7 @@ async fn a_follower_continues_on_the_same_instance_returning() { let mut second = publish_bare(&origin, Some(&epoch)); std::ops::DerefMut::deref_mut(&mut second.1.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "carried on" @@ -10101,7 +10104,7 @@ async fn a_follower_continues_on_the_same_instance_returning() { async fn drain_follower(follower: &mut super::Follower) -> (Vec, Option>) { let mut out = Vec::new(); loop { - match moq_clock::timeout(DRAIN, follower.next()).await { + match kio::clock::timeout(DRAIN, follower.next()).await { Ok(Ok(Some(frame))) => out.push(frame), Ok(Ok(None)) => return (out, Some(Ok(()))), Ok(Err(err)) => return (out, Some(Err(err))), @@ -10131,7 +10134,7 @@ async fn a_follower_continues_through_a_same_epoch_handoff_after_a_gap() { let mut follower = super::Follower::new(export) .unwrap() .with_follow(Duration::from_secs(10)); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..200).step_by(20) { write_aac(&mut track, ms); } @@ -10143,7 +10146,7 @@ async fn a_follower_continues_through_a_same_epoch_handoff_after_a_gap() { track.abort(moq_net::Error::Unroutable); catalog.abort(moq_net::Error::Unroutable); drop(exact); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let served = origin.create_broadcast("pool/job").unwrap(); let mut catalog = crate::catalog::Producer::<()>::new(&mut served.broadcast().clone(), Default::default()).unwrap(); let mut track = aac_rendition(&mut served.broadcast().clone(), &mut catalog, "a.aac"); @@ -10188,12 +10191,12 @@ async fn a_follower_ignores_a_covering_prefix_while_the_exact_route_serves() { let quiet = Duration::from_secs(1); let pool = origin.requests("pool").unwrap(); - assert!(moq_clock::timeout(quiet, follower.next()).await.is_err(), "a start"); + assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a start"); drop(pool); let pool = origin.requests("pool").unwrap(); - assert!(moq_clock::timeout(quiet, follower.next()).await.is_err(), "a restart"); + assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a restart"); drop(pool); - assert!(moq_clock::timeout(quiet, follower.next()).await.is_err(), "an end"); + assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "an end"); finish((exact, catalog)); let end = follower.next().await; @@ -10211,7 +10214,7 @@ async fn a_midstream_stitch_awaits_the_replacement_catalog() { let epoch = moq_net::Epoch::mint(); let (_second, mut catalog) = publish_bare(&origin, Some(&epoch)); assert!( - moq_clock::timeout(Duration::from_secs(60), follower.next()) + kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .is_err(), "awaiting the replacement's catalog, follow={follow:?}" @@ -10220,7 +10223,7 @@ async fn a_midstream_stitch_awaits_the_replacement_catalog() { std::ops::DerefMut::deref_mut(&mut catalog.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "nothing to mux, follow={follow:?}" @@ -10265,7 +10268,7 @@ async fn a_cancelled_replacement_after_the_follow_can_follow_again() { .with_stitch(true) .with_follow(follow); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "the original catalog stays open" @@ -10275,7 +10278,7 @@ async fn a_cancelled_replacement_after_the_follow_can_follow_again() { let (second, mut catalog) = publish_live::<()>(&origin, route()); let audio = aac_rendition(&mut second.broadcast().clone(), &mut catalog, "a.aac"); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "the replacement has no media to commit" @@ -10287,13 +10290,13 @@ async fn a_cancelled_replacement_after_the_follow_can_follow_again() { ); tokio::time::advance(follow).await; assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "still awaiting replacement media after the follow" ); // Observe the origin driver releasing the routed subscription before cancelling B. - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { while old_catalog.subscription().is_some() { old_catalog.subscription_changed().await.unwrap(); } @@ -10305,7 +10308,7 @@ async fn a_cancelled_replacement_after_the_follow_can_follow_again() { catalog.abort(moq_net::Error::Unroutable); drop(second); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "following after the replacement left" @@ -10315,7 +10318,7 @@ async fn a_cancelled_replacement_after_the_follow_can_follow_again() { let (_third, mut catalog) = publish_bare(&origin, Some(&epoch)); std::ops::DerefMut::deref_mut(&mut catalog.modify().unwrap()); catalog.finish().unwrap(); - let end = moq_clock::timeout(follow * 2, follower.next()) + let end = kio::clock::timeout(follow * 2, follower.next()) .await .expect("the final instance ends the export"); assert!(matches!(end, Ok(None)), "{format:?}: {end:?}"); @@ -10368,7 +10371,7 @@ async fn a_nested_stitch_keeps_awaiting_the_pending_replacement() { let epoch = moq_net::Epoch::mint(); let (_second, mut catalog) = publish_bare(&origin, Some(&epoch)); assert!( - moq_clock::timeout(Duration::from_secs(2), follower.next()) + kio::clock::timeout(Duration::from_secs(2), follower.next()) .await .is_err(), "awaiting the replacement's catalog" @@ -10383,14 +10386,14 @@ async fn a_nested_stitch_keeps_awaiting_the_pending_replacement() { .unwrap(); let unanswered = third.requests(); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "resolving the next replacement" ); drop((third, unanswered)); assert!( - moq_clock::timeout(Duration::from_secs(30), follower.next()) + kio::clock::timeout(Duration::from_secs(30), follower.next()) .await .is_err(), "awaiting the second replacement's catalog again" @@ -10398,7 +10401,7 @@ async fn a_nested_stitch_keeps_awaiting_the_pending_replacement() { std::ops::DerefMut::deref_mut(&mut catalog.modify().unwrap()); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "nothing to mux" @@ -10423,7 +10426,7 @@ async fn a_midstream_stitch_catalog_closed_without_a_snapshot_fails() { let (_second, mut catalog) = publish_bare(&origin, Some(&moq_net::Epoch::mint())); assert!( - moq_clock::timeout(Duration::from_secs(1), follower.next()) + kio::clock::timeout(Duration::from_secs(1), follower.next()) .await .is_err(), "awaiting the replacement's catalog" @@ -10431,7 +10434,7 @@ async fn a_midstream_stitch_catalog_closed_without_a_snapshot_fails() { catalog.finish().unwrap(); drop(catalog); - let end = moq_clock::timeout(Duration::from_secs(30), follower.next()) + let end = kio::clock::timeout(Duration::from_secs(30), follower.next()) .await .expect("the closed catalog ends the export"); let err = end.expect_err("a replacement without a catalog fails"); @@ -10601,7 +10604,7 @@ async fn a_backlog_stays_in_the_source_until_due() { config.description = Some(Bytes::from_static(&[0x12, 0x10])); let mut live = Live::audio(config); let mut export = open_export(live.source().await).await.unwrap().with_delay(delay); - let start = moq_clock::now(); + let start = kio::clock::now(); live.track.write(raw_frame(0, b"first", true)).unwrap(); // A zero-delay slot needs a later frame to prove it is complete. live.track.write(raw_frame(40_000, b"warm", false)).unwrap(); @@ -10628,7 +10631,7 @@ async fn a_backlog_stays_in_the_source_until_due() { tokio::time::advance(delay).await; let mut frames = 0; while frames < 50 { - let frame = moq_clock::timeout(DRAIN, export.next()) + let frame = kio::clock::timeout(DRAIN, export.next()) .await .unwrap_or_else(|_| { panic!( @@ -10842,7 +10845,7 @@ async fn export_placed(placed: Placed) -> crate::Result> { exporter = exporter.with_mux_rate(rate); } let mut out = Vec::new(); - while let Ok(next) = moq_clock::timeout(DRAIN, exporter.next()).await { + while let Ok(next) = kio::clock::timeout(DRAIN, exporter.next()).await { match next? { Some(frame) => out.push(frame), None => break, @@ -11202,7 +11205,7 @@ async fn placed_sections_keep_their_source_positions() { .with_replay() .with_mux_rate(RATE); let mut output = Vec::new(); - while let Ok(Some(slice)) = moq_clock::timeout(DRAIN, exporter.next()) + while let Ok(Some(slice)) = kio::clock::timeout(DRAIN, exporter.next()) .await .map(|next| next.unwrap()) { @@ -11259,7 +11262,7 @@ async fn a_track_renamed_on_its_pid_across_returns_retires_the_one_before() { .unwrap() .with_delay(RECORDING_MAX_AGE) .with_replay(); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..200).step_by(20) { write_aac(&mut track, ms); } @@ -11268,7 +11271,7 @@ async fn a_track_renamed_on_its_pid_across_returns_retires_the_one_before() { let _ = drain_to_end(&mut export).await; for round in 1..=4 { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let (broadcast, mut catalog) = publish_live::(&origin, route()); let back = origin .consume() @@ -11325,7 +11328,7 @@ async fn a_track_renamed_on_its_pid_across_a_return_is_quiet_from_its_listing() .unwrap() .with_delay(Duration::from_secs(1)) .with_replay(); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..200).step_by(20) { write_aac(&mut track, ms); } @@ -11334,7 +11337,7 @@ async fn a_track_renamed_on_its_pid_across_a_return_is_quiet_from_its_listing() let _ = drain_to_end(&mut export).await; let (before, _) = export.liveness(0x101); - moq_clock::sleep(Duration::from_secs(10)).await; + kio::clock::sleep(Duration::from_secs(10)).await; let (broadcast, mut catalog) = publish_live::(&origin, route()); let back = origin .consume() @@ -11356,7 +11359,7 @@ async fn a_track_renamed_on_its_pid_across_a_return_is_quiet_from_its_listing() if export.listed_on(0x101) == Some("1.aac") && units == before { quiet.push(since); } - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } assert!(!quiet.is_empty(), "the track was listed with none of its units out"); assert!( @@ -11578,7 +11581,7 @@ async fn a_healthy_stitch_feeds_the_old_generation_until_the_new_clock_acquires( let mut demoted = false; let mut frames = Vec::new(); let step = Duration::from_millis(20); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..14_000).step_by(20) { write_aac(&mut old_audio, ms); if ms == 4000 { @@ -11655,7 +11658,7 @@ async fn repeated_stitches_keep_the_delay() { .with_stitch(true) .with_follow(Duration::from_secs(10)); let step = Duration::from_millis(20); - let start = moq_clock::now(); + let start = kio::clock::now(); // Each frame out: when, and its epoch. let mut frames = Vec::new(); for ms in (0..4 * SWITCH).step_by(20) { @@ -11735,7 +11738,7 @@ async fn an_expired_follow_stops_healthy_input_but_drains_its_buffered_tail() { .with_delay(delay); let mut replacement = None; let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); for ms in (0..4000).step_by(20) { let elapsed = Duration::from_millis(ms); write_aac(&mut old_audio, ms); @@ -11829,7 +11832,7 @@ async fn a_publisher_that_leaves_drains_its_buffered_tail_before_the_end() { .await .unwrap() .with_delay(delay); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut frames = Vec::new(); let end = loop { let elapsed = start.elapsed(); diff --git a/rs/moq-mux/src/container/ts/export_timing_test.rs b/rs/moq-mux/src/container/ts/export_timing_test.rs index 69293dbb5bd..bc447f94865 100644 --- a/rs/moq-mux/src/container/ts/export_timing_test.rs +++ b/rs/moq-mux/src/container/ts/export_timing_test.rs @@ -12,7 +12,7 @@ use std::time::Duration; use bytes::{Bytes, BytesMut}; use hang::catalog::{AAC, AudioConfig, Container, H264, VideoConfig}; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::Timestamp; use mpeg2ts::ts::{ReadTsPacket, TsPacketReader, TsPayload}; @@ -153,7 +153,7 @@ impl Live { reorder: false, delta_size: 400, offset: 0, - start: moq_clock::now(), + start: kio::clock::now(), tick: 0, audio_index: 0, } @@ -205,7 +205,7 @@ impl Live { /// same timeline from the next group, as its replacement or the other half of a 1+1 pair /// would. async fn fall_silent(&mut self, gap: Duration, legs: &mut [&mut Leg]) { - let resume = moq_clock::now() + gap; + let resume = kio::clock::now() + gap; advance(resume, legs).await; let media = (resume.duration_since(self.start).as_secs_f64() * self.scale * 1e6) as u64; self.tick = media.div_ceil(VIDEO_US * GOP) * GOP; @@ -222,7 +222,7 @@ impl Live { Leg { export, every, - next_poll: moq_clock::now(), + next_poll: kio::clock::now(), out: Vec::new(), } } @@ -356,7 +356,7 @@ impl Leg { fn poll(&mut self) { let waiter = kio::Waiter::noop(); - let now = moq_clock::now(); + let now = kio::clock::now(); while let std::task::Poll::Ready(frame) = self.export.poll_next(&waiter) { match frame.expect("exporter error") { Some(frame) => self.out.push((now, frame)), @@ -370,11 +370,11 @@ impl Leg { loop { self.poll(); if let Some(deadline) = self.export.next_due() { - moq_clock::sleep_until(deadline).await; + kio::clock::sleep_until(deadline).await; continue; } - match moq_clock::timeout(Duration::from_millis(10), self.export.next()).await { - Ok(Ok(Some(frame))) => self.out.push((moq_clock::now(), frame)), + match kio::clock::timeout(Duration::from_millis(10), self.export.next()).await { + Ok(Ok(Some(frame))) => self.out.push((kio::clock::now(), frame)), Ok(Ok(None)) => break, Err(_) if self.export.next_due().is_none() => break, Err(_) => {} @@ -397,8 +397,8 @@ async fn advance(at: Instant, legs: &mut [&mut Leg]) { .filter(|wake| *wake <= at) .min() { - moq_clock::sleep_until(wake).await; - let now = moq_clock::now(); + kio::clock::sleep_until(wake).await; + let now = kio::clock::now(); for leg in legs.iter_mut() { if leg.wake().is_some_and(|wake| wake <= now) { leg.poll(); @@ -410,7 +410,7 @@ async fn advance(at: Instant, legs: &mut [&mut Leg]) { } } } - moq_clock::sleep_until(at).await; + kio::clock::sleep_until(at).await; // Read up to the instant the next frame arrives, so the arrival is timed exactly. for leg in legs.iter_mut() { leg.poll_now(); @@ -642,7 +642,7 @@ async fn an_unmarked_step_keeps_the_export_rendering() { let mut leg = live.join(Duration::ZERO).await; live.run(8 * GOP + GOP / 2, &mut [&mut leg], |_| false).await; live.offset += step; - let stepped = moq_clock::now(); + let stepped = kio::clock::now(); live.run(live.tick + 8 * GOP, &mut [&mut leg], |_| false).await; let case = format!("{} s step, lag {lag}", step as f64 / 1e6); @@ -684,7 +684,7 @@ async fn frames_held_through_a_silence_drop_as_late() { let tail = if declared { 2 } else { 5 }; live.run(8 * GOP + tail, &mut [&mut leg], |_| false).await; live.fall_silent(Duration::from_secs(3), &mut [&mut leg]).await; - let resumed = moq_clock::now(); + let resumed = kio::clock::now(); live.run(live.tick + 8 * GOP, &mut [&mut leg], |_| false).await; let dropped = leg.export.dropped(); @@ -730,7 +730,7 @@ async fn a_cut_judges_held_video_when_the_loss_is_observed() { let tail = if declared { 2 } else { 8 }; live.run(8 * GOP + tail, &mut [&mut leg], |_| false).await; live.fall_silent(silence, &mut [&mut leg]).await; - let observed = moq_clock::now(); + let observed = kio::clock::now(); live.group.take().unwrap().abort(moq_net::Error::Unroutable).unwrap(); leg.poll_now(); live.run(live.tick + 8 * GOP, &mut [&mut leg], |_| false).await; diff --git a/rs/moq-mux/src/container/ts/follower.rs b/rs/moq-mux/src/container/ts/follower.rs index b9620da250c..bb8559aabbf 100644 --- a/rs/moq-mux/src/container/ts/follower.rs +++ b/rs/moq-mux/src/container/ts/follower.rs @@ -5,7 +5,7 @@ use std::pin::Pin; use std::task::Poll; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use super::{Export, catalog}; use crate::container::Frame; @@ -96,7 +96,7 @@ pub struct Follower { refused: bool, follow: Duration, stitch: bool, - timer: Option>>, + timer: Option>>, } impl Follower { @@ -210,7 +210,7 @@ impl Follower { self.following(&end); self.state = State::Settling { end, - deadline: moq_clock::now() + self.follow, + deadline: kio::clock::now() + self.follow, }; } State::Settling { end, deadline } => { @@ -390,7 +390,7 @@ impl Follower { end: Err( anyhow::anyhow!("replacement broadcast `{}` ended before serving its catalog", self.path).into(), ), - deadline: moq_clock::now() + self.follow, + deadline: kio::clock::now() + self.follow, }, } } @@ -421,10 +421,10 @@ impl Follower { /// Whether `at` has come, registering `waiter` to wake then if not. fn elapsed(&mut self, waiter: &kio::Waiter, at: Instant) -> bool { - if moq_clock::now() >= at { + if kio::clock::now() >= at { return true; } - let timer = self.timer.get_or_insert_with(|| Box::pin(moq_clock::sleep_until(at))); + let timer = self.timer.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(at))); if timer.deadline() != at { timer.as_mut().reset(at); } diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index 11af1025391..3c69406971f 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -439,7 +439,7 @@ impl Import { /// coalesces a junction's burst of sub-table commits into few groups instead of one per /// commit. pub(super) fn flush_batch(&mut self) -> anyhow::Result<()> { - self.damage_log.flush(moq_clock::now()); + self.damage_log.flush(kio::clock::now()); self.si.flush(self.last_pts.unwrap_or(Timestamp::ZERO), false) } @@ -5254,7 +5254,7 @@ pub(super) mod test { import.decode(&bytes).unwrap(); import.finish().unwrap(); - let first = moq_clock::timeout(Duration::from_secs(10), updates.next()) + let first = kio::clock::timeout(Duration::from_secs(10), updates.next()) .await .expect("the cue track publishes the initial catalog") .unwrap() @@ -5296,7 +5296,7 @@ pub(super) mod test { // SCTE detection takes no lock here (video/audio would still publish later): the old // discarding ScteStream took the lock and republished an empty catalog on this path. assert!( - moq_clock::timeout(Duration::from_millis(10), updates.next()) + kio::clock::timeout(Duration::from_millis(10), updates.next()) .await .is_err(), "SCTE detection must not publish the base catalog" @@ -5375,7 +5375,7 @@ pub(super) mod test { .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); - let frame = moq_clock::timeout(Duration::from_secs(1), reader.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), reader.read_frame()) .await .expect("cue read timed out") .unwrap() @@ -5631,7 +5631,7 @@ pub(super) mod test { if anchored { // The shift then depends on the wall clock, so only its consistency is checked. let first = Timestamp::from_scale(picture(0), 90_000).unwrap(); - timebase.place(first, moq_clock::wall()).unwrap(); + timebase.place(first, kio::clock::wall()).unwrap(); } let mut import = super::Import::new(broadcast, timebase.reserve()); @@ -5676,7 +5676,7 @@ pub(super) mod test { .unwrap(); let mut exporter = exporter.with_delay(RECORDING_MAX_AGE).with_replay(); let mut ts = Vec::new(); - while let Ok(Some(frame)) = moq_clock::timeout(RECORDING_MAX_AGE * 3, exporter.next()) + while let Ok(Some(frame)) = kio::clock::timeout(RECORDING_MAX_AGE * 3, exporter.next()) .await .map(|r| r.unwrap()) { @@ -6060,7 +6060,7 @@ pub(super) mod test { crate::catalog::hang::Container::Legacy(crate::container::Kind::Audio), ); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { frames.push(frame); } frames @@ -6124,7 +6124,7 @@ pub(super) mod test { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { frames.push(frame); } frames @@ -7051,7 +7051,7 @@ pub(super) mod test { track, crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); - let published = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await; + let published = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await; assert!( matches!(published, Ok(Ok(Some(_)))), "a PID that never published held the catalog shut: {published:?}" @@ -7102,7 +7102,7 @@ pub(super) mod test { import.decode(&mux.out).unwrap(); assert_eq!(import.stats().streams[&AAC_PID].damaged, 1); - let first = moq_clock::timeout(Duration::from_millis(10), updates.next()) + let first = kio::clock::timeout(Duration::from_millis(10), updates.next()) .await .expect("the catalog waits on a track that cannot resolve") .unwrap() @@ -7118,7 +7118,7 @@ pub(super) mod test { import.finish().unwrap(); let audio = loop { - let update = moq_clock::timeout(Duration::from_millis(10), updates.next()) + let update = kio::clock::timeout(Duration::from_millis(10), updates.next()) .await .expect("the AAC track never joined") .unwrap() @@ -7443,7 +7443,7 @@ pub(super) mod test { .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); - let frame = moq_clock::timeout(Duration::from_secs(1), reader.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), reader.read_frame()) .await .expect("cue read timed out") .unwrap() @@ -7737,7 +7737,7 @@ pub(super) mod test { let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy(kind)); let mut frames = Vec::new(); let mut breaks = 0; - while let Ok(Ok(Some(read))) = moq_clock::timeout(std::time::Duration::from_millis(50), reader.read()).await { + while let Ok(Ok(Some(read))) = kio::clock::timeout(std::time::Duration::from_millis(50), reader.read()).await { match read { crate::container::Read::Frame { frame, .. } => frames.push(frame), crate::container::Read::Gap { .. } | crate::container::Read::End { .. } => breaks += 1, @@ -8983,7 +8983,7 @@ pub(super) mod test { let track = consumer.track(name).unwrap().subscribe(subscription).await.unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy(kind)); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { if !frame.payload.is_empty() { frames.push(frame); } @@ -9204,7 +9204,7 @@ pub(super) mod test { .with_delay(Duration::from_secs(30)) .with_replay(); let mut ts = Vec::new(); - while let Ok(frame) = moq_clock::timeout(Duration::from_secs(100), export.next()).await { + while let Ok(frame) = kio::clock::timeout(Duration::from_secs(100), export.next()).await { let Some(frame) = frame.unwrap() else { break; }; @@ -9837,7 +9837,7 @@ pub(super) mod test { .with_delay(Duration::from_secs(30)) .with_replay(); let mut ts = Vec::new(); - while let Ok(res) = moq_clock::timeout(Duration::from_secs(100), exporter.next()).await { + while let Ok(res) = kio::clock::timeout(Duration::from_secs(100), exporter.next()).await { let Some(frame) = res.expect("the exporter must take the open GOP after the break") else { break; }; @@ -10504,7 +10504,7 @@ pub(super) mod test { std::task::Poll::Ready(Err(err)) => panic!("exporter error: {err}"), std::task::Poll::Pending => { let Some(deadline) = exporter.next_due() else { break }; - moq_clock::sleep_until(deadline).await; + kio::clock::sleep_until(deadline).await; } } } diff --git a/rs/moq-mux/src/container/ts/import_test.rs b/rs/moq-mux/src/container/ts/import_test.rs index 8bdb0bdb0d8..0a9b2b67d8d 100644 --- a/rs/moq-mux/src/container/ts/import_test.rs +++ b/rs/moq-mux/src/container/ts/import_test.rs @@ -96,7 +96,7 @@ async fn public_container_preserves_loc_for_ts() { track, crate::catalog::hang::Container::Loc(crate::container::Kind::Data), ); - let frame = moq_clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() @@ -262,7 +262,7 @@ async fn import_opus_frames() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); let mut frames = Vec::new(); - while let Ok(res) = moq_clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await { + while let Ok(res) = kio::clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await { let Some(frame) = res.unwrap() else { break }; frames.push(frame.payload); } @@ -480,7 +480,7 @@ async fn import_export_import_roundtrip() { .with_delay(RECORDING_MAX_AGE) .with_replay(); let mut out = BytesMut::new(); - while let Ok(res) = moq_clock::timeout(DRAIN, exporter.next()).await { + while let Ok(res) = kio::clock::timeout(DRAIN, exporter.next()).await { match res.expect("exporter error") { Some(frame) => out.extend_from_slice(&frame.payload), None => break, @@ -541,7 +541,7 @@ async fn survives_midstream_join() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await + while let Ok(Ok(Some(frame))) = kio::clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await { frames.push(frame); } @@ -596,7 +596,7 @@ async fn kyrion_dirtystart_extracts_real_cues() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); let mut cues = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await + while let Ok(Ok(Some(frame))) = kio::clock::timeout(std::time::Duration::from_millis(50), reader.read_frame()).await { cues.push((frame.payload.to_vec(), frame.timestamp)); } @@ -701,7 +701,7 @@ struct Imported { published: std::collections::BTreeMap>, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, } /// Import `data` on a catalog with the default clock. @@ -711,9 +711,9 @@ async fn import_stream(data: &[u8]) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut import = crate::container::ts::Import::new(broadcast, catalog.reserve()); - let before = moq_clock::wall(); + let before = kio::clock::wall(); import.decode(data).unwrap(); - let after = moq_clock::wall(); + let after = kio::clock::wall(); import.finish().unwrap(); let snapshot = catalog.snapshot(); diff --git a/rs/moq-mux/src/container/ts/oracle.rs b/rs/moq-mux/src/container/ts/oracle.rs index 36cbeb37dc3..7865c299ec0 100644 --- a/rs/moq-mux/src/container/ts/oracle.rs +++ b/rs/moq-mux/src/container/ts/oracle.rs @@ -14,7 +14,7 @@ use std::time::Duration; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use crate::container::Frame; diff --git a/rs/moq-mux/src/container/ts/passthrough_test.rs b/rs/moq-mux/src/container/ts/passthrough_test.rs index 5a77960b672..e35c5d6227a 100644 --- a/rs/moq-mux/src/container/ts/passthrough_test.rs +++ b/rs/moq-mux/src/container/ts/passthrough_test.rs @@ -91,7 +91,7 @@ async fn import_onto( .await?; let mut objects = Vec::new(); let mut markers = Vec::new(); - while let Some(mut group) = moq_clock::timeout(Duration::from_secs(1), track.recv_group()).await?? { + while let Some(mut group) = kio::clock::timeout(Duration::from_secs(1), track.recv_group()).await?? { while let Some(frame) = group.read_frame().await? { if frame.payload.is_empty() { markers.push(group.sequence); diff --git a/rs/moq-mux/src/container/ts/pes_packet_test.rs b/rs/moq-mux/src/container/ts/pes_packet_test.rs index 24268d781e8..858de183db5 100644 --- a/rs/moq-mux/src/container/ts/pes_packet_test.rs +++ b/rs/moq-mux/src/container/ts/pes_packet_test.rs @@ -246,7 +246,7 @@ async fn read_until( ); let mut frames = Vec::new(); loop { - match moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + match kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { Ok(Ok(Some(frame))) => frames.push(frame), Ok(Ok(None)) => return (frames, Ok(true)), Err(_) => return (frames, Ok(false)), diff --git a/rs/moq-mux/src/container/ts/programs.rs b/rs/moq-mux/src/container/ts/programs.rs index e0400a15ec4..70c21848905 100644 --- a/rs/moq-mux/src/container/ts/programs.rs +++ b/rs/moq-mux/src/container/ts/programs.rs @@ -1714,7 +1714,7 @@ mod test { ); let input = two_programs(); - let before = moq_clock::wall(); + let before = kio::clock::wall(); programs.decode(&input[..100]).unwrap(); assert!( programs.programs.is_empty(), @@ -1722,7 +1722,7 @@ mod test { ); programs.decode(&input[100..]).unwrap(); programs.finish().unwrap(); - let after = moq_clock::wall(); + let after = kio::clock::wall(); for (path, fills) in [("event/1.hang", [0xAA, 0xBB]), ("event/2.hang", [0xCC, 0xDD])] { let consumer = origin.consume().request(path, None).await.unwrap(); diff --git a/rs/moq-mux/src/container/ts/recovery_test.rs b/rs/moq-mux/src/container/ts/recovery_test.rs index 677c8c4f40e..005c46443ba 100644 --- a/rs/moq-mux/src/container/ts/recovery_test.rs +++ b/rs/moq-mux/src/container/ts/recovery_test.rs @@ -27,7 +27,7 @@ use std::ops::Range; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use mpeg2ts::pes::{PesPacketReader, ReadPesPacket}; use mpeg2ts::ts::TsPacketReader; @@ -500,7 +500,7 @@ async fn record(profile: Profile) -> Recording { .await .unwrap(); let mut groups = Vec::new(); - while let Some(mut group) = moq_clock::timeout(Duration::from_secs(1), track.recv_group()) + while let Some(mut group) = kio::clock::timeout(Duration::from_secs(1), track.recv_group()) .await .unwrap() .unwrap() @@ -907,7 +907,7 @@ async fn run(recording: &Recording, arm: &Arm) -> Run { let mut open: Vec> = producers.iter().map(|_| None).collect(); let mut kept = vec![0; producers.len()]; for (at, event) in events { - moq_clock::sleep_until(start + at).await; + kio::clock::sleep_until(start + at).await; let Some((t, g, step)) = event else { let snapshot = snapshot.clone(); catalog @@ -947,12 +947,12 @@ async fn run(recording: &Recording, arm: &Arm) -> Run { std::future::pending::<()>().await; }); - moq_clock::sleep_until(start + arm.join).await; + kio::clock::sleep_until(start + arm.join).await; let source = crate::source::announced(&consumer).await; let mut export = (open_ts(source, crate::catalog::CatalogFormat::Hang).await.unwrap()).with_delay(DELAY); let mut frames = Vec::new(); let mut samples = Vec::new(); - while let Ok(next) = moq_clock::timeout(STALL, export.next()).await { + while let Ok(next) = kio::clock::timeout(STALL, export.next()).await { let Some(frame) = next.expect("export error") else { break; }; diff --git a/rs/moq-mux/src/container/ts/release.rs b/rs/moq-mux/src/container/ts/release.rs index 7c354563594..6c319ec00ce 100644 --- a/rs/moq-mux/src/container/ts/release.rs +++ b/rs/moq-mux/src/container/ts/release.rs @@ -3,7 +3,7 @@ use std::task::Poll; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use crate::catalog::{CatalogFormat, Stream}; use crate::container::consumer::Event; @@ -53,7 +53,7 @@ impl Release { source, catalog: Some(catalog), track: None, - subscribed: moq_clock::now(), + subscribed: kio::clock::now(), finished: false, released: false, delay: Duration::ZERO, @@ -159,7 +159,7 @@ impl Release { // does not make them late, and a stall of the whole path does not hide that they are. let arrival = Arrival { arrived: arrived.max(self.subscribed), - read: moq_clock::now(), + read: kio::clock::now(), decode: frame.timestamp.into(), restart: track.markers(), // The output opens on a group, at a random access point; from then on every @@ -208,7 +208,7 @@ impl Release { false => source.live(), }; self.track = Some((m2ts.track.clone(), source)); - self.subscribed = moq_clock::now(); + self.subscribed = kio::clock::now(); } Some((name, _)) if *name != m2ts.track => { return Err(anyhow::anyhow!("the `m2ts` track moved from `{name}` to `{}`", m2ts.track).into()); diff --git a/rs/moq-mux/src/container/ts/release_test.rs b/rs/moq-mux/src/container/ts/release_test.rs index 0ff00915f2f..ceda6b254e0 100644 --- a/rs/moq-mux/src/container/ts/release_test.rs +++ b/rs/moq-mux/src/container/ts/release_test.rs @@ -7,7 +7,7 @@ use std::time::Duration; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use super::oracle::{Admitted, Loss, Object}; use super::{Passthrough, Release, fixture}; @@ -50,7 +50,7 @@ async fn import(data: &[u8]) -> Imported { .await .unwrap(); let mut objects = Vec::new(); - while let Some(mut group) = moq_clock::timeout(Duration::from_secs(1), track.recv_group()) + while let Some(mut group) = kio::clock::timeout(Duration::from_secs(1), track.recv_group()) .await .unwrap() .unwrap() @@ -114,7 +114,7 @@ fn republish_cut( let mut due = Duration::ZERO; for (i, object) in objects.into_iter().enumerate() { due = due.max(at(i, &object)); - moq_clock::sleep_until(start + due).await; + kio::clock::sleep_until(start + due).await; if group.as_ref().map(|(sequence, _)| *sequence) != Some(object.group) { if let Some((sequence, group)) = group.take() { end(sequence, group, &cut); @@ -165,7 +165,7 @@ impl Drop for Republished { /// Every object `release` writes, and when, until it ends or stalls. async fn drain(mut release: Release) -> (Vec<(Instant, Frame)>, Release) { let mut released = Vec::new(); - while let Ok(next) = moq_clock::timeout(STALL, release.next()).await { + while let Ok(next) = kio::clock::timeout(STALL, release.next()).await { let Some(frame) = next.expect("release error") else { break; }; @@ -499,9 +499,9 @@ async fn a_backlog_stays_in_the_source_until_due() { // The publisher keeps its capture pace while the sink stops polling. Sleeping // on the paused clock lets each publication wake at its own scheduled instant. - moq_clock::sleep(RECORDING).await; + kio::clock::sleep(RECORDING).await; for (index, object) in objects.iter().enumerate().skip(first + 1) { - let output = moq_clock::timeout(STALL, release.next()) + let output = kio::clock::timeout(STALL, release.next()) .await .expect("every arrived object is released") .unwrap() diff --git a/rs/moq-mux/src/container/ts/revision_test.rs b/rs/moq-mux/src/container/ts/revision_test.rs index 439114bd61e..3e8d00750b8 100644 --- a/rs/moq-mux/src/container/ts/revision_test.rs +++ b/rs/moq-mux/src/container/ts/revision_test.rs @@ -97,7 +97,7 @@ async fn reexport_frames(spans: &[(u16, &Span<'_>)], intervals: u64) -> Vec(export: &mut super::Export, frames where S::Ext: super::catalog::Catalog, { - while let Ok(frame) = moq_clock::timeout(Duration::from_millis(1), export.next()).await { + while let Ok(frame) = kio::clock::timeout(Duration::from_millis(1), export.next()).await { frames.push(frame.unwrap().expect("the export runs on")); } } @@ -131,7 +131,7 @@ where S::Ext: super::catalog::Catalog, { loop { - match moq_clock::timeout(DELAY * 10, export.next()) + match kio::clock::timeout(DELAY * 10, export.next()) .await .expect("the export ends") { @@ -421,7 +421,7 @@ async fn a_listed_track_keeps_its_descriptors() { .unwrap() .descriptors = vec![language(ENG)]; let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut audio, 0x21)], 0, 3_000).await; catalog @@ -477,7 +477,7 @@ async fn the_clock_moves_behind_the_pmt_naming_its_pid() { let (name, mut clock) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (_, mut other) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live( &mut export, @@ -554,7 +554,7 @@ async fn a_program_descriptor_change_revises_the_pmt() { .unwrap(); let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut audio, 0x21)], 0, 3_000).await; catalog.modify().unwrap().ext.mpegts.program_descriptors = vec![super::catalog::Descriptor { @@ -708,7 +708,7 @@ async fn open( frames: &mut Vec, ) -> super::Export> { let mut export = export_of(consumer).await; - let out = moq_clock::timeout(DELAY * 2, export.next()).await; + let out = kio::clock::timeout(DELAY * 2, export.next()).await; frames.push(out.expect("the tables went out").unwrap().unwrap()); settle(&mut export, frames).await; export @@ -741,7 +741,7 @@ async fn a_pid_recorded_after_its_track_takes_the_held_frames_along() { .await .unwrap(); let mut export = opened.with_delay(DELAY).with_replay(); - let out = moq_clock::timeout(DELAY * 2, export.next()).await; + let out = kio::clock::timeout(DELAY * 2, export.next()).await; let mut frames = vec![out.expect("the tables went out").unwrap().unwrap()]; settle(&mut export, &mut frames).await; @@ -796,7 +796,7 @@ async fn next(export: &mut super::Export) -> Frame where S::Ext: super::catalog::Catalog, { - let out = moq_clock::timeout(DELAY * 4, export.next()).await; + let out = kio::clock::timeout(DELAY * 4, export.next()).await; out.expect("a frame").unwrap().expect("the export runs on") } @@ -911,7 +911,7 @@ async fn a_track_taking_a_pid_over_goes_out_behind_the_tail_before_it() { let (name, mut old) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (_, mut other) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live( &mut export, @@ -972,7 +972,7 @@ async fn a_pid_that_leaves_the_pmt_is_gone_until_it_returns() { let (name, mut old) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (_, mut other) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live( &mut export, @@ -1086,7 +1086,7 @@ async fn a_pid_taken_from_a_stream_that_never_ends_cuts_it() { .unwrap(); let (name, mut old) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut old, 0x21)], 0, 2_000).await; remove(&mut catalog, &name); @@ -1132,7 +1132,7 @@ async fn a_track_recorded_on_the_pmt_pid_after_the_catalog_moves_it_takes_anothe catalog.modify().unwrap().ext.mpegts.program = Some(program(PMT_PID, 1)); let (_, mut first) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 0, 3_000).await; catalog.modify().unwrap().ext.mpegts.program = Some(program(OWN_PMT_PID, 7)); @@ -1183,7 +1183,7 @@ async fn a_moved_pmt_moves_behind_a_new_pat() { catalog.modify().unwrap().ext.mpegts.program = Some(program(PMT_PID)); let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut audio, 0x21)], 0, 3_000).await; catalog.modify().unwrap().ext.mpegts.program = Some(program(MOVED_PMT_PID)); @@ -1218,11 +1218,11 @@ async fn a_pmt_moved_onto_a_stream_fails_the_export() { catalog.modify().unwrap().ext.mpegts.program = Some(program(PMT_PID)); let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut audio, 0x21)], 0, 3_000).await; catalog.modify().unwrap().ext.mpegts.program = Some(program(AUDIO_PID)); - let err = moq_clock::timeout(DELAY * 2, async { + let err = kio::clock::timeout(DELAY * 2, async { loop { if let Err(err) = export.next().await { return err; @@ -1245,7 +1245,7 @@ async fn a_pmt_moved_onto_a_draining_stream_waits_for_it() { let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (name, mut leaving) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live( &mut export, @@ -1315,7 +1315,7 @@ async fn a_catalog_dropping_the_pmt_pid_cancels_a_waiting_move() { let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (name, mut leaving) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; let mut tracks = [(&mut audio, 0x21), (&mut leaving, 0x22)]; live(&mut export, &mut frames, start, &mut tracks, 0, 3_000).await; @@ -1342,7 +1342,7 @@ async fn a_stream_returning_to_the_pid_the_pmt_waits_for_fails_the_export() { let (name, mut leaving) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let config = catalog.snapshot().audio.renditions[&name].clone(); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; let mut tracks = [(&mut audio, 0x21), (&mut leaving, 0x22)]; live(&mut export, &mut frames, start, &mut tracks, 0, 3_000).await; @@ -1358,7 +1358,7 @@ async fn a_stream_returning_to_the_pid_the_pmt_waits_for_fails_the_export() { .tracks .insert(name, super::catalog::Track::new(OTHER_AUDIO_PID)); } - let err = moq_clock::timeout(DELAY * 2, async { + let err = kio::clock::timeout(DELAY * 2, async { loop { if let Err(err) = export.next().await { return err; @@ -1381,10 +1381,10 @@ async fn a_pmt_moved_while_its_tables_go_out_moves_behind_them() { catalog.modify().unwrap().ext.mpegts.program = Some(program(PMT_PID)); let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await.with_mux_rate(rate(4)); for millis in (0..6_000).step_by(50) { - moq_clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start + Duration::from_millis(millis)).await; match millis { // Three packets of PMT from here, in slots of four. 2_500 => { @@ -1467,7 +1467,7 @@ async fn a_revision_out_before_the_one_it_follows_takes_its_version() { .unwrap(); let (_, mut first) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 0, 3_000).await; @@ -1495,7 +1495,7 @@ async fn a_revision_out_before_the_one_it_follows_takes_its_version() { ); let (_, mut added) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); settle(&mut export, &mut frames).await; - moq_clock::sleep_until(start + Duration::from_millis(3_000)).await; + kio::clock::sleep_until(start + Duration::from_millis(3_000)).await; cue.write(Frame { timestamp: moq_net::Timestamp::from_millis(3_000).unwrap(), duration: None, @@ -1541,7 +1541,7 @@ async fn a_stream_taking_a_pid_over_leaves_the_buffer_before_it() { let (_, mut first) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (name, mut before) = aac_track(&mut broadcast, &mut catalog, Some(DATA_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live( &mut export, @@ -1577,7 +1577,7 @@ async fn a_stream_taking_a_pid_over_leaves_the_buffer_before_it() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); settle(&mut export, &mut frames).await; - moq_clock::sleep_until(start + Duration::from_millis(6_000)).await; + kio::clock::sleep_until(start + Duration::from_millis(6_000)).await; let mut section = vec![0x80, 0x7f, 0xfd]; section.resize(4_096, 0xab); private @@ -1638,7 +1638,7 @@ async fn a_stream_too_many_for_the_pmt_section_fails_the_export() { let (_, mut second) = track(&mut broadcast, &mut catalog, OTHER_AUDIO_PID); let (name, mut leaving) = track(&mut broadcast, &mut catalog, 0x105); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; let mut tracks = [(&mut first, 0x21), (&mut second, 0x21), (&mut leaving, 0x21)]; live(&mut export, &mut frames, start, &mut tracks, 0, 3_000).await; @@ -1650,13 +1650,13 @@ async fn a_stream_too_many_for_the_pmt_section_fails_the_export() { (&mut leaving, 0x21), (&mut added, 0x21), ]; - let err = moq_clock::timeout(DELAY * 2, async { + let err = kio::clock::timeout(DELAY * 2, async { loop { for (track, mark) in tracks.iter_mut() { write_marked(track, start.elapsed().as_millis() as u64, *mark); } - moq_clock::sleep(Duration::from_millis(20)).await; - while let Ok(next) = moq_clock::timeout(Duration::from_millis(1), export.next()).await { + kio::clock::sleep(Duration::from_millis(20)).await; + while let Ok(next) = kio::clock::timeout(Duration::from_millis(1), export.next()).await { if let Err(err) = next { return err; } @@ -1681,7 +1681,7 @@ async fn tracks_withdrawn_before_sending_anything_go() { .unwrap(); let (_, mut first) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 0, 3_000).await; let mut open = Vec::new(); @@ -1712,7 +1712,7 @@ async fn tracks_withdrawn_before_sending_anything_go() { async fn live( export: &mut super::Export, frames: &mut Vec, - start: moq_clock::Instant, + start: kio::clock::Instant, tracks: &mut [(&mut Writer, u8)], from: u64, to: u64, @@ -1720,7 +1720,7 @@ async fn live( S::Ext: super::catalog::Catalog, { for millis in (from..to).step_by(20) { - moq_clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start + Duration::from_millis(millis)).await; for (track, mark) in tracks.iter_mut() { write_marked(track, millis, *mark); } @@ -1757,12 +1757,12 @@ async fn the_clock_moves_behind_the_last_packet_of_the_pmt_naming_its_pid() { let (name, mut clock) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let (_, mut other) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await.with_mux_rate(rate(4)); // Frames 50 ms apart, for room beside the tables; the second track's from 500 ms, for room // beside the first tables. for millis in (0..6_000).step_by(50) { - moq_clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start + Duration::from_millis(millis)).await; match millis { ..3_000 => write_marked(&mut clock, millis, 0x21), // The revision moving the clock lays three packets of PMT, in slots of four. @@ -1817,7 +1817,7 @@ async fn a_rate_change_applies_behind_the_revision_it_comes_with() { catalog.modify().unwrap().ext.mpegts.mux_rate = Some(rate(OLD)); let (_, mut audio) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut audio, 0x21)], 0, 3_000).await; { @@ -1878,7 +1878,7 @@ async fn withdraw_and_return(listed: bool) { .unwrap(); let (_, mut first) = aac_track(&mut broadcast, &mut catalog, Some(AUDIO_PID)); let mut frames = Vec::new(); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut export = export_of(&consumer).await; live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 0, 2_000).await; diff --git a/rs/moq-mux/src/container/ts/routes_test.rs b/rs/moq-mux/src/container/ts/routes_test.rs index 161dc654a6e..79883804195 100644 --- a/rs/moq-mux/src/container/ts/routes_test.rs +++ b/rs/moq-mux/src/container/ts/routes_test.rs @@ -127,7 +127,7 @@ impl Imported { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = moq_clock::timeout(Duration::from_millis(50), reader.read_frame()).await { + while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await { frames.push(frame); } frames diff --git a/rs/moq-mux/src/container/ts/si.rs b/rs/moq-mux/src/container/ts/si.rs index 09bd8790304..a1c3295c8fc 100644 --- a/rs/moq-mux/src/container/ts/si.rs +++ b/rs/moq-mux/src/container/ts/si.rs @@ -30,7 +30,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use bytes::Bytes; use moq_net::Timestamp; @@ -628,7 +628,7 @@ impl Capture { /// the host clock ([`DEBOUNCE`]), and a first snapshot is never delayed. `force` /// overrides the debounce, for end of stream. pub fn flush(&mut self, pts: Timestamp, force: bool) -> anyhow::Result<()> { - let now = moq_clock::now(); + let now = kio::clock::now(); for (key, entry) in self.entries.iter_mut() { entry.expire(self.now); if !entry.dirty { @@ -774,7 +774,7 @@ mod tests { use super::*; use crate::container::ts::fixture::{Flags, Mux}; - #[moq_clock::test] + #[kio::test] async fn program_clock_places_and_retires_si_without_media_pts() { let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = crate::catalog::Producer::new( @@ -859,7 +859,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn incomplete_generations_expire_on_their_table_intervals() { let (mut capture, _) = capture(); let mut input = Input::new(&mut capture); @@ -897,7 +897,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn pending_renewal_replaces_its_deadline_without_renewing_other_versions() { let (mut capture, _) = capture(); let mut input = Input::new(&mut capture); @@ -921,7 +921,7 @@ mod tests { assert!(capture.entries[&(0x11, 0x42)].pending.is_empty()); } - #[moq_clock::test] + #[kio::test] async fn retirement_publishes_reduced_and_empty_snapshots_without_host_debounce() { let (mut capture, catalog) = capture(); let mut input = Input::new(&mut capture); @@ -967,13 +967,13 @@ mod tests { assert_eq!(catalog.snapshot().ext.mpegts.si[&0x10][&0x40].track, name); } - #[moq_clock::test] + #[kio::test] async fn host_time_and_new_si_at_one_input_position_do_not_age_si() { let (mut capture, _) = capture(); let input = Input::new(&mut capture); input.section(&mut capture, 0x12, section(0x4e, 0, 0, 0)); capture.flush(Timestamp::ZERO, false).unwrap(); - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; for id in 1..1024 { input.section(&mut capture, 0x12, section(0x4e, id, 0, 1)); } @@ -1032,7 +1032,7 @@ mod tests { assert_eq!(at(&clock, count), Some(4_000)); } - #[moq_clock::test] + #[kio::test] async fn fresh_si_ages_out_while_the_pcr_stalls() { for silent in [false, true] { let (mut capture, _) = capture(); @@ -1058,7 +1058,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn short_form_repetitions_replace_their_deadline_and_latest_value() { let (mut capture, _) = capture(); let mut input = Input::new(&mut capture); diff --git a/rs/moq-mux/src/follow.rs b/rs/moq-mux/src/follow.rs index 5f6222a9ef1..ccc0354ae42 100644 --- a/rs/moq-mux/src/follow.rs +++ b/rs/moq-mux/src/follow.rs @@ -128,7 +128,7 @@ mod tests { /// The next change a follower reports, which must arrive within the origin's update hold. async fn followed(follow: &mut Instances) -> Option { - let next = moq_clock::timeout(std::time::Duration::from_secs(1), follow.next()) + let next = kio::clock::timeout(std::time::Duration::from_secs(1), follow.next()) .await .expect("no change") .expect("the follow failed"); @@ -140,7 +140,7 @@ mod tests { /// The follower stays quiet past the origin's update hold. async fn quiet(follow: &mut Instances) { - if moq_clock::timeout(std::time::Duration::from_secs(1), follow.next()) + if kio::clock::timeout(std::time::Duration::from_secs(1), follow.next()) .await .is_ok() { diff --git a/rs/moq-mux/src/import/track.rs b/rs/moq-mux/src/import/track.rs index fc245053eb4..017bc9fd7d0 100644 --- a/rs/moq-mux/src/import/track.rs +++ b/rs/moq-mux/src/import/track.rs @@ -919,7 +919,7 @@ mod tests { .decode(&payload, Some(Timestamp::from_micros(1_000).unwrap())) .unwrap(); - let frame = moq_clock::timeout(Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() @@ -1239,7 +1239,7 @@ mod tests { .decode(&au, Some(Timestamp::from_micros(1_000).unwrap())) .unwrap(); - let frame = moq_clock::timeout(Duration::from_secs(1), media.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), media.read_frame()) .await .unwrap() .unwrap() @@ -1292,7 +1292,7 @@ mod tests { track, crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); - moq_clock::timeout(Duration::from_secs(1), media.read_frame()) + kio::clock::timeout(Duration::from_secs(1), media.read_frame()) .await .expect("a frame") .unwrap() diff --git a/rs/moq-mux/src/jitter.rs b/rs/moq-mux/src/jitter.rs index 726f7663995..6abf2507b9f 100644 --- a/rs/moq-mux/src/jitter.rs +++ b/rs/moq-mux/src/jitter.rs @@ -7,7 +7,7 @@ use std::pin::Pin; use std::task::Poll; use std::time::Duration; -use moq_clock::{Instant, Sleep}; +use kio::clock::{Instant, Sleep}; use moq_net::Timestamp; /// What each track may hold before its reader is held back, as the container consumer's max @@ -257,7 +257,7 @@ impl Buffer { .released .zip(first) .map_or(Duration::ZERO, |(old, new)| old.saturating_duration_since(new)); - tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "commit-clock", now = ?moq_clock::now(), old_released = ?self.active.released, new_first = ?first, ?shift, old_clock = ?self.active.clock.map(|clock| (clock.anchor, clock.base, clock.generation)), new_clock = ?engine.clock.map(|clock| (clock.anchor, clock.base, clock.generation))); + tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "commit-clock", now = ?kio::clock::now(), old_released = ?self.active.released, new_first = ?first, ?shift, old_clock = ?self.active.clock.map(|clock| (clock.anchor, clock.base, clock.generation)), new_clock = ?engine.clock.map(|clock| (clock.anchor, clock.base, clock.generation))); let offset = self.active.clock.map_or(0, |clock| clock.generation + 1); for clock in [&mut engine.clock, &mut engine.previous].into_iter().flatten() { clock.anchor = clock.anchor.checked_add(shift).ok_or(moq_net::TimeOverflow)?; @@ -1318,7 +1318,7 @@ impl Engine { fn poll_available(&mut self, waiter: &kio::Waiter, held: Option<&BTreeMap>>) -> Poll> { loop { - let now = moq_clock::now(); + let now = kio::clock::now(); let acquired = self.acquired_by(); if acquired.is_some_and(|end| now >= end) { self.acquired(); @@ -1353,7 +1353,9 @@ impl Engine { self.timer = None; return Poll::Pending; }; - let timer = self.timer.get_or_insert_with(|| Box::pin(moq_clock::sleep_until(wake))); + let timer = self + .timer + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(wake))); if timer.deadline() != wake { timer.as_mut().reset(wake); } @@ -1460,7 +1462,7 @@ impl Engine { let Some((_, _, first, ..)) = track.queue.front() else { return false; }; - let now = moq_clock::now(); + let now = kio::clock::now(); if self.delay.is_zero() || *first <= now || acquiring + track.bytes >= self.max_bytes { return true; } @@ -1474,7 +1476,7 @@ impl Engine { } let timer = track .read_timer - .get_or_insert_with(|| Box::pin(moq_clock::sleep_until(reopen))); + .get_or_insert_with(|| Box::pin(kio::clock::sleep_until(reopen))); if timer.deadline() != reopen { timer.as_mut().reset(reopen); } @@ -1586,9 +1588,9 @@ mod tests { const DELAY: Duration = Duration::from_millis(100); /// A pending publisher cannot clobber active expected tracks or automatic clock jumps. - #[moq_clock::test] + #[kio::test] async fn pending_keys_and_active_timeline_jumps_use_independent_clocks() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay(); buffer.expect([0u16]); @@ -1599,7 +1601,7 @@ mod tests { buffer.expect_pending([1, 3], [1, 3]); buffer.push(2, arrival(start, 0, "A2")).unwrap(); buffer.push(3, arrival(start, 10_000, "B3")).unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(due(&mut buffer), ["A0", "A2"]); let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B ready"); @@ -1616,17 +1618,17 @@ mod tests { 0, Arrival { restart: 1, - ..arrival(moq_clock::now(), 0, "A restart") + ..arrival(kio::clock::now(), 0, "A restart") }, ) .unwrap(); - buffer.push(3, arrival(moq_clock::now(), 10_020, "B next")).unwrap(); - moq_clock::sleep(Duration::from_millis(20)).await; + buffer.push(3, arrival(kio::clock::now(), 10_020, "B next")).unwrap(); + kio::clock::sleep(Duration::from_millis(20)).await; let Poll::Ready(next) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B clock kept its deadline"); }; assert_eq!((next.item, next.generation), ("B next", 0)); - moq_clock::sleep(delay - Duration::from_millis(20)).await; + kio::clock::sleep(delay - Duration::from_millis(20)).await; let Poll::Ready(next) = buffer.poll_next(&kio::Waiter::noop()) else { panic!("A restart ready"); }; @@ -1634,9 +1636,9 @@ mod tests { } /// A caller can hold B's first issued item, cancel before adoption, and resume A on its clock. - #[moq_clock::test] + #[kio::test] async fn cancelling_an_issued_replacement_keeps_the_active_clock() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay(); buffer.push(0u16, arrival(start, 0, "A0")).unwrap(); @@ -1646,7 +1648,7 @@ mod tests { buffer.push(1, arrival(start, 10_000, "B")).unwrap(); buffer.lose(&1, true); buffer.lose(&1, true); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(due(&mut buffer), ["A0"]); let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B ready"); @@ -1654,7 +1656,7 @@ mod tests { buffer.commit(first).unwrap(); // The commit drops A's tail. assert_eq!(buffer.reporting().dropped(), 2); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; let Poll::Ready(held) = buffer.poll_next(&kio::Waiter::noop()) else { panic!("B issued"); }; @@ -1662,12 +1664,12 @@ mod tests { buffer.cancel(); assert_eq!(buffer.reporting().dropped(), 2); assert_eq!(buffer.at(0, ms(200)), Some(start + delay + Duration::from_millis(200))); - buffer.push(0, arrival(moq_clock::now(), 200, "A resumed")).unwrap(); + buffer.push(0, arrival(kio::clock::now(), 200, "A resumed")).unwrap(); buffer.start([2], [2]); - buffer.push(2, arrival(moq_clock::now(), 20_000, "C")).unwrap(); - moq_clock::sleep(Duration::from_millis(100)).await; + buffer.push(2, arrival(kio::clock::now(), 20_000, "C")).unwrap(); + kio::clock::sleep(Duration::from_millis(100)).await; assert_eq!(due(&mut buffer), ["A resumed"]); - moq_clock::sleep(Duration::from_millis(400)).await; + kio::clock::sleep(Duration::from_millis(400)).await; let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("C ready"); }; @@ -1682,16 +1684,16 @@ mod tests { /// A cancel after commit resumes the old publisher at its next sync frame, since the frames /// after its cut tail may reference it. - #[moq_clock::test] + #[kio::test] async fn a_cancelled_commit_resumes_the_old_publisher_at_a_sync_frame() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay(); buffer.push(0u16, arrival(start, 0, "A0")).unwrap(); buffer.push(0, arrival(start, 100, "A tail")).unwrap(); buffer.start([1], [1]); buffer.push(1, arrival(start, 10_000, "B")).unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(due(&mut buffer), ["A0"]); let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B ready"); @@ -1701,32 +1703,32 @@ mod tests { assert_eq!(buffer.reporting().dropped(), 1); let delta = Arrival { sync: false, - ..arrival(moq_clock::now(), 200, "A delta") + ..arrival(kio::clock::now(), 200, "A delta") }; assert_eq!(buffer.push(0, delta).unwrap(), Push::Waiting); assert_eq!(buffer.reporting().dropped(), 2); - let key = arrival(moq_clock::now(), 300, "A key"); + let key = arrival(kio::clock::now(), 300, "A key"); assert_eq!(buffer.push(0, key).unwrap(), Push::Queued); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(due(&mut buffer), ["A key"]); } /// A restart the old publisher is still acquiring at commit is dropped with the old tail. - #[moq_clock::test] + #[kio::test] async fn a_commit_drops_the_old_publishers_acquiring_restart() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay); buffer.push(0u16, arrival(start, 0, "A0")).unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(released(&mut buffer), [("A0", 0)]); buffer.start([1], [1]); - buffer.push(1, arrival(moq_clock::now(), 10_000, "B")).unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + buffer.push(1, arrival(kio::clock::now(), 10_000, "B")).unwrap(); + kio::clock::sleep(Duration::from_millis(10)).await; buffer - .push(0, after(1, arrival(moq_clock::now(), 5_000, "A restart"))) + .push(0, after(1, arrival(kio::clock::now(), 5_000, "A restart"))) .unwrap(); - moq_clock::sleep(delay - Duration::from_millis(10)).await; + kio::clock::sleep(delay - Duration::from_millis(10)).await; let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B ready"); }; @@ -1737,9 +1739,9 @@ mod tests { } /// A replacement shifted behind what already went out fails past the clock's range. - #[moq_clock::test] + #[kio::test] async fn a_handoff_past_the_clock_range_returns_overflow() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); // A's clock runs a millisecond behind B's, so B shifts behind A's last frame out. buffer @@ -1758,7 +1760,7 @@ mod tests { }, ) .unwrap(); - moq_clock::sleep(DELAY + Duration::from_millis(1)).await; + kio::clock::sleep(DELAY + Duration::from_millis(1)).await; assert_eq!(due(&mut buffer), ["A"]); let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) else { panic!("B ready"); @@ -1769,15 +1771,15 @@ mod tests { /// Each switch goes out at the delay its replacement's clock acquired, not after the old /// program's tail, so latency does not build up switch after switch, and every frame /// after a switch is the replacement's. - #[moq_clock::test] + #[kio::test] async fn repeated_switches_keep_the_delay() { const TICK: Duration = Duration::from_millis(100); - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::::new(delay).replay(); // Publisher `key` stamps each frame `key * 100 s` past the time it sends it. let push = |buffer: &mut Buffer, key: u16| { - let now = moq_clock::now(); + let now = kio::clock::now(); let frame = Arrival { arrived: now, read: now, @@ -1796,7 +1798,7 @@ mod tests { let mut count = 0; while let Poll::Ready(ready) = buffer.poll_next(&kio::Waiter::noop()) { assert_eq!(ready.track, key, "an old frame after the switch"); - assert_eq!(moq_clock::now() - ready.item, delay); + assert_eq!(kio::clock::now() - ready.item, delay); assert!(ready.generation >= *generation); *generation = ready.generation; count += 1; @@ -1807,7 +1809,7 @@ mod tests { for _ in 0..20 { push(&mut buffer, 0); drain(&mut buffer, 0, &mut generation); - moq_clock::sleep(TICK).await; + kio::clock::sleep(TICK).await; } for key in 1..4u16 { buffer.start([key], [key]); @@ -1818,7 +1820,7 @@ mod tests { if let Poll::Ready(first) = buffer.poll_pending(&kio::Waiter::noop()) { break first; } - moq_clock::sleep(TICK).await; + kio::clock::sleep(TICK).await; }; let dropped = buffer.reporting().dropped(); buffer.commit(first).unwrap(); @@ -1827,7 +1829,7 @@ mod tests { assert_eq!(drain(&mut buffer, key, &mut generation), 1); buffer.adopted(); for _ in 0..20 { - moq_clock::sleep(TICK).await; + kio::clock::sleep(TICK).await; push(&mut buffer, key); drain(&mut buffer, key, &mut generation); } @@ -1835,9 +1837,9 @@ mod tests { assert_eq!(generation, 3); } - #[moq_clock::test] + #[kio::test] async fn decode_before_zero_keeps_its_deadline_and_media_order() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); buffer.push(2, arrival(start, 0, "audio")).unwrap(); let before_zero = Decode::from_nanos(-22_223); @@ -1855,13 +1857,13 @@ mod tests { Some(start + DELAY - Duration::from_nanos(22_223)) ); assert_eq!(buffer.at(0, ms(0)), Some(start + DELAY)); - moq_clock::sleep(DELAY).await; + kio::clock::sleep(DELAY).await; assert_eq!(due(&mut buffer), ["video", "audio"]); } - #[moq_clock::test] + #[kio::test] async fn moving_media_zero_preserves_acquisition_and_deadlines() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut negative = Buffer::new(DELAY); let mut positive = Buffer::new(DELAY); for buffer in [&mut negative, &mut positive] { @@ -1880,7 +1882,7 @@ mod tests { .unwrap(); } } - moq_clock::sleep(DELAY).await; + kio::clock::sleep(DELAY).await; assert_eq!(due(&mut negative), due(&mut positive)); for nanos in [-22_223, -11_112, 0, 11_111] { assert_eq!( @@ -1947,7 +1949,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn acquisition_observes_every_tracks_available_frames() { for order in [[1, 2], [2, 1]] { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(Duration::from_millis(500)); buffer.expect([1, 2]); // The held first frames reach the jitter buffer before the rest of the fill. @@ -1987,7 +1989,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn releases_at_the_delay_in_decode_order() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); assert_eq!(buffer.push(1, arrival(start, 0, "v0")).unwrap(), Push::Queued); assert_eq!(buffer.push(1, arrival(start, 40, "v40")).unwrap(), Push::Queued); @@ -2052,7 +2054,7 @@ mod tests { /// its deadline, emit the same order. #[tokio::test(start_paused = true)] async fn arrival_skew_does_not_change_the_order() { - let start = moq_clock::now(); + let start = kio::clock::now(); let (mut early, mut late) = (Buffer::new(DELAY).replay(), Buffer::new(DELAY).replay()); let frames = [ (1, 0, "v0"), @@ -2084,7 +2086,7 @@ mod tests { /// dropped a frame waits for its next sync frame. #[tokio::test(start_paused = true)] async fn late_frames_are_dropped_until_a_sync_frame() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(2, arrival(start, 0, "a0")).unwrap(); @@ -2154,7 +2156,7 @@ mod tests { /// A restart before anything went out keeps the clock, so the tracks stay on one. #[tokio::test(start_paused = true)] async fn a_skip_before_the_first_release_keeps_one_clock() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); // The video's first group is stale and anchors the clock; the audio is live. buffer.push(1, arrival(start, 0, "v0")).unwrap(); @@ -2182,7 +2184,7 @@ mod tests { /// runs on it, whether or not that track saw the restart. #[tokio::test(start_paused = true)] async fn every_track_joins_a_new_generation_at_its_next_frame() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(2, arrival(start, 0, "a0")).unwrap(); @@ -2192,7 +2194,7 @@ mod tests { // The publisher resumes a second later with its timeline five seconds on. let resume = start + Duration::from_secs(1); - tokio::time::advance(resume - moq_clock::now()).await; + tokio::time::advance(resume - kio::clock::now()).await; assert_eq!( buffer.push(1, after(1, arrival(resume, 5_000, "v5000"))).unwrap(), Push::Queued @@ -2218,7 +2220,7 @@ mod tests { /// clock anchors on it, the track sent latest, so it keeps the delay. #[tokio::test(start_paused = true)] async fn a_track_without_the_restart_joins_the_acquisition() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); buffer.push(1, arrival(start, 0, "v0")).unwrap(); @@ -2229,19 +2231,19 @@ mod tests { // The publisher resumes a second later with its timeline five seconds on, and sends // the audio further behind the video than the delay. let resume = start + Duration::from_secs(1); - tokio::time::advance(resume - moq_clock::now()).await; + tokio::time::advance(resume - kio::clock::now()).await; assert_eq!( buffer.push(1, after(1, arrival(resume, 5_000, "v5000"))).unwrap(), Push::Queued ); let lag = resume + DELAY + Duration::from_millis(50); - tokio::time::advance(lag - moq_clock::now()).await; + tokio::time::advance(lag - kio::clock::now()).await; assert_eq!(buffer.push(2, arrival(lag, 5_000, "a5000")).unwrap(), Push::Queued); tokio::time::advance(Duration::from_millis(20)).await; - let next = moq_clock::now(); + let next = kio::clock::now(); assert_eq!(buffer.push(2, arrival(next, 5_020, "a5020")).unwrap(), Push::Queued); - tokio::time::advance(lag + DELAY - moq_clock::now()).await; + tokio::time::advance(lag + DELAY - kio::clock::now()).await; assert_eq!(released(&mut buffer), [("v5000", 1), ("a5000", 1)]); tokio::time::advance(Duration::from_millis(20)).await; assert_eq!(released(&mut buffer), [("a5020", 1)]); @@ -2253,7 +2255,7 @@ mod tests { /// timeline 15 seconds on: each released frame's generation, and how many were dropped. async fn cross(steps: u64, tail: u64) -> (Vec, u64) { const LAG: u64 = 300; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); @@ -2276,7 +2278,7 @@ mod tests { let mut out = Vec::new(); for (read, key, restart, decode) in frames { let at = start + Duration::from_millis(read); - tokio::time::advance(at - moq_clock::now()).await; + tokio::time::advance(at - kio::clock::now()).await; out.extend(released(&mut buffer).into_iter().map(|(_, generation)| generation)); buffer.push(key, after(restart, arrival(at, decode, "frame"))).unwrap(); } @@ -2314,7 +2316,7 @@ mod tests { /// neither clock, so it drops as late without steering, and the track's next frame on the /// new timeline still joins it. async fn stray(to: u64) { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1]); buffer.push(1, arrival(start, 10_000, "v")).unwrap(); @@ -2323,12 +2325,12 @@ mod tests { assert_eq!(due(&mut buffer), ["v", "d"]); let resume = start + Duration::from_secs(1); - tokio::time::advance(resume - moq_clock::now()).await; + tokio::time::advance(resume - kio::clock::now()).await; buffer.push(1, after(1, arrival(resume, to, "v'"))).unwrap(); tokio::time::advance(DELAY).await; assert_eq!(released(&mut buffer), [("v'", 1)]); - let now = moq_clock::now(); + let now = kio::clock::now(); assert_eq!(buffer.push(2, arrival(now, 10_040, "d")).unwrap(), Push::Late); assert!(buffer.is_empty(), "the old frame was queued on the new clock"); assert!(buffer.steer.floor.is_none(), "the old frame was steered on"); @@ -2351,7 +2353,7 @@ mod tests { /// dropped, and the next on-time frame goes out on the same generation. #[tokio::test(start_paused = true)] async fn a_skip_keeps_the_clock() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.push(1, arrival(start, 0, "a0")).unwrap(); tokio::time::advance(DELAY).await; @@ -2359,7 +2361,7 @@ mod tests { // Group 1 is skipped: frames from 100 ms on arrive after a 250 ms stall. let stalled = start + Duration::from_millis(350); - tokio::time::advance(stalled - moq_clock::now()).await; + tokio::time::advance(stalled - kio::clock::now()).await; assert_eq!(buffer.push(1, arrival(stalled, 200, "a200")).unwrap(), Push::Late); assert_eq!(buffer.push(1, arrival(stalled, 300, "a300")).unwrap(), Push::Queued); tokio::time::advance(Duration::from_millis(100)).await; @@ -2371,13 +2373,13 @@ mod tests { /// marker the publisher shed, so it opens a generation. #[tokio::test(start_paused = true)] async fn a_skip_that_leaps_ahead_opens_a_generation() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.push(1, arrival(start, 0, "a0")).unwrap(); tokio::time::advance(DELAY).await; assert_eq!(due(&mut buffer), ["a0"]); - let now = moq_clock::now(); + let now = kio::clock::now(); assert_eq!(buffer.push(1, arrival(now, 5_000, "a5000")).unwrap(), Push::Queued); tokio::time::advance(DELAY).await; assert_eq!(released(&mut buffer), [("a5000", 1)]); @@ -2388,7 +2390,7 @@ mod tests { /// would cost the output a discontinuity. #[tokio::test(start_paused = true)] async fn a_fresher_frame_after_a_skip_keeps_the_clock() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1]); buffer.push(1, arrival(start, 0, "a0")).unwrap(); @@ -2397,7 +2399,7 @@ mod tests { // A second on, past a skipped group, the next frame is 20 ms less queued than the first. let resume = start + Duration::from_secs(1); - tokio::time::advance(resume - moq_clock::now()).await; + tokio::time::advance(resume - kio::clock::now()).await; assert_eq!(buffer.push(1, arrival(resume, 1_020, "a1020")).unwrap(), Push::Queued); tokio::time::advance(Duration::from_secs(1)).await; assert_eq!(released(&mut buffer), [("a1020", 0)]); @@ -2409,13 +2411,13 @@ mod tests { #[tokio::test(start_paused = true)] async fn a_track_sent_ahead_resuming_after_a_skip_keeps_the_clock() { const LEAD: u64 = 300; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); let mut out = Vec::new(); for at in (0..12_000).step_by(40) { - tokio::time::advance(start + Duration::from_millis(at) - moq_clock::now()).await; - let now = moq_clock::now(); + tokio::time::advance(start + Duration::from_millis(at) - kio::clock::now()).await; + let now = kio::clock::now(); assert_eq!(buffer.push(1, arrival(now, at, "v")).unwrap(), Push::Queued); // Track 2 is sent LEAD ahead, and skips a second of its own. let decode = at + LEAD; @@ -2440,7 +2442,7 @@ mod tests { /// clock puts earlier. #[tokio::test(start_paused = true)] async fn generations_go_out_in_turn() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(1, arrival(start, 40, "v40")).unwrap(); @@ -2449,7 +2451,7 @@ mod tests { assert_eq!(due(&mut buffer), ["v0"]); // A backlog across a jump in the timeline, read in one go. - let now = moq_clock::now(); + let now = kio::clock::now(); buffer.push(1, after(1, arrival(now, 5_000, "v5000"))).unwrap(); buffer.push(2, arrival(now, 4_900, "a4900")).unwrap(); buffer.push(2, arrival(now, 5_020, "a5020")).unwrap(); @@ -2487,8 +2489,8 @@ mod tests { /// fails. async fn drift(ppm: f64, hours: f64, settled: f64, queueing: impl Fn(f64) -> Duration) -> Run { let delay = Duration::from_millis(500); - let start = moq_clock::now(); - let clock = moq_clock::Deadlines::new(start); + let start = kio::clock::now(); + let clock = kio::clock::Deadlines::new(start); let _entered = clock.enter(); let mut buffer = Buffer::new(delay); let mut run = Run { @@ -2676,8 +2678,8 @@ mod tests { /// clock reaching us at `arrive(track, sent)`, or with the frame of its track before it if /// that is later, or never if `None`, in the order they reach us, until a push fails. async fn feed(shape: &Shape, ppm: f64, secs: f64, arrive: impl Fn(u16, f64) -> Option) -> Fed { - let start = moq_clock::now(); - let clock = moq_clock::Deadlines::new(start); + let start = kio::clock::now(); + let clock = kio::clock::Deadlines::new(start); let _entered = clock.enter(); let mut buffer = Buffer::new(shape.delay); let mut frames = Vec::new(); @@ -2821,8 +2823,8 @@ mod tests { async fn unmarked(shape: &Shape, at: f64, step: f64, secs: f64) -> Stepped { // Where the timeline starts, so a step back stays on it. const BASE: f64 = 20_000.0; - let start = moq_clock::now(); - let clock = moq_clock::Deadlines::new(start); + let start = kio::clock::now(); + let clock = kio::clock::Deadlines::new(start); let _entered = clock.enter(); let mut buffer = Buffer::new(shape.delay); buffer.expect(shape.tracks.iter().copied()); @@ -3010,7 +3012,7 @@ mod tests { /// goes out a delay after it arrived. #[tokio::test(start_paused = true)] async fn a_joiner_anchors_on_its_freshest_frame() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); let video = |arrived, decode, sync, item| Arrival { sync, @@ -3048,7 +3050,7 @@ mod tests { } let video = |decode, sync, item| Arrival { sync, - ..arrival(moq_clock::now(), decode, item) + ..arrival(kio::clock::now(), decode, item) }; buffer.push(1, video(0, true, "v0")).unwrap(); tokio::time::advance(Duration::from_millis(40)).await; @@ -3089,7 +3091,7 @@ mod tests { /// keep the delay: anchored on the video, every audio frame would be late. #[tokio::test(start_paused = true)] async fn a_joiner_anchors_on_the_track_sent_latest() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); // Video is sent 300 ms ahead of its decode time, audio as it decodes. @@ -3112,7 +3114,7 @@ mod tests { /// the one sent latest, but two delays at most. #[tokio::test(start_paused = true)] async fn the_acquisition_waits_two_delays_at_most_for_a_silent_track() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); buffer.push(1, arrival(start, 0, "v0")).unwrap(); @@ -3126,7 +3128,7 @@ mod tests { /// moment each was read. #[tokio::test(start_paused = true)] async fn a_steering_step_does_not_reorder_a_tie() { - let start = moq_clock::now(); + let start = kio::clock::now(); let order = |first: (u16, &'static str), second: (u16, &'static str)| { let mut buffer = Buffer::new(DELAY).replay(); buffer.push(1, arrival(start, 0, "v0")).unwrap(); @@ -3146,7 +3148,7 @@ mod tests { /// acquisition ends when the first of them falls due rather than drop it. #[tokio::test(start_paused = true)] async fn the_acquisition_ends_before_a_held_frame_is_due() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY); // Joined 60 ms into a group: its keyframe is due 40 ms from now. let key = Arrival { @@ -3172,7 +3174,7 @@ mod tests { /// frame behind the clock still goes out. #[tokio::test(start_paused = true)] async fn zero_delay_releases_on_arrival() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(Duration::ZERO); buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(1, arrival(start, 40, "v40")).unwrap(); @@ -3189,7 +3191,7 @@ mod tests { /// keep their own admission windows. #[tokio::test(start_paused = true)] async fn admission_respects_due_output_the_future_tail_and_each_tracks_lead() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut buffer = Buffer::new(DELAY).replay(); assert!(!buffer.full(&1, &kio::Waiter::noop())); buffer.push(1, arrival(start, 0, "v0")).unwrap(); @@ -3236,14 +3238,14 @@ mod tests { /// A fast track must leave its future backlog in the source beside a real-time track. #[tokio::test(start_paused = true)] async fn admission_bounds_a_fast_track_beside_an_honest_track() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay(); let mut next = [0, 0]; let mut peak = 0; for step in 0..6_000 { let at = start + Duration::from_millis(step * 20); - tokio::time::advance(at.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; for (key, speed) in [(0, 1), (1, 3)] { while next[key] <= step * 20 * speed && !buffer.full(&(key as u16), &kio::Waiter::noop()) { buffer.push(key as u16, arrival(at, next[key], "frame")).unwrap(); @@ -3259,19 +3261,19 @@ mod tests { ); } /// A sparse future frame reopens input before the frame itself is due. - #[moq_clock::test] + #[kio::test] async fn admission_wakes_when_a_future_tail_enters_the_window() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay(); buffer.push(1, arrival(start, 0, "first")).unwrap(); buffer.push(1, arrival(start, 1_500, "future")).unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; assert_eq!(due(&mut buffer), ["first"]); let reopened = kio::wait(|waiter| { loop { if !buffer.full(&1, waiter) { - return Poll::Ready(moq_clock::now()); + return Poll::Ready(kio::clock::now()); } if buffer.poll_next(waiter).is_pending() { return Poll::Pending; @@ -3292,9 +3294,9 @@ mod tests { /// Without a clock there is no time to judge a frame by, so the byte budget alone bounds what /// an acquisition copies out of the source's backlog. - #[moq_clock::test] + #[kio::test] async fn admission_bounds_the_backlog_while_acquiring_a_clock() { - let start = moq_clock::now(); + let start = kio::clock::now(); for payload in [1_000, 0] { let mut buffer = Buffer::new(Duration::from_millis(500)).with_max_bytes(10_000); for frame in 0..1_024 { @@ -3317,14 +3319,14 @@ mod tests { /// dense track back in its source while the honest track beside it keeps playing. #[tokio::test(start_paused = true)] async fn admission_bounds_a_dense_track_beside_an_honest_track() { - let start = moq_clock::now(); + let start = kio::clock::now(); let delay = Duration::from_millis(500); let mut buffer = Buffer::new(delay).replay().with_max_bytes(10_000); let mut honest = 0; let mut peak = 0; for step in 0..500u64 { let at = start + Duration::from_millis(step * 20); - tokio::time::advance(at.saturating_duration_since(moq_clock::now())).await; + tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; while honest <= step * 20 && !buffer.full(&0, &kio::Waiter::noop()) { buffer.push(0, sized(at, honest, 100)).unwrap(); honest += 20; diff --git a/rs/moq-mux/src/json.rs b/rs/moq-mux/src/json.rs index 2aa3862b5d3..9ec1e8ca899 100644 --- a/rs/moq-mux/src/json.rs +++ b/rs/moq-mux/src/json.rs @@ -36,7 +36,7 @@ //! //! A value timed on the broadcast [`Clock`](crate::Clock) is written at that timestamp as given, //! and the entry advertises how late values reach the transport as its `jitter` and `delay`, the -//! way a media rendition does. A capture [`Instant`](moq_clock::Instant) converts with +//! way a media rendition does. A capture [`Instant`](kio::clock::Instant) converts with //! [`Clock::capture`](crate::Clock::capture) on the catalog's clock: //! //! ```no_run @@ -44,7 +44,7 @@ //! # catalog: &moq_mux::catalog::Producer, //! # gps: &mut moq_mux::json::Stream, //! # fix: serde_json::Value, -//! # received: moq_clock::Instant, +//! # received: kio::clock::Instant, //! # ) -> moq_mux::Result<()> { //! let at = catalog.clock().capture(received)?; //! gps.append(moq_net::Timed::from(&fix).at(at))?; diff --git a/rs/moq-mux/src/linger.rs b/rs/moq-mux/src/linger.rs index f0cf35914a0..9f7b99a5759 100644 --- a/rs/moq-mux/src/linger.rs +++ b/rs/moq-mux/src/linger.rs @@ -21,9 +21,9 @@ pub struct Linger { // Dropped after `Drop::drop` closes the broadcasts. _owner: T, // `None` when the duration overflows the clock, so only an interrupt ends it. - deadline: Option, + deadline: Option, // Armed at the deadline, created on first poll. - timer: Option, + timer: Option, } impl Linger<()> { @@ -45,7 +45,7 @@ impl Linger { Self { broadcasts: broadcasts.into_iter().collect(), _owner: owner, - deadline: moq_clock::now().checked_add(duration), + deadline: kio::clock::now().checked_add(duration), timer: None, } } @@ -56,7 +56,7 @@ impl Linger { let Some(deadline) = self.deadline else { return Poll::Pending; }; - let timer = self.timer.get_or_insert_with(|| moq_clock::sleep_until(deadline)); + let timer = self.timer.get_or_insert_with(|| kio::clock::sleep_until(deadline)); waiter.poll_future(Pin::new(timer)) } @@ -108,10 +108,10 @@ mod tests { async fn a_late_subscriber_drains_the_tail_until_the_deadline() { let origin = crate::source::produce_origin(); let (broadcast, track) = finished(&origin); - let start = moq_clock::now(); + let start = kio::clock::now(); let linger = tokio::spawn(Linger::new([broadcast], track, Duration::from_secs(30)).wait()); - moq_clock::sleep(Duration::from_secs(29)).await; + kio::clock::sleep(Duration::from_secs(29)).await; let late = origin.consume().request(PATH, None).await.unwrap(); let video = late.track("video").unwrap(); for sequence in 0..3 { @@ -127,7 +127,7 @@ mod tests { ); linger.await.unwrap(); - assert_eq!(moq_clock::now() - start, Duration::from_secs(30)); + assert_eq!(kio::clock::now() - start, Duration::from_secs(30)); assert!(unroutable(&origin).await); } @@ -136,12 +136,12 @@ mod tests { async fn the_deadline_is_fixed_at_the_end() { let origin = crate::source::produce_origin(); let (broadcast, track) = finished(&origin); - let start = moq_clock::now(); + let start = kio::clock::now(); let linger = Linger::new([broadcast], track, Duration::from_secs(30)); - moq_clock::sleep(Duration::from_secs(20)).await; + kio::clock::sleep(Duration::from_secs(20)).await; linger.wait().await; - assert_eq!(moq_clock::now() - start, Duration::from_secs(30)); + assert_eq!(kio::clock::now() - start, Duration::from_secs(30)); } /// Dropping the handle, as an interrupt does, closes the broadcast at once. diff --git a/rs/moq-mux/src/pace.rs b/rs/moq-mux/src/pace.rs index c99eea7531b..2ac863de442 100644 --- a/rs/moq-mux/src/pace.rs +++ b/rs/moq-mux/src/pace.rs @@ -1,6 +1,6 @@ //! Pacing of media frames onto the wall clock. -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; use moq_net::Timestamp; @@ -248,7 +248,7 @@ mod tests { /// frame onto the anchor. #[test] fn paces_across_timescales() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::from_millis(500)); // A PCR slot at microsecond scale anchors the stream. @@ -266,7 +266,7 @@ mod tests { /// panics on a large but valid `Duration` (`--delay` is unbounded). #[test] fn huge_lead_does_not_overflow() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::MAX); assert_eq!(pacer.pace(ms(0), start), start); assert_eq!(pacer.pace(ms(40), start), start + Duration::from_millis(40)); @@ -279,7 +279,7 @@ mod tests { /// arrival cadence rather than the media one. #[test] fn absorbs_a_standing_delivery_lag() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::from_millis(500)); assert_eq!(pacer.pace(ms(0), start), start, "the first frame anchors at now"); @@ -299,7 +299,7 @@ mod tests { /// rather than growing with every outlier. #[test] fn absorbed_lag_is_capped_by_the_lead() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::from_millis(50)); assert_eq!(pacer.pace(ms(0), start), start); @@ -316,7 +316,7 @@ mod tests { /// Zero lead (SRT, whose receiver owns the jitter buffer) absorbs nothing. #[test] fn zero_lead_absorbs_nothing() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default(); assert_eq!(pacer.pace(ms(0), start), start); @@ -327,7 +327,7 @@ mod tests { #[test] fn hurry_makes_the_frame_the_live_edge() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::from_millis(500)); assert_eq!(pacer.pace(ms(0), start), start); @@ -343,7 +343,7 @@ mod tests { /// onto a re-anchor the delay itself provoked. #[test] fn the_delay_is_outside_the_lead_comparison() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); assert_eq!(pacer.pace(ms(0), start), start + Duration::from_millis(100)); @@ -361,7 +361,7 @@ mod tests { /// playback back toward live rather than leaving it there for the session. #[test] fn an_earlier_arrival_re_anchors_and_keeps_the_delay() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); // The first frame was produced 500ms ago; nothing here knows that yet. @@ -386,7 +386,7 @@ mod tests { /// present at it: the offset playback holds behind the edge has to survive. #[test] fn hurry_keeps_the_delay() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); assert_eq!(pacer.hurry(ms(800), start), start + Duration::from_millis(100)); @@ -399,7 +399,7 @@ mod tests { /// second arrival in. #[test] fn due_reads_the_anchor_without_moving_it() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); assert_eq!(pacer.due(ms(0)), None, "no anchor until the first frame"); @@ -415,7 +415,7 @@ mod tests { #[test] fn lead_schedules_bursts_into_the_future() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::from_millis(500)); assert_eq!(pacer.pace(ms(0), start), start); diff --git a/rs/moq-mux/src/rate.rs b/rs/moq-mux/src/rate.rs index 113f2031d53..ddccff5fcaf 100644 --- a/rs/moq-mux/src/rate.rs +++ b/rs/moq-mux/src/rate.rs @@ -12,7 +12,7 @@ use std::{ time::Duration, }; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::bandwidth; @@ -116,11 +116,11 @@ pub enum Target { /// ``` /// # use moq_mux::rate::{Control, Policy, Target}; /// # use moq_net::bandwidth; -/// # use moq_clock::Instant; +/// # use kio::clock::Instant; /// let mut control = Control::new(Policy::new(bandwidth::Rate::from_mbps(4))); /// // A 2 Mbps estimate takes the 4 Mbps target down to what the link will carry. /// assert_eq!( -/// control.update(Some(bandwidth::Rate::from_mbps(2)), moq_clock::now()), +/// control.update(Some(bandwidth::Rate::from_mbps(2)), kio::clock::now()), /// Some(Target::Enabled(bandwidth::Rate::from_mbps(2))) /// ); /// @@ -131,7 +131,7 @@ pub enum Target { /// let mut control = Control::new(policy); /// control.set_probed(true); /// assert_eq!( -/// control.update(Some(bandwidth::Rate::from_mbps(3)), moq_clock::now()), +/// control.update(Some(bandwidth::Rate::from_mbps(3)), kio::clock::now()), /// Some(Target::Disabled) /// ); /// ``` @@ -428,7 +428,7 @@ pub struct Follower { grant: bandwidth::Consumer, control: Control, /// Armed at the control's deadline, created on first use. - timer: Option, + timer: Option, /// Feed the current grant on the next poll, after [`set_policy`](Self::set_policy) /// changed it. refeed: bool, @@ -478,7 +478,7 @@ impl Follower { self.grant.peek() }; self.control.set_probed(self.grant.probed()); - if let Some(target) = self.control.update(estimate, moq_clock::now()) { + if let Some(target) = self.control.update(estimate, kio::clock::now()) { return Poll::Ready(Ok(target)); } } @@ -496,7 +496,7 @@ impl Follower { /// step from now, so a quiet grant still retries and a sender that keeps failing /// is not hammered. Does nothing once another poll has fed the grant. pub fn failed(&mut self) { - self.control.failed(moq_clock::now()); + self.control.failed(kio::clock::now()); } fn poll_deadline(&mut self, waiter: &kio::Waiter) -> Poll<()> { @@ -504,7 +504,7 @@ impl Follower { self.timer = None; return Poll::Pending; }; - let timer = self.timer.get_or_insert_with(|| moq_clock::sleep_until(at)); + let timer = self.timer.get_or_insert_with(|| kio::clock::sleep_until(at)); if timer.deadline() != at { timer.reset(at); } @@ -550,7 +550,7 @@ mod tests { let mut control = control(); // A 2 Mbps pipe: take the target down to it at once, no ramp, no waiting. assert_eq!( - control.update(Some(bps(2_000_000)), moq_clock::now()), + control.update(Some(bps(2_000_000)), kio::clock::now()), Some(on(bps(2_000_000))) ); assert_eq!(control.target(), on(bps(2_000_000))); @@ -559,7 +559,7 @@ mod tests { #[test] fn missing_estimate_holds_the_target() { let mut control = control(); - let now = moq_clock::now(); + let now = kio::clock::now(); control.update(Some(bps(2_000_000)), now).unwrap(); // Losing the estimate (disconnected) is not evidence the uplink is @@ -572,7 +572,7 @@ mod tests { fn estimate_never_raises_above_max() { let mut control = control(); // A wildly optimistic estimate is not licence to exceed what was configured. - assert_eq!(control.update(Some(bps(100_000_000)), moq_clock::now()), None); + assert_eq!(control.update(Some(bps(100_000_000)), kio::clock::now()), None); assert_eq!(control.target(), on(bps(4_000_000))); } @@ -580,14 +580,14 @@ mod tests { fn target_never_falls_below_min() { let mut control = control(); // A near-dead uplink floors at min (max/10) rather than chasing to zero. - assert_eq!(control.update(Some(bps(1)), moq_clock::now()), Some(on(bps(400_000)))); + assert_eq!(control.update(Some(bps(1)), kio::clock::now()), Some(on(bps(400_000)))); assert_eq!(control.target(), on(bps(400_000))); } #[test] fn raise_is_ramp_limited() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); // target 1M // The pipe reopens to 4 Mbps. One second later the default 25%/s ramp @@ -606,7 +606,7 @@ mod tests { #[test] fn suppressed_raises_do_not_starve_the_ramp() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); // target 1M // Tick at 100ms: each tick alone is under the 5% threshold. @@ -632,7 +632,7 @@ mod tests { #[test] fn a_raise_reaching_the_ceiling_beats_hysteresis() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); // Walk up until it settles, then confirm where it settled. @@ -658,7 +658,7 @@ mod tests { #[test] fn upward_jitter_stays_inside_the_deadband() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(2_000_000)), start).unwrap(); // target 2M, well under the 4M ceiling // A 0.5% rise: inside the 5% deadband, and nowhere near the ceiling. @@ -690,7 +690,7 @@ mod tests { #[test] fn small_moves_are_suppressed() { let mut control = control(); - let now = moq_clock::now(); + let now = kio::clock::now(); control.update(Some(bps(2_000_000)), now).unwrap(); // target 2M // 2% under the current target: inside the 5% deadband, so no reconfigure. @@ -712,7 +712,7 @@ mod tests { let mut control = Control::new(policy); assert_eq!(control.target(), on(bps(1_000_000))); - assert_eq!(control.update(Some(bps(2_000_000)), moq_clock::now()), None); + assert_eq!(control.update(Some(bps(2_000_000)), kio::clock::now()), None); assert_eq!(control.target(), on(bps(1_000_000))); } @@ -739,7 +739,7 @@ mod tests { #[test] fn a_quiet_grant_recovers_on_deadlines() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); assert_eq!(control.deadline(), None, "a drop lands at once"); @@ -764,7 +764,7 @@ mod tests { /// band could leave a deadline that applies nothing and spins its caller. #[test] fn every_deadline_applies_a_change() { - let start = moq_clock::now(); + let start = kio::clock::now(); for max in [15, 20, 21, 999, 1_000_003, 4_000_000, 1 << 50] { for floor in [1, max / 10, max / 3, max - max / 25] { let mut control = Control::new(Policy::new(bps(max))); @@ -781,7 +781,7 @@ mod tests { #[test] fn reaching_the_estimate_clears_the_deadline() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); assert_eq!( control.update(Some(bps(1_100_000)), start + Duration::from_secs(1)), @@ -795,7 +795,7 @@ mod tests { #[test] fn a_climb_below_the_ceiling_settles_in_the_deadband() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); control .update(Some(bps(2_000_000)), start + Duration::from_secs(1)) @@ -811,7 +811,7 @@ mod tests { /// not scheduled, whether it is all of the raise or what one step leaves over. #[test] fn a_raise_inside_the_deadband_is_not_scheduled() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut whole = control(); whole.update(Some(bps(2_000_000)), start).unwrap(); assert_eq!(whole.update(Some(bps(2_050_000)), start + Duration::from_secs(1)), None); @@ -830,7 +830,7 @@ mod tests { /// Losing the estimate or a drop cancels a scheduled raise. #[test] fn a_missing_estimate_or_a_drop_clears_the_deadline() { - let start = moq_clock::now(); + let start = kio::clock::now(); let scheduled = || { let mut control = control(); control.update(Some(bps(1_000_000)), start).unwrap(); @@ -858,7 +858,7 @@ mod tests { #[test] fn a_failed_raise_is_retried() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); control .update(Some(bps(4_000_000)), start + Duration::from_secs(1)) @@ -889,7 +889,7 @@ mod tests { #[test] fn a_failed_drop_is_retried() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); control.failed(start); assert_eq!(control.target(), on(bps(4_000_000))); @@ -905,7 +905,7 @@ mod tests { #[test] fn a_failure_after_no_change_does_nothing() { let mut control = control(); - let start = moq_clock::now(); + let start = kio::clock::now(); control.update(Some(bps(2_000_000)), start).unwrap(); assert_eq!( control.update(Some(bps(1_960_000)), start + Duration::from_secs(1)), @@ -932,7 +932,7 @@ mod tests { let mut applied = Vec::new(); let mut refused = false; // A minute without a wake is far past anything the ramp still needs. - while let Ok(target) = moq_clock::timeout(Duration::from_secs(60), follower.next()).await { + while let Ok(target) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await { let Target::Enabled(target) = target.unwrap() else { panic!("a policy without a lower rendition disabled the sender") }; @@ -962,7 +962,7 @@ mod tests { // The 3 Mbps grant no longer fits under the new 2 Mbps ceiling, which is where a // new policy starts, so nothing moves until the grant does. assert!( - moq_clock::timeout(Duration::from_secs(60), follower.next()) + kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .is_err() ); @@ -971,7 +971,7 @@ mod tests { assert_eq!(follower.next().await.unwrap(), on(bps(3_000_000))); follower.set_policy(Policy::new(bps(4_000_000))); assert!( - moq_clock::timeout(Duration::from_secs(60), follower.next()) + kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .is_err() ); @@ -986,7 +986,7 @@ mod tests { let mut follower = Follower::new(grant.consume(), Policy::new(bps(2_000_000))); grant.set(Some(bps(2_000_000))).unwrap(); assert!( - moq_clock::timeout(Duration::from_secs(60), follower.next()) + kio::clock::timeout(Duration::from_secs(60), follower.next()) .await .is_err(), "settled at the 2 Mbps ceiling" @@ -1012,7 +1012,7 @@ mod tests { follower.set_policy(policy); let mut applied = Vec::new(); - while let Ok(target) = moq_clock::timeout(Duration::from_secs(60), follower.next()).await { + while let Ok(target) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await { applied.push(target.unwrap()); } assert_eq!(applied.last(), Some(&on(bps(4_000_000))), "{applied:?}"); @@ -1052,7 +1052,7 @@ mod tests { #[test] fn a_rung_disables_below_its_boundary() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); // Squeezed, but still inside its band: it adapts like any sender. assert_eq!(rung.update(Some(bps(3_500_000)), start), Some(on(bps(3_500_000)))); @@ -1069,7 +1069,7 @@ mod tests { fn the_lowest_rung_never_disables() { let mut lowest = Control::new(Policy::new(bps(350_000))); lowest.set_probed(true); - assert_eq!(lowest.update(Some(bps(1)), moq_clock::now()), Some(on(bps(35_000)))); + assert_eq!(lowest.update(Some(bps(1)), kio::clock::now()), Some(on(bps(35_000)))); } /// Without a session probing for it, a stopped rendition could never see the estimate @@ -1079,7 +1079,7 @@ mod tests { let mut rung = rung(); rung.set_probed(false); assert_eq!( - rung.update(Some(bps(1_000_000)), moq_clock::now()), + rung.update(Some(bps(1_000_000)), kio::clock::now()), Some(on(bps(1_000_000))) ); } @@ -1089,7 +1089,7 @@ mod tests { #[test] fn a_disabled_rung_resumes_when_probing_stops() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(1_000_000)), start), Some(Target::Disabled)); rung.set_probed(false); @@ -1102,7 +1102,7 @@ mod tests { #[test] fn a_rung_resumes_past_the_hysteresis_and_ramps() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); // Back over the boundary, but not by the 5% hysteresis: stay off. @@ -1125,7 +1125,7 @@ mod tests { #[test] fn jitter_at_the_boundary_does_not_flap() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); rung.update(Some(bps(3_400_000)), start).unwrap(); // About 3% either side of the boundary, every 100ms for 10s. @@ -1149,7 +1149,7 @@ mod tests { #[test] fn a_missing_estimate_holds_a_disabled_rung() { let mut rung = rung(); - let now = moq_clock::now(); + let now = kio::clock::now(); rung.update(Some(bps(1_000_000)), now).unwrap(); assert_eq!(rung.update(None, now + Duration::from_secs(10)), None); assert_eq!(rung.target(), Target::Disabled); @@ -1163,7 +1163,7 @@ mod tests { policy.lower = Some(bps(950_000)); let mut rung = Control::new(policy); rung.set_probed(true); - let now = moq_clock::now(); + let now = kio::clock::now(); assert_eq!(rung.update(Some(bps(500_000)), now), Some(Target::Disabled)); assert_eq!( rung.update(Some(bps(10_000_000)), now + Duration::from_secs(1)), @@ -1178,7 +1178,7 @@ mod tests { policy.lower = Some(bps(1_000_000)); let mut rung = Control::new(policy); rung.set_probed(true); - assert_eq!(rung.update(Some(bps(1)), moq_clock::now()), Some(on(bps(100_000)))); + assert_eq!(rung.update(Some(bps(1)), kio::clock::now()), Some(on(bps(100_000)))); } /// A disable or resume the sender failed to apply is taken back and retried, so the @@ -1186,7 +1186,7 @@ mod tests { #[test] fn a_failed_toggle_is_retried() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); rung.failed(start); assert_eq!(rung.target(), on(bps(5_000_000))); @@ -1210,7 +1210,7 @@ mod tests { #[test] fn a_failed_resume_under_the_margin_stops_retrying() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); let resumed = start + Duration::from_secs(1); assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333)))); @@ -1228,7 +1228,7 @@ mod tests { fn a_rung_under_its_boundary_disables_when_probing_starts() { let mut rung = rung(); rung.set_probed(false); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(on(bps(3_000_000)))); let mut funded = rung.clone(); @@ -1250,7 +1250,7 @@ mod tests { #[test] fn a_rung_under_a_raised_boundary_disables() { let mut rung = rung(); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_500_000)), start), Some(on(bps(3_500_000)))); // The boundary moves from 3.33 Mbps to 3.67 Mbps, over the applied target. @@ -1299,7 +1299,7 @@ mod tests { controls.push(control); tracks.push(track); } - let start = moq_clock::now(); + let start = kio::clock::now(); let mut update = |at: Instant| -> Vec { controls .iter_mut() @@ -1527,7 +1527,7 @@ mod tests { policy.lower = lower.map(bps); let mut model = Model { control: Control::new(policy), - now: moq_clock::now(), + now: kio::clock::now(), grant: None, probed: false, }; diff --git a/rs/moq-mux/src/source.rs b/rs/moq-mux/src/source.rs index 22a4fe038f7..1dd890544cd 100644 --- a/rs/moq-mux/src/source.rs +++ b/rs/moq-mux/src/source.rs @@ -701,12 +701,12 @@ mod tests { let timeout = std::time::Duration::from_secs(5); let consumer = subscriber.consume(); - let catalog = moq_clock::timeout(timeout, consumer.follow("a/pub", None).unwrap().available()) + let catalog = kio::clock::timeout(timeout, consumer.follow("a/pub", None).unwrap().available()) .await .expect("the catalog resolves") .unwrap(); let source = Source::new(consumer, catalog); - let sibling = moq_clock::timeout(timeout, source.resolve(Some(&Relative::new("./source").unwrap()), None)) + let sibling = kio::clock::timeout(timeout, source.resolve(Some(&Relative::new("./source").unwrap()), None)) .await .expect("the sibling resolves without the stalled session") .unwrap(); @@ -718,7 +718,7 @@ mod tests { settle().await; assert!(binding.poll_broadcast(&kio::Waiter::noop()).is_pending()); let _late = healthy.publish("a/late", Default::default()).unwrap(); - let late = moq_clock::timeout(timeout, binding.broadcast()) + let late = kio::clock::timeout(timeout, binding.broadcast()) .await .expect("the later sibling resolves") .unwrap(); diff --git a/rs/moq-mux/src/stats.rs b/rs/moq-mux/src/stats.rs index a46724ace88..c9d057a6bd7 100644 --- a/rs/moq-mux/src/stats.rs +++ b/rs/moq-mux/src/stats.rs @@ -5,7 +5,7 @@ //! the catalog [`Producer`](crate::catalog::Producer) for what a publisher writes, the export //! [`Source`](crate::Source) for what a viewer reads. -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; use std::sync::{Arc, Mutex, PoisonError}; diff --git a/rs/moq-net-tests/Cargo.toml b/rs/moq-net-tests/Cargo.toml index 73fe5cb3933..9450844734c 100644 --- a/rs/moq-net-tests/Cargo.toml +++ b/rs/moq-net-tests/Cargo.toml @@ -14,7 +14,7 @@ ignored = ["tokio"] [dev-dependencies] futures = { workspace = true } -moq-clock = { path = "../moq-clock", default-features = false, features = ["sim"] } +kio = { path = "../kio", features = ["sim"] } moq-json = { path = "../moq-json" } moq-net = { path = "../moq-net", features = ["fuzz"] } serde_json = { workspace = true } diff --git a/rs/moq-net-tests/tests/integration/ietf_conformance.rs b/rs/moq-net-tests/tests/integration/ietf_conformance.rs index 7b7c8c27f2c..23e1064c41b 100644 --- a/rs/moq-net-tests/tests/integration/ietf_conformance.rs +++ b/rs/moq-net-tests/tests/integration/ietf_conformance.rs @@ -29,7 +29,7 @@ async fn routing(version: &str, cluster: bool) { let track = broadcast.create_track("test", moq_net::track::Info::default()).unwrap(); let serving = prefix.clone(); let answer = broadcast.consume(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let request = serving.requested_broadcast().await.unwrap(); assert_eq!(request.path().as_str(), NAMESPACE); moq_net::fuzz::accept(request, answer); @@ -79,14 +79,14 @@ async fn routing(version: &str, cluster: bool) { drop((links, prefix, broadcast, track)); } -#[moq_clock::test] +#[kio::test] async fn conformance_namespaces_route_through_one_relay() { for version in ["moq-transport-18"] { routing(version, false).await; } } -#[moq_clock::test] +#[kio::test] async fn conformance_namespaces_route_through_a_lite_cluster() { for version in ["moq-transport-18"] { routing(version, true).await; diff --git a/rs/moq-net-tests/tests/integration/refresh.rs b/rs/moq-net-tests/tests/integration/refresh.rs index 1f8a5931a86..5b5df917977 100644 --- a/rs/moq-net-tests/tests/integration/refresh.rs +++ b/rs/moq-net-tests/tests/integration/refresh.rs @@ -12,7 +12,7 @@ fn origin(hop: u64) -> origin::Producer { /// The JSON owner answers demand across a publisher link, a cluster peer, and a reader link. /// Existing readers keep their deltas; the late reader receives the cached group, then a new /// complete snapshot. -#[moq_clock::test] +#[kio::test] async fn json_snapshot_refresh_crosses_a_two_relay_cluster() { use moq_json::snapshot; use moq_net::{Timed, Timescale, Timestamp}; @@ -95,7 +95,7 @@ async fn json_snapshot_refresh_crosses_a_two_relay_cluster() { original.read_frame().await.unwrap().unwrap(); assert!(delta_bytes > ratio as usize * snapshot_bytes); // Simulated time passing cannot roll a group, even with deltas over the ratio. - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; assert!(producer.poll_refresh(&kio::Waiter::noop()).is_pending()); assert_eq!(track.demand().wanted(), Some(0)); @@ -103,7 +103,7 @@ async fn json_snapshot_refresh_crosses_a_two_relay_cluster() { // Poll the new reader while the owner drives refresh: a front does not join its // serving copy until read. Refresh is a request, not a hold, so the cached group // arrives first, whole, and the fresh one follows. - let (mut cached, mut fresh) = moq_clock::timeout(Duration::from_secs(1), async { + let (mut cached, mut fresh) = kio::clock::timeout(Duration::from_secs(1), async { let (refreshed, groups) = futures::join!(producer.refresh(), async { let cached = late.recv_group().await.unwrap().unwrap(); (cached, late.recv_group().await.unwrap().unwrap()) @@ -147,7 +147,7 @@ async fn json_snapshot_refresh_crosses_a_two_relay_cluster() { } } -#[moq_clock::test] +#[kio::test] async fn ratio_joins_cross_two_relays() { for name in ["moq-lite-06", "moq-lite-07-wip"] { let version: Version = name.parse().unwrap(); @@ -190,14 +190,14 @@ async fn ratio_joins_cross_two_relays() { } if name == "moq-lite-07-wip" { let mut demand = producer.demand(); - moq_clock::timeout(Duration::from_secs(1), async { + kio::clock::timeout(Duration::from_secs(1), async { while demand.wanted_changed().await.unwrap() != Some(1) {} }) .await .unwrap(); } else { // Drain runnable protocol tasks on simulated time, without a wall-clock sleep. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert_eq!(producer.demand().wanted(), Some(0)); } drop((joins, under, received, baseline, group, links)); diff --git a/rs/moq-net-tests/tests/integration/restart.rs b/rs/moq-net-tests/tests/integration/restart.rs index 175830ec888..af3214481be 100644 --- a/rs/moq-net-tests/tests/integration/restart.rs +++ b/rs/moq-net-tests/tests/integration/restart.rs @@ -38,12 +38,12 @@ async fn link(version: Version, from: &origin::Producer, to: &origin::Producer) /// Let every task settle, past the update hold. Time is paused, so this returns once /// the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// The next announce event, failing on a hang. async fn next_event(announced: &mut announce::Consumer) -> announce::Event { - moq_clock::timeout(Duration::from_secs(10), announced.next()) + kio::clock::timeout(Duration::from_secs(10), announced.next()) .await .expect("announce hung") .expect("announce ended") @@ -79,7 +79,7 @@ async fn expect_replaced(version: Version, announced: &mut announce::Consumer, p /// Nothing more arrives, past the update hold. async fn quiet(version: Version, announced: &mut announce::Consumer) { - if let Ok(event) = moq_clock::timeout(Duration::from_secs(1), announced.next()).await { + if let Ok(event) = kio::clock::timeout(Duration::from_secs(1), announced.next()).await { panic!("{version}: expected nothing more, got {event:?}"); } } @@ -93,7 +93,7 @@ fn write(track: &track::Producer, tag: &str) { /// The next frame a subscription delivers, as text. async fn read(subscription: &mut track::Subscriber) -> String { - let mut group = moq_clock::timeout(Duration::from_secs(10), subscription.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(10), subscription.recv_group()) .await .expect("subscription hung") .unwrap() @@ -152,9 +152,9 @@ async fn relay_chain(version: &str) { macro_rules! relay_chain_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, relay_chain($version)) + kio::clock::timeout(TEST_TIMEOUT, relay_chain($version)) .await .expect("timed out"); } @@ -187,7 +187,7 @@ impl Worker { ); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (claim.clone(), outputs.clone()); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(request) = handler.requested_broadcast().await { let output = broadcast::Info::new().produce(); let track = output.create_track("video", timed()).unwrap(); @@ -242,16 +242,16 @@ async fn prefix_pool(version: &str) { } } -#[moq_clock::test] +#[kio::test] async fn prefix_pool_lite06() { - moq_clock::timeout(TEST_TIMEOUT, prefix_pool("moq-lite-06")) + kio::clock::timeout(TEST_TIMEOUT, prefix_pool("moq-lite-06")) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn prefix_pool_lite07() { - moq_clock::timeout(TEST_TIMEOUT, prefix_pool("moq-lite-07-wip")) + kio::clock::timeout(TEST_TIMEOUT, prefix_pool("moq-lite-07-wip")) .await .expect("timed out"); } @@ -273,7 +273,7 @@ impl Claim { Rc::new(moq_net::fuzz::requests_route(origin, moq_net::Path::from_static("live"), route).unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (dynamic.clone(), outputs.clone()); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(request) = handler.requested_broadcast().await { let output = broadcast::Info::new().produce(); let track = output.create_track("video", timed()).unwrap(); @@ -330,7 +330,7 @@ async fn dynamic_epoch(version: &str, from: Option, to: Option) { // A re-price at the same epoch is an update at most: every handle survives. claim.update_route(claim.dynamic.route().with_cost(5)); - while let Ok(event) = moq_clock::timeout(Duration::from_secs(1), announced.next()).await { + while let Ok(event) = kio::clock::timeout(Duration::from_secs(1), announced.next()).await { assert!( matches!(event, Some(announce::Event::Update(_))), "{version}: a re-price delivered {event:?}" @@ -382,11 +382,11 @@ fn epochs() -> (Epoch, Epoch) { macro_rules! dynamic_epoch_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { let (a, b) = epochs(); for (from, to) in [(Some(a.clone()), Some(b.clone())), (Some(a), None), (None, Some(b))] { - moq_clock::timeout(TEST_TIMEOUT, dynamic_epoch($version, from, to)) + kio::clock::timeout(TEST_TIMEOUT, dynamic_epoch($version, from, to)) .await .expect("timed out"); } @@ -405,7 +405,7 @@ dynamic_epoch_tests! { /// An update does not override route selection: with a second claim still at the /// epoch, a claim dropping it hands re-requests to the second, which outranks any /// route without one. -#[moq_clock::test] +#[kio::test] async fn dynamic_epoch_second_route_keeps_winning() { let (a, _) = epochs(); let origin = produce_origin(1); @@ -427,7 +427,7 @@ async fn dynamic_epoch_second_route_keeps_winning() { // The epoch still stands through the second claim, so this is no restart, and the // instance's subscriptions resume through it. first.update_epoch(None); - while let Ok(event) = moq_clock::timeout(Duration::from_secs(1), announced.next()).await { + while let Ok(event) = kio::clock::timeout(Duration::from_secs(1), announced.next()).await { assert!( matches!(event, Some(announce::Event::Update(_))), "dropping a shared epoch delivered {event:?}" @@ -511,9 +511,9 @@ async fn retired_fetch(version: &str, explicit: bool) { macro_rules! retired_fetch_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, retired_fetch($version, false)).await.expect("timed out"); + kio::clock::timeout(TEST_TIMEOUT, retired_fetch($version, false)).await.expect("timed out"); } )* }; } @@ -553,7 +553,7 @@ async fn unanswered_takeover(version: &str) { expect_restart(version, &mut announced, "live").await; write(&old_track, "old:0"); - let next = moq_clock::timeout(Duration::from_secs(10), subscription.recv_group()) + let next = kio::clock::timeout(Duration::from_secs(10), subscription.recv_group()) .await .expect("subscription hung"); match next { @@ -567,9 +567,9 @@ async fn unanswered_takeover(version: &str) { macro_rules! unanswered_takeover_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, unanswered_takeover($version)).await.expect("timed out"); + kio::clock::timeout(TEST_TIMEOUT, unanswered_takeover($version)).await.expect("timed out"); } )* }; } @@ -582,14 +582,14 @@ unanswered_takeover_tests! { unanswered_takeover_lite07: "moq-lite-07-wip", } -#[moq_clock::test] +#[kio::test] async fn retired_fetch_explicit_epoch_control() { - moq_clock::timeout(TEST_TIMEOUT, retired_fetch("moq-lite-07-wip", true)) + kio::clock::timeout(TEST_TIMEOUT, retired_fetch("moq-lite-07-wip", true)) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn withdrawal_refuses_new_fetches_but_keeps_open_reads() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let version: Version = version.parse().unwrap(); @@ -612,7 +612,7 @@ async fn withdrawal_refuses_new_fetches_but_keeps_open_reads() { } } -#[moq_clock::test] +#[kio::test] async fn a_more_specific_source_cannot_fill_a_held_covering_track() { for name in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let version: Version = name.parse().unwrap(); @@ -654,7 +654,7 @@ impl Pool { let outputs = Rc::new(RefCell::new(std::collections::HashMap::new())); let answered = Rc::new(RefCell::new(0)); let (handler, served, count) = (claim.clone(), outputs.clone(), answered.clone()); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(request) = handler.requested_broadcast().await { let path = request.path().to_string(); let prepared = request.prepare(Epoch::mint()).unwrap(); @@ -737,9 +737,9 @@ async fn claim_restart(version: &str) { macro_rules! claim_restart_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, claim_restart($version)) + kio::clock::timeout(TEST_TIMEOUT, claim_restart($version)) .await .expect("timed out"); } @@ -814,11 +814,11 @@ async fn priority_update(version: &str, relayed: bool, switch: bool) { macro_rules! priority_update_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { for relayed in [false, true] { for switch in [false, true] { - moq_clock::timeout(TEST_TIMEOUT, priority_update($version, relayed, switch)) + kio::clock::timeout(TEST_TIMEOUT, priority_update($version, relayed, switch)) .await .expect("timed out"); } diff --git a/rs/moq-net/AGENTS.md b/rs/moq-net/AGENTS.md index 89d798d36a7..19c3fb7943c 100644 --- a/rs/moq-net/AGENTS.md +++ b/rs/moq-net/AGENTS.md @@ -16,5 +16,5 @@ The wire layer. Generic over the transport and media-agnostic: the relay never i # Testing -- Tests never use tokio or the wall clock. Prefer a plain `#[test]` that polls with explicit instants; async bodies use `#[moq_clock::test]`, whose simulated time jumps only when every task is stalled. tokio is for the benches. +- Tests never use tokio or the wall clock. Prefer a plain `#[test]` that polls with explicit instants; async bodies use `#[kio::test]`, whose simulated time jumps only when every task is stalled. tokio is for the benches. - `just rs fuzz ` (one per file in `fuzz/fuzz_targets/`) needs nightly. The target bodies live in `src/fuzz.rs`; `fuzz/regressions//` replays under `just check`, so commit every crash input there. diff --git a/rs/moq-net/Cargo.toml b/rs/moq-net/Cargo.toml index ddaff4c7a5f..d0f3460b673 100644 --- a/rs/moq-net/Cargo.toml +++ b/rs/moq-net/Cargo.toml @@ -15,7 +15,7 @@ categories = ["multimedia", "network-programming", "web-programming"] [features] default = ["async"] # Runtime-backed helpers and Lite/IETF sessions; explicit-time model drivers stay available. -async = ["dep:futures", "moq-clock/runtime"] +async = ["dep:futures", "kio/runtime"] # Exposes the wire codecs to the `fuzz/` harness and the announce, codec, path, varint, frame, and canonical storage benches, # and session views of an origin to the viewers bench, through the hidden `fuzz` module. Off by @@ -32,7 +32,6 @@ futures = { workspace = true, optional = true } hashbrown = { workspace = true } hashlink = { workspace = true } kio = { workspace = true, features = ["macros"] } -moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false } moq-pattern = { workspace = true, features = ["serde"] } num_enum = { workspace = true } rand = { workspace = true } @@ -48,7 +47,7 @@ uuid = { workspace = true } criterion = { package = "bench-harness", path = "../bench-harness" } futures = { workspace = true } # The tests' executor, with simulated time. -moq-clock = { path = "../moq-clock", features = ["sim"] } +kio = { path = "../kio", features = ["runtime", "sim"] } proptest = { workspace = true } serde_json = { workspace = true } # The benches run on tokio. test-util (tokio::time::pause/advance) is test-only, so diff --git a/rs/moq-net/benches/memory.rs b/rs/moq-net/benches/memory.rs index 090d053e06b..ab5f261b2b9 100644 --- a/rs/moq-net/benches/memory.rs +++ b/rs/moq-net/benches/memory.rs @@ -95,7 +95,7 @@ fn runtime() -> tokio::runtime::Runtime { } fn now() -> moq_net::time::Instant { - moq_clock::now() + kio::clock::now() } /// One publisher and one subscriber session over an in-memory pair. diff --git a/rs/moq-net/benches/origin.rs b/rs/moq-net/benches/origin.rs index f1319c13a18..7ceee27db72 100644 --- a/rs/moq-net/benches/origin.rs +++ b/rs/moq-net/benches/origin.rs @@ -1481,7 +1481,7 @@ impl Generation { async fn announce(&self, epoch: &Epoch) { self.route(epoch); for track in &self.tracks { - moq_clock::timeout(COPY_WAIT, support::wanted(track.demand())) + kio::clock::timeout(COPY_WAIT, support::wanted(track.demand())) .await .expect("route swap did not splice") .expect("replacement track closed"); @@ -1511,14 +1511,14 @@ async fn copy_walk(tracks: usize, copies: usize) -> CopyWalk { let epoch = Epoch::mint(); let first = Generation::build(&producer, tracks); first.route(&epoch); - let resolved = moq_clock::timeout(COPY_WAIT, producer.consume().request(COPY_PATH, None)) + let resolved = kio::clock::timeout(COPY_WAIT, producer.consume().request(COPY_PATH, None)) .await .expect("front did not resolve") .expect("front refused"); let mut subscribers = Vec::with_capacity(tracks); for i in 0..tracks { let track = resolved.track(&format!("{i}")).unwrap(); - let subscriber = moq_clock::timeout(COPY_WAIT, track.subscribe(None)) + let subscriber = kio::clock::timeout(COPY_WAIT, track.subscribe(None)) .await .expect("track did not splice") .expect("subscribe failed"); @@ -1672,7 +1672,7 @@ async fn resume_overlap(shape: ResumeShape, ordered: bool) -> ResumeOverlap { (broadcast, track) }; let mut generations = vec![generation(&mut (0..retained))]; - let resolved = moq_clock::timeout(COPY_WAIT, producer.consume().request(COPY_PATH, None)) + let resolved = kio::clock::timeout(COPY_WAIT, producer.consume().request(COPY_PATH, None)) .await .expect("front did not resolve") .expect("front refused"); @@ -1681,7 +1681,7 @@ async fn resume_overlap(shape: ResumeShape, ordered: bool) -> ResumeOverlap { let subscription = track::Subscription::default().with_max_delay(Duration::from_secs(3600)); let mut subscribers = Vec::with_capacity(readers); for _ in 0..readers { - let subscriber = moq_clock::timeout(COPY_WAIT, track.subscribe(subscription.clone())) + let subscriber = kio::clock::timeout(COPY_WAIT, track.subscribe(subscription.clone())) .await .expect("track did not splice") .expect("subscribe failed"); @@ -1699,7 +1699,7 @@ async fn resume_overlap(shape: ResumeShape, ordered: bool) -> ResumeOverlap { generation(&mut (0..retained).rev()) }); let (_, latest) = generations.last().unwrap(); - moq_clock::timeout(COPY_WAIT, support::wanted(latest.demand())) + kio::clock::timeout(COPY_WAIT, support::wanted(latest.demand())) .await .expect("route swap did not splice") .expect("replacement track closed"); diff --git a/rs/moq-net/benches/session/mod.rs b/rs/moq-net/benches/session/mod.rs index 87f7b47fd1f..2032db72277 100644 --- a/rs/moq-net/benches/session/mod.rs +++ b/rs/moq-net/benches/session/mod.rs @@ -1409,7 +1409,7 @@ impl IdleRoom { async fn measure(&self, iters: u64) -> Duration { let start = Instant::now(); for _ in 0..iters { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } start.elapsed() } @@ -1468,7 +1468,7 @@ pub(crate) fn withdrawal(c: &mut Criterion) { .unwrap() }) .collect(); - while moq_clock::timeout(Duration::from_secs(1), announced.next()) + while kio::clock::timeout(Duration::from_secs(1), announced.next()) .await .is_ok() {} @@ -1476,7 +1476,7 @@ pub(crate) fn withdrawal(c: &mut Criterion) { drop(live); let mut retracted = 0; while let Ok(Some(event)) = - moq_clock::timeout(Duration::from_secs(1), announced.next()).await + kio::clock::timeout(Duration::from_secs(1), announced.next()).await { assert!(matches!(event, moq_net::announce::Event::End(_)), "{event:?}"); retracted += 1; diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 7fa0d90f905..ee6eeff6d5a 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -2541,7 +2541,7 @@ impl Enforce { mod tests { use super::*; - #[moq_clock::test] + #[kio::test] async fn a_request_waits_for_an_unanswered_token() { let handle = Link::new(true); let setup = handle.present(Bytes::new(), true).unwrap(); @@ -3125,7 +3125,7 @@ mod request_token_tests { /// A request token reaches the app's acceptor like any other token, and the grant the /// app answers is what the verdict resolves to. - #[moq_clock::test] + #[kio::test] async fn a_request_token_reaches_the_acceptor() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3141,7 +3141,7 @@ mod request_token_tests { /// An AUTH token has no type, so a request token of any type but out-of-band cannot reach /// the acceptor as one: it is unsupported, never handed over as if it were a plain token. - #[moq_clock::test] + #[kio::test] async fn a_typed_request_token_is_unsupported() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3178,7 +3178,7 @@ mod request_token_tests { /// request message, not the AUTH stream, so `requests()` stays live on a session whose /// `supported` is false, even once the peer turns out not to speak AUTH. This is the shape /// a standard moq-transport peer presents when it does not negotiate the AUTH extension. - #[moq_clock::test] + #[kio::test] async fn a_request_token_is_verified_without_the_auth_extension() { let handle = Link::new(false); let mut requests = handle.handle().requests(); @@ -3194,7 +3194,7 @@ mod request_token_tests { /// With no `requests()` consumer, a request token cannot be verified in band, so the verdict /// is Unsupported and the caller refuses the request NOT_SUPPORTED. - #[moq_clock::test] + #[kio::test] async fn no_consumer_refuses_a_request_token_as_unsupported() { let handle = Link::new(true); let verdict = handle.verify_request(token(b"jwt", 0), None); @@ -3204,7 +3204,7 @@ mod request_token_tests { /// A refused request token resolves to the refusal, which the caller sends the peer as /// UNAUTHORIZED. - #[moq_clock::test] + #[kio::test] async fn a_refused_request_token_is_unauthorized() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3219,7 +3219,7 @@ mod request_token_tests { /// A grant the acceptor revoked, dropped or replaced before the verdict was read is admitted /// as it stands now, never as first issued. - #[moq_clock::test] + #[kio::test] async fn a_grant_ended_before_admission_is_refused() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3250,7 +3250,7 @@ mod request_token_tests { /// The grant lives exactly as long as the request: dropping the verdict ends the /// acceptor's issued grant, so it never outlives the request nor joins the union. - #[moq_clock::test] + #[kio::test] async fn dropping_the_verdict_ends_the_grant() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3264,7 +3264,7 @@ mod request_token_tests { /// A request token never joins the session union: the union stays what the connection /// credential earned, not what a request token granted. - #[moq_clock::test] + #[kio::test] async fn a_request_token_never_joins_the_union() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3291,7 +3291,7 @@ mod request_token_tests { /// The session's scope for unnamed requests is the connection credential's grant and every /// grant issued to an AUTH token, and nothing a request token earned: a token on one /// request never widens what tokenless requests may do. - #[moq_clock::test] + #[kio::test] async fn the_scope_is_session_tokens_only() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3337,7 +3337,7 @@ mod request_token_tests { } /// Revoking or dropping an AUTH token's grant takes it out of the scope. - #[moq_clock::test] + #[kio::test] async fn an_ended_auth_grant_leaves_the_scope() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3359,7 +3359,7 @@ mod request_token_tests { /// A session never authorized is bound by its origin handles alone, whatever its AUTH /// tokens were granted: the scope only exists once the connection credential has a grant. - #[moq_clock::test] + #[kio::test] async fn an_unauthorized_session_has_no_scope() { let handle = Link::new(true); let mut requests = handle.handle().requests(); @@ -3382,7 +3382,7 @@ mod request_token_tests { } /// The request grant carries the acceptor's expiry, which is the deadline it lapses at. - #[moq_clock::test] + #[kio::test] async fn a_request_grant_has_the_acceptors_expiry() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3407,7 +3407,7 @@ mod request_token_tests { /// A grant that has already expired never admits the request or renews it, even for the /// moment before its deadline would fire. - #[moq_clock::test] + #[kio::test] async fn an_already_expired_grant_is_refused() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3455,7 +3455,7 @@ mod request_token_tests { } /// An accepted REQUEST_UPDATE replaces the grant and its expiry. - #[moq_clock::test] + #[kio::test] async fn a_renewal_token_replaces_the_grant_and_expiry() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3493,7 +3493,7 @@ mod request_token_tests { /// With no accepted renewal, the deadline ends the request as Expired, and the /// session is not closed by it. - #[moq_clock::test] + #[kio::test] async fn the_deadline_expires_the_request_without_renewal() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3519,7 +3519,7 @@ mod request_token_tests { /// A renewal the acceptor granted before the old deadline lapsed keeps the request, even /// when the serve loop applies it only after the deadline. - #[moq_clock::test] + #[kio::test] async fn a_granted_renewal_outlives_the_old_deadline() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3541,7 +3541,7 @@ mod request_token_tests { let second = grant_in(&runtime, 600); let second_expires = second.expires; let _issued2 = requests.next().await.unwrap().accept(second); - moq_clock::sleep(Duration::from_secs(61)).await; + kio::clock::sleep(Duration::from_secs(61)).await; let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await; assert!(pending, "the lapsed deadline ended a request whose renewal was granted"); @@ -3557,7 +3557,7 @@ mod request_token_tests { /// untouched and ends only when its own deadline lapses. The serve loops end the request on /// a refusal separately (a refused renewal ends only that request); this covers only that /// the grant object is not mutated. - #[moq_clock::test] + #[kio::test] async fn a_refused_renewal_leaves_the_grant() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3603,7 +3603,7 @@ mod request_token_tests { /// An acceptor-side update that no longer covers the request ends it, even when the /// replacement has no expiry to lapse at; one that still covers it is folded in. - #[moq_clock::test] + #[kio::test] async fn an_update_that_stops_covering_ends_the_request() { let runtime = crate::time::sim(); let handle = Link::new(true); @@ -3627,7 +3627,7 @@ mod request_token_tests { assert!(pending, "a covering update keeps the request"); issued.update(Grant::default()); - let err = moq_clock::timeout( + let err = kio::clock::timeout( Duration::from_secs(1), kio::wait(|waiter| request_grant.poll_ended(waiter)), ) @@ -3686,7 +3686,7 @@ mod request_token_tests { /// An acceptor-side revoke ends the request before the deadline, and does not close the /// session. - #[moq_clock::test] + #[kio::test] async fn an_acceptor_revoke_ends_the_request() { let runtime = crate::time::sim(); let handle = Link::new(true); diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index 625342e9e0a..86716eeadeb 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -828,8 +828,8 @@ mod tests { ); // Start the returned driver after the handshake completes. - let (_session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (_session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); // Verify the client offered every configured moq-lite version over the `moql` SETUP. let mut setup_bytes = Bytes::from(fake.control_writes()); @@ -863,7 +863,7 @@ mod tests { /// `connect` for the life of the session, since it waited for the initial announce /// set. Resolving a path you need is `request`'s job, which waits for /// that path rather than for the peer to finish talking. - #[moq_clock::test] + #[kio::test] async fn connect_does_not_wait_for_the_peer_to_announce() { // Serves bidi streams, so the announce stream opens, and never answers on them. let gate = kio::Producer::new(true); @@ -878,9 +878,9 @@ mod tests { // Paused time auto-advances while every task is idle, so a `connect` that waits // on the silent peer trips this rather than hanging the suite. - let (_session, _driver) = moq_clock::timeout( + let (_session, _driver) = kio::clock::timeout( std::time::Duration::from_secs(30), - client.connect(moq_clock::now(), transport), + client.connect(kio::clock::now(), transport), ) .await .expect("connect waited on a peer that never announced") @@ -961,12 +961,12 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn alpn_lite_falls_back_to_moql_setup_and_switches_version_post_setup() { run_alpn_lite_fallback_case(Some(ALPN_LITE)).await; } - #[moq_clock::test] + #[kio::test] async fn no_alpn_falls_back_to_moql_setup_and_switches_version_post_setup() { run_alpn_lite_fallback_case(None).await; } @@ -1138,14 +1138,14 @@ mod tests { // `stats()` reads the machine's latest sample and primes the sampler, so a // periodic poller observes fresh counters without consuming the bandwidth // channel. - #[moq_clock::test] + #[kio::test] async fn stats_reads_prime_the_sampler() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()); fake.set_send_rate(Some(1_000_000)); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); - let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); // The construction-time snapshot, before the machine sampled anything. assert_eq!( @@ -1157,7 +1157,7 @@ mod tests { // so the new rate shows up within an interval (paused time auto-advances). fake.set_send_rate(Some(2_000_000)); while session.stats().estimated_send_rate != Some(crate::bandwidth::Rate::from_bps(2_000_000)) { - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + kio::clock::sleep(std::time::Duration::from_millis(10)).await; } } @@ -1167,15 +1167,15 @@ mod tests { // the construction-time snapshot: this backend reports no send rate, so // there is no bandwidth consumer keeping the sampler ticking, and the test // never reads stats while the session is live. - #[moq_clock::test] + #[kio::test] async fn stats_capture_the_final_counters() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()); fake.set_send_rate(None); fake.set_sent_bytes(0); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); - let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); assert!( session.send_bandwidth().is_none(), "no send-rate estimate, so nothing samples on its own" @@ -1196,20 +1196,20 @@ mod tests { // The send-bandwidth sampler lives inside the driver: it samples as soon as a // consumer exists and keeps sampling on its interval. Simulated time makes // the interval fire deterministically. - #[moq_clock::test] + #[kio::test] async fn send_bandwidth_samples_while_the_driver_runs() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()); fake.set_send_rate(Some(1_000_000)); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); - let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); + let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); let mut bandwidth = session.send_bandwidth().expect("backend reports an estimate"); assert_eq!( bandwidth.peek(), Some(crate::bandwidth::Rate::from_bps(1_000_000)), "the estimate is readable before the sampler first runs" ); - moq_clock::sim::spawn(crate::time::run(driver)); + kio::clock::sim::spawn(crate::time::run(driver)); assert_eq!( bandwidth.changed().await.unwrap(), @@ -1234,20 +1234,20 @@ mod tests { /// Run the driver until the sender's target reads `bps`. async fn probes_to(fake: &FakeSession, bps: u64) { while fake.probe_target() != bps { - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } } // The session probes for every reservation on its allocator, demanded or not: a // stopped rendition loses its viewers, and still has to be funded to resume. - #[moq_clock::test] + #[kio::test] async fn the_sender_probes_to_the_reservations() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe(); fake.set_send_rate(Some(1_000_000)); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); - let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); let bandwidth = session.allocator(); let (_watched_broadcast, watched) = reservable(); @@ -1270,12 +1270,12 @@ mod tests { // An override replaces the sum, zero turns probing off, and clearing it follows the // reservations again. - #[moq_clock::test] + #[kio::test] async fn an_override_replaces_the_reservations() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe(); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); - let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); let bandwidth = session.allocator(); let (_broadcast, track) = reservable(); @@ -1294,7 +1294,7 @@ mod tests { // A reconnecting caller dials every session with one allocator, so a reservation // taken before the reconnect still moves the next session's target. - #[moq_clock::test] + #[kio::test] async fn a_reconnect_keeps_following_the_reservations() { let bandwidth = crate::bandwidth::Allocator::default(); let client = Client::new() @@ -1305,16 +1305,16 @@ mod tests { let reserved = bandwidth.reserve(&track.demand(), crate::bandwidth::Rate::from_bps(4_000_000)); let first = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe(); - let (session, driver) = client.connect(moq_clock::now(), first.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (session, driver) = client.connect(kio::clock::now(), first.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); probes_to(&first, 4_000_000).await; session.abort(Error::Cancel); session.closed().await; drop(session); let second = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe(); - let (_session, driver) = client.connect(moq_clock::now(), second.clone()).await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + let (_session, driver) = client.connect(kio::clock::now(), second.clone()).await.unwrap(); + kio::clock::sim::spawn(crate::time::run(driver)); probes_to(&second, 4_000_000).await; reserved.update(crate::bandwidth::Rate::from_bps(3_000_000)); diff --git a/rs/moq-net/src/coding/stream.rs b/rs/moq-net/src/coding/stream.rs index 93699c86f69..f158991473a 100644 --- a/rs/moq-net/src/coding/stream.rs +++ b/rs/moq-net/src/coding/stream.rs @@ -166,7 +166,7 @@ mod tests { /// starves it: quinn schedules strictly by priority and round-robins only /// within a level, so a rank-0 group with bytes pending is enough to keep /// the scheduler from ever reaching the transport's default of 0. - #[moq_clock::test] + #[kio::test] async fn open_prioritises_the_stream() { let gate = kio::Producer::new(true); let mut session = SinkSession::gated_bi(gate.consume()); @@ -184,7 +184,7 @@ mod tests { /// The accepted half answers on the stream it was handed (track info, subscribe /// responses), so it needs the same order as one we opened. A fix that only /// covered `open` would leave every reply behind the media. - #[moq_clock::test] + #[kio::test] async fn accept_prioritises_the_stream() { let gate = kio::Producer::new(true); let mut session = SinkSession::accepted_bi(gate.consume()); diff --git a/rs/moq-net/src/coding/writer.rs b/rs/moq-net/src/coding/writer.rs index d158ee2f780..3050ef8b1e7 100644 --- a/rs/moq-net/src/coding/writer.rs +++ b/rs/moq-net/src/coding/writer.rs @@ -336,7 +336,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn raw_payload_stop_uses_the_negotiated_registry() { for (version, expected) in [ ( @@ -380,7 +380,7 @@ mod tests { /// A message the stream has not taken whole cannot be finished, so closing resets rather /// than hand the peer a truncated message. - #[moq_clock::test] + #[kio::test] async fn closing_an_unflushed_message_resets() { let log = Log::default(); let budget = kio::Producer::new(0); diff --git a/rs/moq-net/src/ietf/auth.rs b/rs/moq-net/src/ietf/auth.rs index dd5f4e87047..108efd3206a 100644 --- a/rs/moq-net/src/ietf/auth.rs +++ b/rs/moq-net/src/ietf/auth.rs @@ -605,7 +605,7 @@ mod tests { use crate::Pattern; #[cfg(feature = "async")] - #[moq_clock::test] + #[kio::test] async fn auth_refused_without_credit_spends_no_request_id() { for version in [Version::Draft18] { for client in [false, true] { diff --git a/rs/moq-net/src/ietf/peer.rs b/rs/moq-net/src/ietf/peer.rs index 415dc86825c..5150035d1fa 100644 --- a/rs/moq-net/src/ietf/peer.rs +++ b/rs/moq-net/src/ietf/peer.rs @@ -140,7 +140,7 @@ mod tests { /// The announce loops read the peer's declaration once and hold it, while /// subscription serving re-reads it. A second SETUP overwriting the identity would /// split those two apart, so the first write is the one that counts. - #[moq_clock::test] + #[kio::test] async fn first_write_wins() { let first = Peer { cluster: cluster::Peer { @@ -176,7 +176,7 @@ mod tests { } /// MoQ Epoch needs both sides: a peer declaring it to a side that declined leaves it off. - #[moq_clock::test] + #[kio::test] async fn epoch_needs_our_offer_too() { let declared = Peer { epoch: true, diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 648d57209fa..d990c0e7f23 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -5793,7 +5793,7 @@ mod group_priority_test { use crate::ietf::priority; use crate::lite::test_transport::SinkSession; - #[moq_clock::test] + #[kio::test] async fn standalone_end_of_track_does_not_claim_end_of_group() { let log = crate::lite::test_transport::Log::default(); let session = SinkSession::new(log.clone()); @@ -5822,7 +5822,7 @@ mod group_priority_test { /// The standalone END_OF_TRACK stream ranks as the group it ends, not at the raw /// subscriber priority. - #[moq_clock::test] + #[kio::test] async fn standalone_end_of_track_ranks_as_its_group() { let log = crate::lite::test_transport::Log::default(); let queue = PriorityQueue::default(); @@ -5847,7 +5847,7 @@ mod group_priority_test { /// Cancelled while its FIN waits for the acknowledgement, a ranked stream resets as it /// gives up its rank, rather than sending on with a send order the queue has reused. - #[moq_clock::test] + #[kio::test] async fn a_ranked_stream_cancelled_after_its_fin_resets() { let log = crate::lite::test_transport::Log::default(); let queue = PriorityQueue::default(); @@ -5881,7 +5881,7 @@ mod group_priority_test { assert_eq!(rival.current(), 0, "and released its rank"); } - #[moq_clock::test] + #[kio::test] async fn exact_end_of_track_survives_the_final_group_fin() { use crate::lite::test_transport::Sent; for version in [Version::Draft18, Version::Draft20, Version::Draft22] { @@ -5946,7 +5946,7 @@ mod group_priority_test { /// An inline END_OF_TRACK spares the standalone marker only once its stream is /// acknowledged: a stream reset after its FIN may never deliver it. - #[moq_clock::test] + #[kio::test] async fn an_unacknowledged_inline_end_of_track_is_not_sent() { for acked in [true, false] { let mut session = SinkSession::new(Default::default()); @@ -6001,7 +6001,7 @@ mod group_priority_test { ); assert!(!terminal.sent.load(Ordering::Relaxed), "not until acknowledged"); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -6029,7 +6029,7 @@ mod group_priority_test { /// lower ones"), matching the transport trait's send order, so the higher-priority /// subscription's group stream must get the higher send order. An inversion here /// would transmit the LOWEST-priority track first under contention. - #[moq_clock::test] + #[kio::test] async fn group_stream_preserves_model_priority() { let log = crate::lite::test_transport::Log::default(); let queue = PriorityQueue::default(); @@ -6082,7 +6082,7 @@ mod group_priority_test { /// prefers when it has no subscriber preference to go on, so it has to reach the wire. /// It went out as a flat 0 before, which put catalog, audio, and video in one tier for /// every moq-transport peer. - #[moq_clock::test] + #[kio::test] async fn group_header_carries_the_publisher_priority() { let header = serve_group_header(track::Info::timed().with_priority(hang_audio_priority())).await; assert_eq!( @@ -6099,7 +6099,7 @@ mod group_priority_test { /// A track that never set a priority goes out at the midpoint, 127, one step off the /// draft's usual 128 so it mirrors moq-lite's 128, and not 255, the least urgent value a /// peer like moxygen would deprioritize. - #[moq_clock::test] + #[kio::test] async fn group_header_defaults_to_the_midpoint() { let header = serve_group_header(track::Info::timed()).await; assert_eq!(header.publisher_priority, 127); @@ -6153,7 +6153,7 @@ mod group_priority_test { } /// A track that always has another group ready yields within its budget. - #[moq_clock::test] + #[kio::test] async fn a_busy_track_yields_to_its_siblings() { /// `TrackServe`'s passes per poll; each starts at most one group. const BUDGET: usize = 32; @@ -6299,7 +6299,7 @@ mod group_priority_test { } /// A group with more objects ready than one poll's budget drains over several polls. - #[moq_clock::test] + #[kio::test] async fn a_long_group_drains_within_the_budget() { /// `GroupServe`'s passes per poll; each writes at most one object. const BUDGET: usize = 32; @@ -6387,14 +6387,14 @@ mod group_priority_test { async fn settle_serve(serve: &mut TrackServe) { for _ in 0..8 { let _ = serve.poll(&kio::Waiter::noop()); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } } /// A peer withholding stream credit makes each subscription hold one group machine, /// however many tracks it subscribes to and groups they publish: the backlog waits in the /// cache. Granting credit then serves every group still worth sending. - #[moq_clock::test] + #[kio::test] async fn withheld_credit_holds_one_group_machine_per_subscription() { for (tracks, groups) in [(1, 1), (1, 64), (16, 1), (16, 64)] { let gate = kio::Producer::new(false); @@ -6445,7 +6445,7 @@ mod group_priority_test { /// A group waiting for stream credit that the cache evicts leaves at once, rather than /// spending the credit on a reset once it arrives. The next group takes its place. - #[moq_clock::test] + #[kio::test] async fn an_evicted_group_waiting_for_credit_leaves_at_once() { let gate = kio::Producer::new(false); let track = track::Producer::new( @@ -6485,7 +6485,7 @@ mod group_priority_test { } /// A subgroup waiting for stream credit keeps its subscription expiry armed. - #[moq_clock::test] + #[kio::test] async fn group_waiting_for_stream_credit_expires() { let gate = kio::Producer::new(false); let session = SinkSession::gated_open_uni(gate.consume()); @@ -6521,7 +6521,7 @@ mod group_priority_test { "stream credit is exhausted" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -6532,7 +6532,7 @@ mod group_priority_test { /// A local group that never held the requested prefix fails rather than serving its /// tail as the whole group, with or without an end inside it. - #[moq_clock::test] + #[kio::test] async fn a_group_missing_its_prefix_fails() { for until in [None, Some(5)] { let track = track::Producer::new( @@ -6571,7 +6571,7 @@ mod group_priority_test { /// A FIN holds the subgroup's bytes until the peer acknowledges it, so a subgroup /// that goes stale while waiting still expires instead of pinning them. - #[moq_clock::test] + #[kio::test] async fn unacknowledged_fin_expires_with_the_group() { let session = SinkSession::new(Default::default()).with_unacked_fin(); let log = session.log.clone(); @@ -6608,7 +6608,7 @@ mod group_priority_test { ); assert!(log.resets().is_empty()); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -6619,7 +6619,7 @@ mod group_priority_test { } /// A stream parked on its FIN acknowledgement still follows each priority update. - #[moq_clock::test] + #[kio::test] async fn unacknowledged_fin_follows_priority_updates() { let session = SinkSession::new(Default::default()).with_unacked_fin(); let log = session.log.clone(); @@ -6670,7 +6670,7 @@ mod group_priority_test { } /// The final payload remains guarded after its frame has advanced the group cursor. - #[moq_clock::test] + #[kio::test] async fn blocked_final_transport_chunk_expires_with_the_group() { let gate = kio::Producer::new(true); let session = SinkSession::gated_uni(gate.consume()); @@ -6720,7 +6720,7 @@ mod group_priority_test { "the final byte is transport-blocked" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -6737,7 +6737,7 @@ mod subscribe_cursor_test { /// A group retention gives up on while a FETCH reads it is refused as too old, rather /// than answered with the prefix read so far. - #[moq_clock::test] + #[kio::test] async fn a_fetch_past_retention_is_refused_not_truncated() { let track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), @@ -6748,8 +6748,8 @@ mod subscribe_cursor_test { open.write_frame(crate::Timestamp::ZERO, b"a".to_vec()).unwrap(); let consumer = track.consume(); - let read = moq_clock::sim::spawn(async move { read_fetch(&consumer, 0, 0, None, 0, false).await.map(|_| ()) }); - moq_clock::sim::yield_now().await; + let read = kio::clock::sim::spawn(async move { read_fetch(&consumer, 0, 0, None, 0, false).await.map(|_| ()) }); + kio::clock::sim::yield_now().await; // The track runs a full second past the group's successor. for ms in [1000, 2000] { let mut group = track.append_group().unwrap(); @@ -6764,7 +6764,7 @@ mod subscribe_cursor_test { /// A subscription's cursor starts at the oldest cached group, so serving it verbatim /// replays every retained group at once, each on its own stream. Relays reject the burst /// and players skip straight back to the live edge, so the catch-up is pure waste. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_is_served_from_the_live_edge() { let log = Log::default(); let session = SinkSession::new(log.clone()); @@ -6808,7 +6808,7 @@ mod serve_tests { use crate::lite::test_transport::{Log, ScriptedSession, Sent, SinkSession}; use crate::model::ProduceTest; - #[moq_clock::test] + #[kio::test] async fn idle_advertisements_keep_reading_goaways() { let version = Version::Draft22; let session = ScriptedSession::new(vec![0x10, 0, 2, 0, 0]); @@ -6851,7 +6851,7 @@ mod serve_tests { assert_eq!(session.log.closes()[0].0, 0x03); } - #[moq_clock::test] + #[kio::test] async fn an_update_after_draft18_goaway_is_refused_without_closing_the_session() { let version = Version::Draft18; let h = serve(version); @@ -6890,7 +6890,7 @@ mod serve_tests { assert_eq!(body.message::(version).unwrap().error_code, 0x06); } - #[moq_clock::test] + #[kio::test] async fn a_subscription_keeps_its_goaway_count_until_the_final_marker() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -7012,7 +7012,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn requester_fin_is_version_gated_for_subscriptions() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -7057,7 +7057,7 @@ mod serve_tests { } /// A reset request stream still cancels the subscription on every draft. - #[moq_clock::test] + #[kio::test] async fn requester_reset_cancels_subscriptions() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -7087,7 +7087,7 @@ mod serve_tests { /// A close must count requests before their first poll and release them even /// when a dispatched task is cancelled or its message is refused. - #[moq_clock::test] + #[kio::test] async fn drain_counts_dispatched_subscribe_and_fetch() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -7161,7 +7161,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn subscription_update_applies_priority_without_ending_the_request() { let version = Version::Draft18; let h = serve(version); @@ -7197,7 +7197,7 @@ mod serve_tests { /// A priority update moves the group streams already in flight too, not only the /// ones opened after it. - #[moq_clock::test] + #[kio::test] async fn subscription_update_reprioritizes_open_group_streams() { let version = Version::Draft18; let h = serve(version); @@ -7356,13 +7356,13 @@ mod serve_tests { what: &str, ready: impl Fn() -> bool, ) { - moq_clock::timeout(std::time::Duration::from_secs(10), async { + kio::clock::timeout(std::time::Duration::from_secs(10), async { while !ready() { assert!( futures::poll!(serve.as_mut()).is_pending(), "the subscription ended before {what}" ); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } }) .await @@ -7386,7 +7386,7 @@ mod serve_tests { /// A track error ends a draft-22 subscription while its group stream waits for the /// next object. The abort reaches the group, which resets its stream before /// PUBLISH_DONE(INTERNAL_ERROR) is sent. - #[moq_clock::test] + #[kio::test] async fn publish_done_after_a_track_error_follows_every_stream_close() { let version = Version::Draft22; let h = serve(version); @@ -7404,7 +7404,7 @@ mod serve_tests { .await; h.track.abort(Error::Transport("upstream failed".into())).unwrap(); - moq_clock::timeout(std::time::Duration::from_secs(10), serve) + kio::clock::timeout(std::time::Duration::from_secs(10), serve) .await .expect("the track error ends the subscription") .ok(); @@ -7420,7 +7420,7 @@ mod serve_tests { /// A subscription that runs to the track's end counts every data stream it opened, /// the fill and the END_OF_TRACK marker included, and closes each one before /// PUBLISH_DONE(TRACK_ENDED). - #[moq_clock::test] + #[kio::test] async fn publish_done_at_the_track_end_counts_and_follows_every_stream() { let version = Version::Draft22; let h = serve(version); @@ -7439,7 +7439,7 @@ mod serve_tests { group.finish().unwrap(); h.track.finish().unwrap(); - moq_clock::timeout(std::time::Duration::from_secs(10), serve) + kio::clock::timeout(std::time::Duration::from_secs(10), serve) .await .expect("the track's end ends the subscription") .unwrap(); @@ -7455,7 +7455,7 @@ mod serve_tests { /// A finished group's stream whose FIN is never acknowledged holds PUBLISH_DONE only until /// the group goes stale: its successor's arrival plus the budget, even under a budget past /// the cache window, which evicts both groups first. - #[moq_clock::test] + #[kio::test] async fn publish_done_waits_on_an_unacknowledged_fin_until_the_group_is_stale() { let version = Version::Draft22; let session = ScriptedSession::per_stream(vec![Vec::new()]).with_unacked_uni_fins(1); @@ -7471,7 +7471,7 @@ mod serve_tests { msg.max_age = Some(budget.as_millis() as u64); // `create_broadcast` registers the broadcast from a spawned task. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; let stream = Stream::open(&mut crate::driver::Transport::new(h.session.clone()), version) .await .unwrap(); @@ -7496,7 +7496,7 @@ mod serve_tests { let step = Duration::from_secs(1); async fn wait(mut serve: std::pin::Pin<&mut F>, seconds: u64) { for _ in 0..seconds { - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; assert!( futures::poll!(serve.as_mut()).is_pending(), "PUBLISH_DONE went out early" @@ -7518,8 +7518,8 @@ mod serve_tests { wait(serve.as_mut(), budget.as_secs() - 12).await; assert!(h.log.resets().is_empty()); - moq_clock::sim::advance(step).await; - moq_clock::timeout(step, serve) + kio::clock::sim::advance(step).await; + kio::clock::timeout(step, serve) .await .expect("the stale group releases PUBLISH_DONE") .unwrap(); @@ -7533,7 +7533,7 @@ mod serve_tests { /// A track that ends with an Unsupported error (a relay refusing a copy whose metadata /// changed does) ends its subscription with INTERNAL_ERROR: UPDATE_FAILED is only for an /// update the publisher could not apply. - #[moq_clock::test] + #[kio::test] async fn an_unsupported_track_error_is_not_a_failed_update() { let version = Version::Draft18; let h = serve(version); @@ -7615,7 +7615,7 @@ mod serve_tests { // REQUEST_UPDATE, Request ID 2, one NEW_GROUP_REQUEST (0x32) of 0. request.push(&[0x02, 0, 4, 2, 1, 0x32, 0x00]); - moq_clock::timeout(std::time::Duration::from_secs(10), serve) + kio::clock::timeout(std::time::Duration::from_secs(10), serve) .await .expect("the failed update ends the subscription") .ok(); @@ -7633,7 +7633,7 @@ mod serve_tests { wire } - #[moq_clock::test] + #[kio::test] async fn publish_done_after_a_failed_update_follows_every_stream_close() { fail_update_mid_flight(Version::Draft22) .await @@ -7642,7 +7642,7 @@ mod serve_tests { /// Draft-22 §9.9: Stream Count is every data stream the publisher opened, "including /// any fill fetch streams", or 2^64-1 when it can't be exact. - #[moq_clock::test] + #[kio::test] async fn publish_done_after_a_failed_update_counts_the_open_fill() { let wire = fail_update_mid_flight(Version::Draft22).await; let (_, count) = wire.publish_done.unwrap(); @@ -7676,7 +7676,7 @@ mod serve_tests { /// FORWARD=0 drops the subscription, and its upstream demand, while the request stays /// established; FORWARD=1 subscribes again as a new SUBSCRIBE would, at the live edge. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_pauses_and_resumes_as_a_new_subscriber() { for version in [Version::Draft22] { for start_paused in [false, true] { @@ -7738,7 +7738,7 @@ mod serve_tests { /// A resume joins as a new SUBSCRIBE would, so a joining FETCH after it is served from where /// the resume joined rather than refused as the pause left it. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_after_a_resume_is_served() { let version = Version::Draft18; let h = serve(version); @@ -7770,7 +7770,7 @@ mod serve_tests { /// A resume that cannot subscribe again fails its update: REQUEST_ERROR answers it, then /// PUBLISH_DONE says UPDATE_FAILED. - #[moq_clock::test] + #[kio::test] async fn a_failed_resume_answers_its_update() { for version in [Version::Draft22] { let h = serve(version); @@ -7789,7 +7789,7 @@ mod serve_tests { h.track.abort(Error::Transport("upstream failed".into())).unwrap(); request.push(&forward_update(version, 4, true)); - moq_clock::timeout(std::time::Duration::from_secs(10), serve) + kio::clock::timeout(std::time::Duration::from_secs(10), serve) .await .expect("the failed resume ends the subscription") .unwrap_err(); @@ -7854,7 +7854,7 @@ mod serve_tests { /// A SUBSCRIBE is a join, with or without NEW_GROUP_REQUEST: a track opted in to refresh /// wants the group past one over its ratio, and SUBSCRIBE_OK advertises DYNAMIC_GROUPS. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_joins_under_the_refresh_ratio() { for version in [Version::Draft22] { for refresh in [Some(1), None] { @@ -7883,7 +7883,7 @@ mod serve_tests { } /// An absolute filter has a fixed start, so its SUBSCRIBE is no join even over the ratio. - #[moq_clock::test] + #[kio::test] async fn an_absolute_subscribe_is_no_join() { let version = Version::Draft22; let h = serve_track(version, crate::track::Info::timed().with_refresh(1)); @@ -7905,7 +7905,7 @@ mod serve_tests { /// An absolute SUBSCRIBE carrying NEW_GROUP_REQUEST asks as an update would: past a group /// the track holds, it is a join under the ratio. - #[moq_clock::test] + #[kio::test] async fn an_absolute_subscribe_with_a_new_group_request_joins() { let version = Version::Draft22; for (value, wanted) in [(0, 5), (5, 5), (4, 0)] { @@ -7932,7 +7932,7 @@ mod serve_tests { /// An update's NEW_GROUP_REQUEST is a join on a track opted in to refresh, answered with /// REQUEST_OK. One naming a group the track holds asks nothing. - #[moq_clock::test] + #[kio::test] async fn a_new_group_update_joins_a_refreshing_track() { for version in [Version::Draft22] { for (value, wanted) in [(0, 5), (5, 5), (4, 0)] { @@ -7975,7 +7975,7 @@ mod serve_tests { /// A track without refresh cannot honor a NEW_GROUP_REQUEST update, which fails the /// subscription like any update it cannot apply. - #[moq_clock::test] + #[kio::test] async fn a_new_group_update_without_refresh_fails() { for version in [Version::Draft22] { let h = serve(version); @@ -8020,7 +8020,7 @@ mod serve_tests { /// An update's AUTHORIZATION TOKEN that this endpoint cannot use closes the session with /// the draft's code, as it would on the SUBSCRIBE, not only the subscription. - #[moq_clock::test] + #[kio::test] async fn an_update_token_that_cannot_be_used_closes_the_session() { for version in [Version::Draft22] { for (token, expected, why) in [ @@ -8092,7 +8092,7 @@ mod serve_tests { /// Distinct tokens are legal but refused NOT_SUPPORTED, /// since authorizing on one would ignore the rest. Either way the session stays open, and /// a single token is answered as usual. - #[moq_clock::test] + #[kio::test] async fn a_request_with_repeated_or_several_tokens_is_refused_alone() { for (version, malformed) in [(Version::Draft22, 0x4)] { let request = |tokens: &[&[u8]]| { @@ -8139,7 +8139,7 @@ mod serve_tests { /// An update whose tokens repeat is answered MALFORMED_AUTH_TOKEN rather than /// NOT_SUPPORTED, and one with several distinct tokens NOT_SUPPORTED. Either fails only its /// subscription. - #[moq_clock::test] + #[kio::test] async fn a_repeated_or_several_update_tokens_are_refused() { let other: &[u8] = &[0x03, 0x00, 0xBB]; for (version, tokens, code) in [ @@ -8194,7 +8194,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn subscription_track_property_filter_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -8232,7 +8232,7 @@ mod serve_tests { } /// A source track failing to decode ends only the subscriptions it feeds, not the requester's session. - #[moq_clock::test] + #[kio::test] async fn source_decode_failure_keeps_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -8265,7 +8265,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn namespace_updates_do_not_postpone_an_auth_withdrawal() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -8307,7 +8307,7 @@ mod serve_tests { /// A refused namespace update waits for its REQUEST_ERROR to be acknowledged instead of /// letting the writer's drop reset discard it. - #[moq_clock::test] + #[kio::test] async fn refused_namespace_update_is_delivered_before_the_stream_ends() { let version = Version::Draft22; let h = serve(version); @@ -8343,7 +8343,7 @@ mod serve_tests { assert!(h.log.closes().is_empty(), "{version}: the session closed"); } - #[moq_clock::test] + #[kio::test] async fn namespace_updates_move_the_prefix_after_acknowledgement() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -8403,11 +8403,11 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn namespace_requester_fin_is_version_gated() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let session = ScriptedSession::per_stream_eof(vec![vec![]]); let stream = Stream::open(&mut crate::driver::Transport::new(session.clone()), version) .await @@ -8457,7 +8457,7 @@ mod serve_tests { async fn run_live(h: &mut Serve, msg: ietf::Subscribe<'static>) { // `create_broadcast` registers the broadcast from a spawned task, so yield to the // runtime before subscribing or the lookup 404s. - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; let session = h.session.clone(); let stream = Stream::open(&mut crate::driver::Transport::new(session.clone()), h.publisher.version) @@ -8483,7 +8483,7 @@ mod serve_tests { /// one re-authenticates instead of waiting for the announcement. The reply is encoded here rather than matched by code alone, so /// a value slipping outside the draft's table cannot pass, and the reason phrase is the /// origin's own, which is what carries a refusal the registry has no value for. - #[moq_clock::test] + #[kio::test] async fn a_missing_broadcast_is_refused_with_the_draft_s_code() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let error_code = 0x10; @@ -8593,7 +8593,7 @@ mod serve_tests { /// MoQ Epoch pins SUBSCRIBE, FETCH and TRACK_STATUS to the instance they name: the /// broadcast under the path now being another instance, or one with no epoch at all, /// refuses them as gone instead of serving another instance's content. - #[moq_clock::test] + #[kio::test] async fn a_request_for_another_instance_is_refused() { for version in [Version::Draft22] { let served = crate::Epoch::mint(); @@ -8635,7 +8635,7 @@ mod serve_tests { /// A SUBSCRIBE pinned to a gone instance is refused as missing even when it asks to /// wait: an instance never comes back, so there is nothing to rendezvous with. - #[moq_clock::test] + #[kio::test] async fn a_pinned_request_never_waits_for_its_instance() { for version in [Version::Draft22] { let stale = crate::Epoch::mint(); @@ -8680,7 +8680,7 @@ mod serve_tests { /// An EPOCH on a request breaks a session that did not negotiate MoQ Epoch: the peer /// cannot have learned an instance it was never told about. - #[moq_clock::test] + #[kio::test] async fn an_epoch_without_the_extension_is_a_violation() { for version in [Version::Draft22] { let h = serve(version); @@ -8718,7 +8718,7 @@ mod serve_tests { /// TRACK_STATUS gets what a SUBSCRIBE_OK would carry, as far as each draft's answer has /// room, without subscribing to the track. INCLUDE_PROPERTIES=0 empties the properties. - #[moq_clock::test] + #[kio::test] async fn track_status_is_answered_on_every_draft() { for version in ALL_VERSIONS { for wanted in [true, false] { @@ -8726,7 +8726,7 @@ mod serve_tests { let mut group = h.track.create_group(group::Info { sequence: 4 }).unwrap(); group.write_frame(timestamp(), b"a".as_slice()).unwrap(); group.write_frame(timestamp(), b"b".as_slice()).unwrap(); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; let stream = Stream::open(&mut crate::driver::Transport::new(h.session.clone()), version) .await @@ -8771,7 +8771,7 @@ mod serve_tests { /// A TRACK_STATUS outside what the peer may subscribe to is refused before the track /// resolves, and one whose grant narrows while it resolves is refused too. - #[moq_clock::test] + #[kio::test] async fn track_status_outside_the_grant_is_refused() { let nothing = || crate::auth::Grant { publish: Default::default(), @@ -8789,7 +8789,7 @@ mod serve_tests { let auth = crate::auth::Link::new(false); auth.handle().authorize(¬hing()); h.publisher = h.publisher.clone().with_auth(auth); - let code = moq_clock::timeout( + let code = kio::clock::timeout( std::time::Duration::from_secs(1), answer_code(&h, track_status("live/cam", true, version), version), ) @@ -8845,7 +8845,7 @@ mod serve_tests { /// A request's USE_VALUE token decodes but grants nothing yet, so a TRACK_STATUS outside /// the session grant is still refused. - #[moq_clock::test] + #[kio::test] async fn a_request_token_does_not_widen_the_grant() { let nothing = crate::auth::Grant { publish: Default::default(), @@ -8870,7 +8870,7 @@ mod serve_tests { /// A TRACK_STATUS answer parked on its request stream when the grant narrows is reset, /// never delivered once the stream drains. - #[moq_clock::test] + #[kio::test] async fn track_status_narrowed_while_answering_is_reset() { for version in ALL_VERSIONS { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -8916,7 +8916,7 @@ mod serve_tests { )); for _ in 0..100 { assert!(futures::poll!(answer.as_mut()).is_pending(), "{version}: never parked"); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } auth.handle().authorize(&crate::auth::Grant { @@ -8929,7 +8929,7 @@ mod serve_tests { }; *writable = true; drop(writable); - let res = moq_clock::timeout(std::time::Duration::from_secs(1), answer) + let res = kio::clock::timeout(std::time::Duration::from_secs(1), answer) .await .unwrap_or_else(|_| panic!("{version}: still answering after the grant narrowed")); assert!(matches!(res, Err(Error::Unauthorized)), "{version}: {res:?}"); @@ -8975,7 +8975,7 @@ mod serve_tests { } /// A TRACK_STATUS for a broadcast we do not serve is refused as a SUBSCRIBE would be. - #[moq_clock::test] + #[kio::test] async fn track_status_for_a_missing_broadcast_is_refused() { for version in ALL_VERSIONS { let code = refusal(version, ietf::TrackStatus::ID, track_status("absent", true, version)).await; @@ -8986,7 +8986,7 @@ mod serve_tests { /// Opting out of SUBSCRIBE_OK's properties also opts out of timestamps: with no /// TIMESCALE declared, the objects go out unstamped. - #[moq_clock::test] + #[kio::test] async fn the_properties_opt_out_strips_object_timestamps() { let version = Version::Draft22; let stamp = crate::Timestamp::from_millis(123_456).unwrap(); @@ -9040,7 +9040,7 @@ mod serve_tests { ietf::RequestError::decode(&mut buf, version).unwrap().error_code } - #[moq_clock::test] + #[kio::test] async fn range_filters_over_the_default_limit_get_invalid_filter() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let h = serve(version); @@ -9095,7 +9095,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn rendezvous_wait_is_capped_at_zero_but_answers_timeout() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { // A wait applies only to a missing publisher; a missing track on a live one does not exist. @@ -9125,7 +9125,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn reserved_namespace_requests_never_reach_the_application() { let version = Version::Draft22; for path in [".", "./child", ".session", ".session/extension"] { @@ -9159,7 +9159,7 @@ mod serve_tests { /// A namespace that overflows `Path::MAX_BYTES` under a deep root is refused per /// request, and the session stays open. - #[moq_clock::test] + #[kio::test] async fn a_namespace_too_long_under_the_root_is_refused_per_request() { for version in ALL_VERSIONS { let h = serve(version); @@ -9205,7 +9205,7 @@ mod serve_tests { /// Legal requests we don't serve are refused NOT_SUPPORTED one at a time, and the /// session stays open for the next one. - #[moq_clock::test] + #[kio::test] async fn legal_requests_we_do_not_serve_are_refused_per_request() { const NOT_SUPPORTED: u64 = 0x3; @@ -9241,7 +9241,7 @@ mod serve_tests { } /// A SUBSCRIBE_NAMESPACE always asks for namespaces, and gets NAMESPACE for each. - #[moq_clock::test] + #[kio::test] async fn subscribe_namespace_gets_namespaces() { let version = Version::Draft18; let h = serve(version); @@ -9296,7 +9296,7 @@ mod serve_tests { /// A Next Object or unfiltered join gives its current-group fill the head exactly /// once, while the subscription starts after that snapshot. - #[moq_clock::test] + #[kio::test] async fn canonical_join_serves_the_head_on_a_fetch_stream() { for filter in [Filter::NextObject, Filter::Unfiltered] { let mut h = serve(Version::Draft22); @@ -9338,7 +9338,7 @@ mod serve_tests { /// Narrowing an open subscription retires a group the new range excludes, whole or in /// part, before it forwards an object outside that range. - #[moq_clock::test] + #[kio::test] async fn narrowing_retires_an_open_live_group() { let narrowed = [ // The whole group falls below the new start. @@ -9360,7 +9360,7 @@ mod serve_tests { let h = serve(version); let mut group = h.track.create_group(group::Info { sequence: 1 }).unwrap(); group.write_frame(timestamp(), b"before-update".as_slice()).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let mut request = ScriptedSession::new(Vec::new()); request.log = h.log.clone(); let stream = Stream::open(&mut crate::driver::Transport::new(request.clone()), version) @@ -9417,7 +9417,7 @@ mod serve_tests { /// Widening with a fill hands each remaining object of the current group to exactly one /// stream: the live stream for what it still covers, and a fill tail for the rest, /// including all of it once a narrowing retired the live stream. - #[moq_clock::test] + #[kio::test] async fn widening_with_a_fill_streams_the_current_group_once() { let open = Filter::Unfiltered; // The live stream stops after object 1, which the widening lifts. @@ -9444,7 +9444,7 @@ mod serve_tests { history.finish().unwrap(); let mut group = h.track.create_group(group::Info { sequence: 1 }).unwrap(); group.write_frame(timestamp(), b"before-update".as_slice()).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let mut request = ScriptedSession::new(Vec::new()); request.log = h.log.clone(); let stream = Stream::open(&mut crate::driver::Transport::new(request.clone()), version) @@ -9515,7 +9515,7 @@ mod serve_tests { /// A fill-only update keeps a live join's floor, so a fill short of the live edge does not /// also hand the groups below that floor to the live cursor. - #[moq_clock::test] + #[kio::test] async fn a_fill_only_update_keeps_the_live_join_floor() { let version = Version::Draft22; let h = serve(version); @@ -9524,7 +9524,7 @@ mod serve_tests { history.finish().unwrap(); let mut group = h.track.create_group(group::Info { sequence: 1 }).unwrap(); group.write_frame(timestamp(), b"live".as_slice()).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let mut request = ScriptedSession::new(Vec::new()); request.log = h.log.clone(); let stream = Stream::open(&mut crate::driver::Transport::new(request.clone()), version) @@ -9573,14 +9573,14 @@ mod serve_tests { } /// An independent historical fill never expands the subscription's live bounds. - #[moq_clock::test] + #[kio::test] async fn a_historical_update_fill_keeps_the_live_bounds() { for end in [None, Some(EndLocation { group: 0, object: None })] { let version = Version::Draft22; let h = serve(version); let mut group = h.track.create_group(group::Info { sequence: 1 }).unwrap(); group.write_frame(timestamp(), b"history".as_slice()).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let mut request = ScriptedSession::new(Vec::new()); request.log = h.log.clone(); let stream = Stream::open(&mut crate::driver::Transport::new(request.clone()), version) @@ -9651,7 +9651,7 @@ mod serve_tests { /// moq-lite's own join over draft-22: Relative(1) names the start of the current /// group, so the cache replays the whole group on the subscription stream. - #[moq_clock::test] + #[kio::test] async fn relative_one_replays_the_current_group() { let mut h = serve(Version::Draft22); @@ -9671,7 +9671,7 @@ mod serve_tests { /// A Next Object subscription never receives the already-published head of the /// current group: everything below the snapshot is outside the requested range. - #[moq_clock::test] + #[kio::test] async fn next_object_does_not_replay_the_head() { let mut h = serve(Version::Draft22); @@ -9693,7 +9693,7 @@ mod serve_tests { } /// A wider fill resets its promised stream and leaves the live subscription open. - #[moq_clock::test] + #[kio::test] async fn a_multi_group_fill_is_refused_without_ending_the_subscription() { let mut h = serve(Version::Draft22); @@ -9738,7 +9738,7 @@ mod serve_tests { /// A fill ranks as the group it fills, in its subscription's GROUP_ORDER, and follows /// that rank while it is open: the queue moving it, and its subscriber priority. - #[moq_clock::test] + #[kio::test] async fn a_fill_ranks_as_the_group_it_fills() { let h = serve(Version::Draft22); let mut group = h.track.create_group(group::Info { sequence: 4 }).unwrap(); @@ -9800,7 +9800,7 @@ mod serve_tests { /// A fill of the current group outranks the live stream carrying the rest of that group, /// which the subscriber cannot use without the fill's objects first. - #[moq_clock::test] + #[kio::test] async fn a_fill_outranks_the_rest_of_its_group() { let h = serve(Version::Draft22); let mut group = h.track.create_group(group::Info { sequence: 4 }).unwrap(); @@ -9835,7 +9835,7 @@ mod serve_tests { /// A standalone FETCH competes with group streams by its subscriber priority alone, its /// request id breaking ties, whatever group and GROUP_ORDER it asks for. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_ranks_by_its_priority() { for version in [Version::Draft22] { for (group, group_order) in [(1, GroupOrder::Ascending), (3, GroupOrder::Descending)] { @@ -9859,7 +9859,7 @@ mod serve_tests { /// A joining FETCH ranks as the group it fetches in the subscription it joins, not as a /// request of its own. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_ranks_in_its_subscription() { const LATEST: u64 = 5; @@ -9913,7 +9913,7 @@ mod serve_tests { /// Yield so the broadcast registered by `serve` is visible to the lookup. async fn settle() { - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } /// Fill the track with finished groups 0..=`latest`, so the live edge is a group past 0 @@ -9976,7 +9976,7 @@ mod serve_tests { /// FETCH returns the saved multi-object prefix, including empty objects, and excludes /// later objects that belong to the subscription. Decode the wire fields independently. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_is_answered_with_fetch_ok() { const LATEST: u64 = 5; @@ -10071,7 +10071,7 @@ mod serve_tests { } /// Dispatch order must not depend on which request task gets polled first. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_waits_for_its_dispatched_subscription() { let version = Version::Draft18; let mut h = serve(version); @@ -10103,7 +10103,7 @@ mod serve_tests { assert!(h.log.resets().is_empty()); } - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_waits_for_a_reordered_subscription() { let version = Version::Draft18; let mut h = serve(version); @@ -10135,7 +10135,7 @@ mod serve_tests { assert!(h.log.resets().is_empty()); } - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_wakes_when_its_pending_subscription_is_dropped() { for version in JOINING_DRAFTS { let h = serve(version); @@ -10168,7 +10168,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_times_out_an_unresolved_subscription() { let version = Version::Draft18; let h = serve(version); @@ -10197,7 +10197,7 @@ mod serve_tests { /// The group never held the promised prefix, so the fetch itself fails and the /// refusal carries that error: refused before FETCH_OK, and never reset. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_refuses_a_missing_prefix_before_fetch_ok() { let version = Version::Draft18; let h = serve(version); @@ -10233,7 +10233,7 @@ mod serve_tests { } /// A joining FETCH whose prefix group was evicted is refused as missing before FETCH_OK. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_refuses_a_prefix_group_it_lost() { let version = Version::Draft18; let h = serve(version); @@ -10293,7 +10293,7 @@ mod serve_tests { /// A joining FETCH that arrives after its subscription ended has no live edge to name, so /// it is refused rather than answered from a group that is no longer the edge of anything. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_without_its_subscription_is_refused() { for version in JOINING_DRAFTS { let mut h = serve(version); @@ -10315,7 +10315,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_rejects_unsupported_filters() { for version in JOINING_DRAFTS { for filter in [Filter::Unfiltered, Filter::Relative(0)] { @@ -10351,7 +10351,7 @@ mod serve_tests { /// A subscription that started on an empty track has no prefix to serve, so the /// fetch range is invalid on every draft that carries joining FETCH. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_rejects_an_empty_snapshot() { for version in JOINING_DRAFTS { let h = serve(version); @@ -10416,7 +10416,7 @@ mod serve_tests { run_fetch(h, fetch_type, group_order, true).await } - #[moq_clock::test] + #[kio::test] async fn a_cached_standalone_fetch_yields_while_writing() { for version in FETCH_DRAFTS { let h = serve(version); @@ -10429,7 +10429,7 @@ mod serve_tests { let done = std::rc::Rc::new(std::cell::Cell::new(false)); let saw_payload = std::rc::Rc::new(std::cell::Cell::new(false)); - let sibling = moq_clock::sim::spawn({ + let sibling = kio::clock::sim::spawn({ let done = done.clone(); let saw_payload = saw_payload.clone(); let log = h.log.clone(); @@ -10438,7 +10438,7 @@ mod serve_tests { if log.writes.lock().unwrap().len() > 1024 { saw_payload.set(true); } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } } }); @@ -10572,7 +10572,7 @@ mod serve_tests { } /// A whole group is answered on one fetch stream. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_serves_one_whole_group() { for version in FETCH_DRAFTS { let mut h = serve(version); @@ -10602,7 +10602,7 @@ mod serve_tests { /// FETCH_OK carries the properties SUBSCRIBE_OK would, as far as each draft has room for /// them, and INCLUDE_PROPERTIES=0 empties the block. The objects carry Timestamps only /// when that block declares their units. - #[moq_clock::test] + #[kio::test] async fn fetch_ok_carries_the_track_properties() { let info = track::Info { max_age: Some(Duration::from_secs(5)), @@ -10671,7 +10671,7 @@ mod serve_tests { /// Every answer describing the track forwards the properties moq-net does not interpret /// unchanged, beside the ones it does, on every draft with a Track Properties block. - #[moq_clock::test] + #[kio::test] async fn unknown_track_properties_are_forwarded() { for version in [Version::Draft22] { let upstream = unknown_properties(version); @@ -10728,7 +10728,7 @@ mod serve_tests { } /// Immutable Properties keep the bytes their publisher sealed. - #[moq_clock::test] + #[kio::test] async fn immutable_track_properties_keep_their_encoding() { // Sealed: OBJECT_DELIVERY_TIMEOUT = 42 and DYNAMIC_GROUPS = 1. let block = [0x0b, 4, 0x02, 42, 0x2e, 1]; @@ -10772,7 +10772,7 @@ mod serve_tests { /// that boundary as an object property does: dropped when mutable, refused when sealed. /// Drafts 18 and 22 serialize alike, so across a relay hop only the track's carried /// ingress draft says which meaning it has. - #[moq_clock::test] + #[kio::test] async fn track_property_0x06_does_not_cross_to_draft_22() { let upstream = |block: &[u8]| { let properties = @@ -10831,7 +10831,7 @@ mod serve_tests { /// A range ending inside its group stops at its End Object, which draft 22 counts /// inclusively and older drafts count as one past. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_stops_at_its_end_object() { for version in FETCH_DRAFTS { let mut h = serve(version); @@ -10855,7 +10855,7 @@ mod serve_tests { /// A group holding no objects at or past the start is answered empty, on draft 22 with /// an End Location covering the range asked for (section 9.11). The whole group covers /// at least its start. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_past_the_last_object_is_empty() { for version in FETCH_DRAFTS { for (end, covered) in [(0, 2), (6, 5)] { @@ -10944,7 +10944,7 @@ mod serve_tests { /// On draft 22, a start past Largest Object is refused INVALID_RANGE (section 9.11), /// wherever the publisher knows it. Where it does not, it answers empty. A start beyond /// the final group's last object still finds the track's end there. - #[moq_clock::test] + #[kio::test] async fn a_draft22_fetch_past_the_largest_object_is_refused() { let version = Version::Draft22; for largest in [ @@ -10993,7 +10993,7 @@ mod serve_tests { /// On a live feed whose newest group finished with no objects, Largest Object sits in the /// group before it, so a draft-22 FETCH of the empty group starts past it. - #[moq_clock::test] + #[kio::test] async fn a_draft22_fetch_of_an_empty_newest_group_is_refused() { let version = Version::Draft22; let mut h = serve(version); @@ -11015,7 +11015,7 @@ mod serve_tests { /// On draft 22, an End Object past a finished group's last object is still the End /// Location reported (section 10.14), even in the group holding Largest Object, unless /// the track ends there. - #[moq_clock::test] + #[kio::test] async fn a_draft22_fetch_past_a_group_end_reports_the_requested_end() { let version = Version::Draft22; for (group, largest, reported) in [ @@ -11054,7 +11054,7 @@ mod serve_tests { /// A track whose cache only ever answered a fetch has no live feed, so its newest /// object is not Largest Object: a draft-22 FETCH past it echoes the requested end. - #[moq_clock::test] + #[kio::test] async fn a_draft22_fetch_of_a_fetch_only_cache_is_not_capped() { let version = Version::Draft22; let h = serve(version); @@ -11083,7 +11083,7 @@ mod serve_tests { /// The last group of a finished track ends the response at its last object, with End /// of Track set. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_of_the_last_group_reports_the_end_of_track() { for version in FETCH_DRAFTS { let mut h = serve(version); @@ -11111,7 +11111,7 @@ mod serve_tests { /// A bounded range ending at the last object still reports the track's end; a /// shorter prefix must not claim that the track ends there. - #[moq_clock::test] + #[kio::test] async fn a_fetch_ending_at_the_final_object_reports_the_end_of_track() { for version in FETCH_DRAFTS { for end in [1, 2] { @@ -11138,7 +11138,7 @@ mod serve_tests { /// A draft-22 filter bounded by Largest Object resolves against it, starting past it only /// for Next Object. An idle copy resolves from its upstream report, and refuses /// a relative filter when it has not learned that report. - #[moq_clock::test] + #[kio::test] async fn a_draft22_fetch_relative_to_largest_object_resolves_against_it() { for version in [Version::Draft22] { for (filter, groups) in [ @@ -11196,7 +11196,7 @@ mod serve_tests { } /// Wider requests are refused before FETCH_OK, even if their end is past the track. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_spanning_several_groups_is_refused() { for version in FETCH_DRAFTS { for order in [GroupOrder::Ascending, GroupOrder::Descending] { @@ -11219,7 +11219,7 @@ mod serve_tests { } /// A whole live group waits for its end and never claims the track ends. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_waits_for_the_largest_object_group() { for version in FETCH_DRAFTS { let mut h = serve(version); @@ -11265,7 +11265,7 @@ mod serve_tests { } /// A group that does not exist, below the newest one or past it, is refused. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_of_a_missing_group_is_refused() { for version in FETCH_DRAFTS { for missing in [2, 5] { @@ -11297,7 +11297,7 @@ mod serve_tests { /// A standalone FETCH outside what the peer may subscribe to is refused before it /// reaches the origin, and one whose grant narrows while its group loads is refused too. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_outside_the_grant_is_refused() { let unauthorized = |version| { crate::ietf::error::request::to_code( @@ -11349,7 +11349,7 @@ mod serve_tests { "{version}: served an unwritten group" ); auth.handle().authorize(¬hing); - let buf = moq_clock::timeout(std::time::Duration::from_secs(1), fetch) + let buf = kio::clock::timeout(std::time::Duration::from_secs(1), fetch) .await .unwrap_or_else(|_| panic!("{version}: still loading after the grant narrowed")); assert_eq!( @@ -11362,7 +11362,7 @@ mod serve_tests { /// A grant that narrows while a standalone FETCH waits on stream credit for its response /// stops it there: nothing it no longer may send reaches the wire. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_narrowed_while_responding_stops() { for version in FETCH_DRAFTS { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -11423,7 +11423,7 @@ mod serve_tests { if session.log.writes.lock().unwrap().len() > mark { break; } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!( session.log.writes.lock().unwrap().len() > mark, @@ -11435,7 +11435,7 @@ mod serve_tests { subscribe: Default::default(), expires: None, }); - let res = moq_clock::timeout(std::time::Duration::from_secs(1), fetch) + let res = kio::clock::timeout(std::time::Duration::from_secs(1), fetch) .await .unwrap_or_else(|_| panic!("{version}: still responding after the grant narrowed")); assert!(matches!(res, Err(Error::Unauthorized)), "{version}: {res:?}"); @@ -11446,7 +11446,7 @@ mod serve_tests { /// A joining FETCH answers from its subscription's cache, which outlives the /// subscription, so it holds its own gate: one parked on stream credit when the grant /// narrows stops there, and nothing reaches the wire once credit returns. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_narrowed_while_responding_stops() { const PAYLOAD: &[u8] = b"joined-prefix"; @@ -11529,7 +11529,7 @@ mod serve_tests { if session.log.writes.lock().unwrap().len() > mark { break; } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!( session.log.writes.lock().unwrap().len() > mark, @@ -11541,7 +11541,7 @@ mod serve_tests { subscribe: Default::default(), expires: None, }); - let res = moq_clock::timeout(std::time::Duration::from_secs(1), fetch) + let res = kio::clock::timeout(std::time::Duration::from_secs(1), fetch) .await .unwrap_or_else(|_| panic!("{version}: still responding after the grant narrowed")); assert!(matches!(res, Err(Error::Unauthorized)), "{version}: {res:?}"); @@ -11579,7 +11579,7 @@ mod serve_tests { /// Past FETCH_OK, a joining FETCH finishes its head on its own authority: the subscription /// ending leaves it to finish, but the token that authorized the subscription still ends /// it, before or after the subscription has. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_outlives_its_subscription_but_not_its_token() { const PAYLOAD: &[u8] = b"joined-prefix"; for (version, end) in JOINING_DRAFTS.into_iter().flat_map(|version| { @@ -11678,7 +11678,7 @@ mod serve_tests { if session.log.writes.lock().unwrap().len() > mark { break; } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!( session.log.writes.lock().unwrap().len() > mark, @@ -11702,7 +11702,7 @@ mod serve_tests { futures::poll!(fetch.as_mut()).is_pending(), "{version} {end:?}: the fetch ended with its subscription" ); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } if end == JoinEnd::RevokedAfter { let enforced = enforced.take().expect("a token"); @@ -11715,7 +11715,7 @@ mod serve_tests { }; *open = true; drop(open); - let res = moq_clock::timeout(std::time::Duration::from_secs(1), fetch) + let res = kio::clock::timeout(std::time::Duration::from_secs(1), fetch) .await .unwrap_or_else(|_| panic!("{version} {end:?}: the fetch never ended")); let finished = matches!(end, JoinEnd::Ended | JoinEnd::TokenEnded); @@ -11724,7 +11724,7 @@ mod serve_tests { false => assert!(matches!(res, Err(Error::Unauthorized)), "{version} {end:?}: {res:?}"), } if let Some(subscription) = subscription { - let _ = moq_clock::timeout(std::time::Duration::from_secs(1), subscription) + let _ = kio::clock::timeout(std::time::Duration::from_secs(1), subscription) .await .unwrap_or_else(|_| panic!("{version}: the revoked subscription kept serving")); } @@ -11744,7 +11744,7 @@ mod serve_tests { h: Serve, serving: std::pin::Pin>>>, renewal: crate::auth::Request, - fetch: moq_clock::sim::JoinHandle>, + fetch: kio::clock::sim::JoinHandle>, /// The gate holding the fetch's answer back, shut. _credit: kio::Producer, _first: crate::auth::Issued, @@ -11797,7 +11797,7 @@ mod serve_tests { .await .unwrap(); let mark = h.log.writes.lock().unwrap().len(); - let fetch = moq_clock::sim::spawn(h.publisher.clone().run_fetch_stream( + let fetch = kio::clock::sim::spawn(h.publisher.clone().run_fetch_stream( stream, ietf::Fetch { request_id: FETCH_ID, @@ -11817,7 +11817,7 @@ mod serve_tests { if h.log.writes.lock().unwrap().len() > mark { break; } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!(h.log.writes.lock().unwrap().len() > mark, "FETCH_OK never went out"); settle().await; @@ -11837,14 +11837,14 @@ mod serve_tests { /// A refused renewal ends the token's authority, not only the subscription: a joining /// FETCH already past FETCH_OK stops serving under the refused token rather than finishing /// on the old grant, while the subscription still ends with UPDATE_FAILED. - #[moq_clock::test] + #[kio::test] async fn a_refused_renewal_ends_an_answered_joining_fetch() { let join = answered_join().await; // Credit stays shut: the refusal alone must wake the fetch parked on it. The // subscription's request then waits on the fetch, which holds its token's slot. join.renewal.reject(crate::SessionError::Unauthorized, "no"); - let served = moq_clock::timeout(Duration::from_secs(1), join.serving) + let served = kio::clock::timeout(Duration::from_secs(1), join.serving) .await .expect("the refused subscription kept serving"); assert!( @@ -11855,7 +11855,7 @@ mod serve_tests { .publish_done .expect("PUBLISH_DONE was sent"); assert_eq!(status, ietf::PublishDoneStatus::UpdateFailed.code(), "UPDATE_FAILED"); - let res = moq_clock::timeout(Duration::from_secs(1), join.fetch) + let res = kio::clock::timeout(Duration::from_secs(1), join.fetch) .await .expect("the fetch never ended") .expect("the fetch panicked"); @@ -11869,7 +11869,7 @@ mod serve_tests { /// A renewal the subscription abandons, granted but never applied because the /// subscription ended first, does not keep the old grant alive for a joined FETCH that /// outlives it: the FETCH still ends when the old grant lapses. - #[moq_clock::test] + #[kio::test] async fn an_abandoned_renewal_leaves_an_answered_joining_fetch_the_old_expiry() { let join = answered_join().await; let rt = join.h.publisher.runtime.clone(); @@ -11878,7 +11878,7 @@ mod serve_tests { let _renewed = join.renewal.accept(grant_all_expiring(&rt, None)); drop(join.serving); - let res = moq_clock::timeout(Duration::from_secs(61), join.fetch) + let res = kio::clock::timeout(Duration::from_secs(61), join.fetch) .await .expect("the fetch outlived its token") .expect("the fetch panicked"); @@ -11900,7 +11900,7 @@ mod serve_tests { /// A token subscription's grant ending ends it at every await, setup and teardown /// included, not only while it serves: what it holds upstream is released first, and the /// peer is then told as far as it got, refused before SUBSCRIBE_OK and done after it. - #[moq_clock::test] + #[kio::test] async fn a_revoked_token_ends_a_subscription_wherever_it_waits() { for version in ALL_VERSIONS { for parked in [Parked::Resolving, Parked::Acking, Parked::Ending] { @@ -12021,7 +12021,7 @@ mod serve_tests { *writable = true; drop(writable); } - let _ = moq_clock::timeout(std::time::Duration::from_secs(1), subscription.as_mut()) + let _ = kio::clock::timeout(std::time::Duration::from_secs(1), subscription.as_mut()) .await .unwrap_or_else(|_| panic!("{version} {parked:?}: outlived its grant")); @@ -12058,7 +12058,7 @@ mod serve_tests { /// A subscriber withdrawing a SUBSCRIBE while its setup waits on a producer that never /// answers ends it at once: its demand and its slot are given back, and nothing answers it. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_withdrawn_during_setup_releases_its_demand() { for version in ALL_VERSIONS { for setup in [Setup::Resolving, Setup::Subscribing, Setup::Live] { @@ -12068,7 +12068,7 @@ mod serve_tests { } /// Broadcast resolution cannot hold a withdrawn FETCH or TRACK_STATUS alive. - #[moq_clock::test] + #[kio::test] async fn requests_withdrawn_while_resolving_release_their_demand() { for version in ALL_VERSIONS { for kind in [request::Kind::Fetch, request::Kind::TrackStatus] { @@ -12207,7 +12207,7 @@ mod serve_tests { assert_eq!(demanded(), !matches!(setup, Setup::Resolving), "{version} {setup:?}"); withdraw(&request, version); - let res = moq_clock::timeout(std::time::Duration::from_secs(1), serving) + let res = kio::clock::timeout(std::time::Duration::from_secs(1), serving) .await .unwrap_or_else(|_| panic!("{version} {setup:?}: outlived its withdrawal")); assert!(res.is_ok(), "{version} {setup:?}: {res:?}"); @@ -12223,7 +12223,7 @@ mod serve_tests { /// A resume subscribes again as a new SUBSCRIBE does, so a subscriber withdrawing the /// request while the resume waits on an idle copy's live edge ends it at once too. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_withdrawn_while_resuming_releases_its_demand() { for version in ALL_VERSIONS { let mut h = serve(version); @@ -12252,7 +12252,7 @@ mod serve_tests { } withdraw(&request, version); - moq_clock::timeout(std::time::Duration::from_secs(1), serve) + kio::clock::timeout(std::time::Duration::from_secs(1), serve) .await .unwrap_or_else(|_| panic!("{version}: outlived its withdrawal")) .unwrap(); @@ -12263,7 +12263,7 @@ mod serve_tests { /// A datagram group is never fetchable: a FETCH for one is refused like a group that /// does not exist, newest or not, and opens no fetch stream for its payload. - #[moq_clock::test] + #[kio::test] async fn a_standalone_fetch_of_a_datagram_group_is_refused() { for version in FETCH_DRAFTS { for newest in [true, false] { @@ -12290,7 +12290,7 @@ mod serve_tests { } /// A joining FETCH reaching back before the subscription's group is refused. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_spanning_several_groups_is_refused() { for version in JOINING_DRAFTS { let mut h = serve(version); @@ -12354,7 +12354,7 @@ mod serve_tests { } /// An absolute joining FETCH starting past the subscription's group names an empty range. - #[moq_clock::test] + #[kio::test] async fn an_absolute_joining_fetch_past_the_subscription_is_refused() { let version = Version::Draft18; let mut h = serve(version); @@ -12400,7 +12400,7 @@ mod serve_tests { } /// A fill against an empty track has an empty range: no fetch stream is owed. - #[moq_clock::test] + #[kio::test] async fn an_empty_track_opens_no_fill_stream() { let mut h = serve(Version::Draft22); @@ -12448,7 +12448,7 @@ mod serve_tests { /// SUBSCRIBE_OK announces the publisher's default order, newest first, whatever the /// subscription asked for. - #[moq_clock::test] + #[kio::test] async fn subscribe_ok_announces_the_default_order() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for requested in [GroupOrder::Ascending, GroupOrder::Descending, GroupOrder::Any] { @@ -12473,7 +12473,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn largest_object_is_the_live_edge_before_draft22() { for version in [Version::Draft18] { assert_eq!( @@ -12484,7 +12484,7 @@ mod serve_tests { } } - #[moq_clock::test] + #[kio::test] async fn largest_object_is_the_live_edge_on_draft22() { assert_eq!( subscribe_ok_largest(Version::Draft22).await, @@ -12496,7 +12496,7 @@ mod serve_tests { /// The filter's object bounds trim what `run_group` writes: the skipped head is not /// sent, the first written object's delta is its absolute id, and a capped tail stops /// early. Extensions are off so the wire is just deltas, sizes, and payloads. - #[moq_clock::test] + #[kio::test] async fn run_group_honors_the_slice() { fn header() -> ietf::GroupHeader { ietf::GroupHeader { @@ -12567,7 +12567,7 @@ mod serve_tests { /// A stream cut short by the range's end Location does not claim END_OF_GROUP, since /// the group goes on past it. A range ending on a whole group still does. A cap at or past /// the group's real end clears the bit too, since the header is written before we know. - #[moq_clock::test] + #[kio::test] async fn capped_group_does_not_claim_its_end() { async fn serve(object: Option) -> ietf::GroupHeader { let log = crate::lite::test_transport::Log::default(); @@ -12762,7 +12762,7 @@ mod serve_tests { /// subscription alive past the old grant's expiry: the reader re-verifies the token off /// the subscribe stream and re-arms the deadline. Proven against the deadline the /// original grant would otherwise have lapsed at. - #[moq_clock::test] + #[kio::test] async fn a_request_update_renews_a_token_subscription_past_the_old_expiry() { const VERSION: Version = Version::Draft18; @@ -12824,7 +12824,7 @@ mod serve_tests { // Past the original 60s expiry: the renewal re-armed the deadline, so the // subscription lives on. - moq_clock::sim::advance(Duration::from_secs(120)).await; + kio::clock::sim::advance(Duration::from_secs(120)).await; for _ in 0..50 { let _ = futures::poll!(acceptor.as_mut()); assert!( @@ -12837,7 +12837,7 @@ mod serve_tests { /// A pause is answered before a renewal riding it could be verified, so an update carrying /// both fails instead of acknowledging a token nobody checked. - #[moq_clock::test] + #[kio::test] async fn a_pause_carrying_a_token_fails_the_update() { for version in [Version::Draft18] { let (auth, mut requests, _cred) = auth_covering_other(); @@ -12928,7 +12928,7 @@ mod serve_tests { /// verified and answered, not collapsed. The loop keeps per-update state while a verify is /// pending (draft-18 section 10.9.1 answers each update); the single slot it replaced /// dropped the middle renewal (0x42) entirely, so its token was never verified. - #[moq_clock::test] + #[kio::test] async fn two_renewals_buffered_behind_a_pending_verdict_each_get_a_verdict() { const VERSION: Version = Version::Draft18; @@ -12999,7 +12999,7 @@ mod serve_tests { /// Draft-22 advertises MAX_REQUEST_UPDATES, so a peer that leaves more outstanding than that /// broke the negotiated limit: draft-22 section 9.1.7 closes the session with /// TOO_MANY_REQUEST_UPDATES. - #[moq_clock::test] + #[kio::test] async fn renewals_past_the_advertised_limit_close_the_session() { const VERSION: Version = Version::Draft22; @@ -13055,7 +13055,7 @@ mod serve_tests { /// Exactly MAX_REQUEST_UPDATES outstanding (the one being verified plus the queue) is within /// the advertised limit, so a draft-22 peer holding that many is not faulted: the request /// keeps running and the session stays up. - #[moq_clock::test] + #[kio::test] async fn renewals_at_the_advertised_limit_keep_the_request() { const VERSION: Version = Version::Draft18; @@ -13104,7 +13104,7 @@ mod serve_tests { /// Drafts below 19 carry no MAX_REQUEST_UPDATES option, so a peer there agreed to no ceiling: /// the same flood that closes a draft-22 session must neither end the request nor close the /// session on draft-18, because a conforming peer must not be stranded for a limit it never saw. - #[moq_clock::test] + #[kio::test] async fn older_drafts_do_not_strand_a_renewal_flood() { const VERSION: Version = Version::Draft18; @@ -13148,7 +13148,7 @@ mod serve_tests { /// answer restores one MAX_REQUEST_UPDATES credit. A peer that only sends token-less priority /// updates must keep its credit so it can still renew, so each gets a REQUEST_OK and the /// session stays up well past the advertised limit. - #[moq_clock::test] + #[kio::test] async fn token_less_updates_are_each_acknowledged() { const VERSION: Version = Version::Draft18; @@ -13225,7 +13225,7 @@ mod serve_tests { /// renewal, never before it: an answer names no Request ID, so its order is /// all that ties it to its update. The renewal is refused, so its REQUEST_ERROR is the first /// answer either way, and the token-less update behind it is never answered ahead of it. - #[moq_clock::test] + #[kio::test] async fn an_update_behind_a_pending_renewal_is_answered_in_order() { for version in [Version::Draft18] { let (auth, mut requests, _cred) = auth_covering_other(); @@ -13290,7 +13290,7 @@ mod serve_tests { /// On drafts without the option the guard is a memory backstop, not a protocol limit: a flood /// past it ends the one request through PUBLISH_DONE, never the session. - #[moq_clock::test] + #[kio::test] async fn an_older_draft_flood_past_the_guard_ends_the_request() { const VERSION: Version = Version::Draft18; @@ -13337,7 +13337,7 @@ mod serve_tests { /// too: with a grant that never expires and an acceptor sitting on the renewal, the stream /// closing drops the subscription's demand at once. The request keeps its stream, and so its /// credit, until the acceptor lets go of the renewal. - #[moq_clock::test] + #[kio::test] async fn a_closed_subscription_ends_while_a_renewal_is_pending() { const VERSION: Version = Version::Draft18; @@ -13425,7 +13425,7 @@ mod serve_tests { /// A REQUEST_UPDATE the acceptor refuses ends only that subscription, at once, through the /// PUBLISH_DONE UPDATE_FAILED path (draft-18 section 10.9.1). The old /// grant does not keep it alive to its 60s expiry, and the session stays up. - #[moq_clock::test] + #[kio::test] async fn a_refused_request_update_ends_the_subscription() { const VERSION: Version = Version::Draft18; @@ -13500,7 +13500,7 @@ mod serve_tests { /// A slow acceptor answering a renewal must not stall serving nor let the request outlive /// its grant: the renewal verify is raced against the old deadline, which still fires and /// sends PUBLISH_DONE. The stream keeps its credit until the acceptor lets go of the renewal. - #[moq_clock::test] + #[kio::test] async fn a_slow_renewal_does_not_stall_serving() { const VERSION: Version = Version::Draft18; let (auth, mut requests, _cred) = auth_covering_other(); @@ -13550,7 +13550,7 @@ mod serve_tests { // The acceptor is stuck. Past the old 60s expiry the deadline must still fire and end // the request EXPIRED, rather than the pending renewal stalling serving. - moq_clock::sim::advance(Duration::from_secs(120)).await; + kio::clock::sim::advance(Duration::from_secs(120)).await; let done = { let log = Log::default(); let mut writer = crate::coding::Writer::new( @@ -13604,7 +13604,7 @@ mod serve_tests { /// Publisher / SUBSCRIBE side: on a session without the AUTH extension the union is /// `None` forever. A token-bearing SUBSCRIBE the limit does not cover is verified by the /// application, not admitted by the permissive union. - #[moq_clock::test] + #[kio::test] async fn a_request_token_on_a_no_auth_session_is_verified() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(false); @@ -13706,7 +13706,7 @@ mod serve_tests { /// A subscriber's token grant is checked on its `subscribe` patterns: a write-only grant /// does not admit a SUBSCRIBE, a read-only one does. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_token_needs_a_subscribe_grant() { let read_only = crate::auth::Grant { publish: crate::Patterns::new(), @@ -13727,7 +13727,7 @@ mod serve_tests { /// A request token stands in for the limit this side set on the peer, so a SUBSCRIBE the /// limit refuses is admitted on the token and a later narrowing leaves it standing. - #[moq_clock::test] + #[kio::test] async fn a_request_token_stands_in_for_the_local_limit() { let nothing = Some(crate::auth::Grant::default()); let (auth, _h, mut serving) = serve_token_subscribe(crate::auth::Grant::all(), nothing).await; @@ -13749,7 +13749,7 @@ mod serve_tests { /// What the peer's AUTH_OK grants us never authorizes what the peer asks of us: with a /// covering peer grant and no limit, the application still verifies the SUBSCRIBE's token, /// and its refusal refuses the subscription. - #[moq_clock::test] + #[kio::test] async fn a_covering_peer_grant_never_skips_the_verifier() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(true); @@ -13789,7 +13789,7 @@ mod serve_tests { /// Every token is verified, even on a SUBSCRIBE the limit already covers: the verifier /// refusing it refuses the subscription, and one it grants stands outside the limit, so /// narrowing the limit away from it leaves the subscription its token admitted. - #[moq_clock::test] + #[kio::test] async fn a_covering_limit_still_verifies_the_token() { let limit = |subtree: &str| crate::auth::Grant { publish: crate::Patterns::new(), @@ -13813,7 +13813,7 @@ mod serve_tests { /// Where tokens decide, a token arriving on an update for a subscription admitted without /// one is refused NOT_SUPPORTED rather than taken unread, failing only that subscription. - #[moq_clock::test] + #[kio::test] async fn a_token_on_a_subscription_admitted_without_one_is_refused() { for version in [Version::Draft22] { let auth = crate::auth::Link::new(false); @@ -13868,7 +13868,7 @@ mod serve_tests { /// With no verifier, a limited session refuses a token as unsupported rather than /// unauthorized, even one its limit covers, and a session never limited ignores the token. - #[moq_clock::test] + #[kio::test] async fn a_token_without_a_verifier_is_unsupported() { const VERSION: Version = Version::Draft18; for limit in [crate::auth::Grant::default(), crate::auth::Grant::all()] { @@ -13935,7 +13935,7 @@ mod serve_tests { /// A token waiting on the application holds the subscription's slot. Withdrawn while still /// queued it gives the slot back at once; once the application took it, the slot stays /// counted until the application answers, and that late answer authorizes nothing. - #[moq_clock::test] + #[kio::test] async fn a_stalled_verification_holds_the_subscription_slot() { const VERSION: Version = Version::Draft18; @@ -14004,7 +14004,7 @@ mod serve_tests { /// A peer that cancels a SUBSCRIBE whose token the application took keeps the request's /// stream, and so its credit, until the application answers: cancelling and resubscribing /// cannot leave more verifications in flight than the peer's credit admits. - #[moq_clock::test] + #[kio::test] async fn a_cancelled_subscribe_keeps_its_stream_until_the_application_answers() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(false); @@ -14050,7 +14050,7 @@ mod serve_tests { /// What the peer granted us bounds what we send, so a request token never admits a /// SUBSCRIBE outside it, and the application is not even asked. - #[moq_clock::test] + #[kio::test] async fn a_request_token_cannot_exceed_the_peers_grant() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(true); @@ -14114,7 +14114,7 @@ mod tests { use futures::FutureExt; async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } fn occurrences(log: &crate::lite::test_transport::Log, needle: &[u8]) -> usize { @@ -14240,7 +14240,7 @@ mod tests { /// (`Client::with_peer_hop`) is never advertised to that peer; it would only /// echo the peer's own content back at it. A broadcast with an independent /// route still is. - #[moq_clock::test] + #[kio::test] async fn assigned_peer_hop_filters_echoed_announces() { let assigned = crate::Hop::new(777).unwrap(); let (publisher, consumer, _routes) = echo_harness(assigned).await; @@ -14258,7 +14258,7 @@ mod tests { /// An anonymous chain received from an identified peer keeps the 0 on the wire /// and is never advertised back to that session: split-horizon matches `via` /// as well as the chain. - #[moq_clock::test] + #[kio::test] async fn anonymous_chain_is_forwarded_with_zero_and_not_echoed() { let assigned = crate::Hop::new(777).unwrap(); let r1 = crate::Hop::new(9).unwrap(); @@ -14302,7 +14302,7 @@ mod tests { /// negotiated peer always sends its own HOP_PATH, so a route attributed to the /// assigned identity is a state this peer class cannot reach; see /// [`a_declared_zero_chain_is_not_advertised_back`] for what it gets instead. - #[moq_clock::test] + #[kio::test] async fn withheld_peer_hop_falls_back_to_assigned() { let assigned = crate::Hop::new(777).unwrap(); let declared = crate::Hop::new(9).unwrap(); @@ -14329,7 +14329,7 @@ mod tests { /// and one that declared 0 names itself 0 there. An arriving chain is not rewritten, /// so the route carries 0; the assigned identity stays on `via` and split-horizon /// matches it, so the peer is not advertised its own route back. - #[moq_clock::test] + #[kio::test] async fn a_declared_zero_chain_is_not_advertised_back() { let assigned = crate::Hop::new(777).unwrap(); let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -14367,7 +14367,7 @@ mod tests { /// MoQ Active Count: the OK counts exactly the NAMESPACE messages that follow it, /// so a route this peer is never told about is not counted either. Counting one would /// leave the peer waiting on a message that never comes. - #[moq_clock::test] + #[kio::test] async fn the_ok_counts_only_what_is_advertised() { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -14444,7 +14444,7 @@ mod tests { /// without an origin-level (un)announce, silently flipping `advertisable`. /// Namespace forwarding must follow: advertise when a clean route appears, /// withdraw when the last one detaches. - #[moq_clock::test] + #[kio::test] async fn namespace_follows_route_eligibility_changes() { let assigned = crate::Hop::new(777).unwrap(); let clean_publisher = crate::Hop::new(778).unwrap(); @@ -14547,7 +14547,7 @@ mod tests { /// A peer that refuses an advertisement with a retry interval of 0 is asking not to be /// offered it again. Coming back anyway turns a permanent refusal (unauthorized, /// uninterested) into a request every few seconds for the life of the session. - #[moq_clock::test] + #[kio::test] async fn a_refusal_that_forbids_retrying_is_not_retried() { const VERSION: Version = Version::Draft18; @@ -14599,7 +14599,7 @@ mod tests { /// withdraws the old, and only once the peer accepted it, since the two streams are /// unordered. The peer never sees the namespace absent. A peer without the extension /// cannot tell the two apart, so it still sees the old one withdrawn first. - #[moq_clock::test] + #[kio::test] async fn another_epoch_is_advertised_before_the_old_is_withdrawn() { use crate::lite::test_transport::Sent; const VERSION: Version = Version::Draft18; @@ -14702,7 +14702,7 @@ mod tests { /// A peer that declared nothing is told without being asked. Relays that never send /// SUBSCRIBE_NAMESPACE hear nothing otherwise, and every third-party one behaves /// that way: a publisher is expected to announce itself. - #[moq_clock::test] + #[kio::test] async fn a_peer_that_declared_nothing_is_told_unsolicited() { const VERSION: Version = Version::Draft18; @@ -14747,7 +14747,7 @@ mod tests { /// A PUBLISH_NAMESPACE is withdrawn by cancelling its request: reset /// plus STOP_SENDING. A FIN there is a protocol violation some peers close on. - #[moq_clock::test] + #[kio::test] async fn publish_namespace_withdraws_by_reset() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -14810,7 +14810,7 @@ mod tests { /// ACTIVE_COUNT only answers SUBSCRIBE_NAMESPACE (MoQ Active Count), so one on the OK /// to a PUBLISH_NAMESPACE is the peer breaking the extension, negotiated or not. - #[moq_clock::test] + #[kio::test] async fn a_counted_publish_namespace_ok_is_a_violation() { const VERSION: Version = Version::Draft18; @@ -14850,7 +14850,7 @@ mod tests { VERSION, ); - let res = moq_clock::timeout(Duration::from_secs(5), publisher.run_publish_namespaces()) + let res = kio::clock::timeout(Duration::from_secs(5), publisher.run_publish_namespaces()) .await .expect("the violation ends the loop"); assert!(matches!(res, Err(Error::ProtocolViolation)), "{res:?}"); @@ -14972,7 +14972,7 @@ mod tests { /// segment. The subscription also repeats every visible /// namespace the unsolicited loop already sent. A NAMESPACE is discovery, not /// a second route. - #[moq_clock::test] + #[kio::test] async fn hidden_namespaces_need_an_opt_in() { for (solicit, prefix, hidden, cam, stats) in [ (Some(false), "", false, 2, 0), @@ -14996,7 +14996,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn hidden_discovery_obeys_peer_setup_and_requested_prefix() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for declared in [false, true] { @@ -15034,7 +15034,7 @@ mod tests { /// unsolicited PUBLISH_NAMESPACE and a NAMESPACE on the SUBSCRIBE_NAMESPACE stream. /// Those are two discoveries of one namespace, not two routes. A peer that asked to /// be solicited hears it only on the stream. - #[moq_clock::test] + #[kio::test] async fn a_non_solicit_peer_hears_a_namespace_both_ways() { let (times, streams) = advertise_both_ways(Some(false)).await; assert_eq!(times, 2, "PUBLISH_NAMESPACE and NAMESPACE"); @@ -15048,7 +15048,7 @@ mod tests { /// A peer that did not send SOLICIT still gets NAMESPACE on its SUBSCRIBE_NAMESPACE /// stream: one for a match that already exists, one announced /// after, then NAMESPACE_DONE when that announcement ends. - #[moq_clock::test] + #[kio::test] async fn a_non_solicit_subscribe_namespace_carries_namespace() { for version in [Version::Draft18] { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -15137,7 +15137,7 @@ mod tests { /// Send capacity can park an admitted stream's header. That must not wedge the loop: /// withdrawals queued behind it still need to progress. A withdrawal ends its request's /// own stream, which needs no new open, so it is visible while every open is blocked. - #[moq_clock::test] + #[kio::test] async fn a_parked_open_still_lets_a_namespace_be_withdrawn() { const VERSION: Version = Version::Draft18; @@ -15218,7 +15218,7 @@ mod tests { /// A namespace nobody can advertise any more is not pending, whatever happened before. /// `deferred` outliving the want would arm the retry timer forever for a wire message /// that can never happen: not a spin, but a session that never sleeps. - #[moq_clock::test] + #[kio::test] async fn a_namespace_that_stops_being_advertisable_stops_being_deferred() { let assigned = crate::Hop::new(777).unwrap(); @@ -15260,7 +15260,7 @@ mod tests { /// A minimum wait binds every path back to the namespace, not just the retry sweep. /// A route change re-prices the advertisement; it does not excuse us from the wait the /// peer asked for. - #[moq_clock::test] + #[kio::test] async fn a_route_change_still_waits_out_a_refusal() { const VERSION: Version = Version::Draft18; @@ -15357,7 +15357,7 @@ mod tests { /// request that already carries it, sending the changed parameter only. The new cost /// is 0, which has to be explicit: REQUEST_UPDATE keeps an omitted parameter, so /// leaving it out would keep the old price. - #[moq_clock::test] + #[kio::test] async fn a_repricing_is_a_request_update() { const VERSION: Version = Version::Draft18; @@ -15435,7 +15435,7 @@ mod tests { /// ACTIVE_COUNT only answers SUBSCRIBE_NAMESPACE (MoQ Active Count), so one on the OK /// to a REQUEST_UPDATE is the peer breaking the extension too. - #[moq_clock::test] + #[kio::test] async fn a_counted_update_ok_is_a_violation() { const VERSION: Version = Version::Draft18; @@ -15497,7 +15497,7 @@ mod tests { .announce("cam", crate::origin::Route::default().with_epoch(epoch).with_cost(0)) .unwrap(); - let res = moq_clock::timeout(Duration::from_secs(5), run) + let res = kio::clock::timeout(Duration::from_secs(5), run) .await .expect("the violation ends the loop"); assert!(matches!(res, Err(Error::ProtocolViolation)), "{res:?}"); @@ -15510,7 +15510,7 @@ mod tests { /// updates the advertisement in place, like any other change within an instance: /// withdrawing it would make the namespace briefly vanish downstream just because /// its replica moved. - #[moq_clock::test] + #[kio::test] async fn a_replica_change_is_a_request_update() { const VERSION: Version = Version::Draft18; @@ -15654,7 +15654,7 @@ mod tests { /// A route's auth rides its PUBLISH_NAMESPACE as the request's token, and swapping it /// renews the request in place: REQUEST_UPDATE on the same stream, carrying only the /// new token. - #[moq_clock::test] + #[kio::test] async fn swapping_a_route_auth_is_a_request_update() { swaps_a_route_auth(Version::Draft18).await; } @@ -15722,7 +15722,7 @@ mod tests { /// An auth another handle issued is not this session's to present: the route is /// advertised under the session's scope, and the credential never reaches this peer. - #[moq_clock::test] + #[kio::test] async fn a_foreign_route_auth_is_not_carried() { const VERSION: Version = Version::Draft18; @@ -15751,7 +15751,7 @@ mod tests { /// moq-transport cannot name an auth on a request that had none, so naming one /// withdraws the request and makes it again with the token. - #[moq_clock::test] + #[kio::test] async fn naming_an_auth_restarts_an_unnamed_request() { const VERSION: Version = Version::Draft18; @@ -15777,7 +15777,7 @@ mod tests { /// Renewals wait on their answers side by side: one the peer has not answered holds up /// neither another namespace's renewal nor a new announcement. - #[moq_clock::test] + #[kio::test] async fn renewals_are_in_flight_together() { const VERSION: Version = Version::Draft18; @@ -15824,7 +15824,7 @@ mod tests { /// From draft 18 an idle advertisement keeps reading, so a peer that FINs or resets its /// answer while nothing is pending has the namespace offered again, after a wait that /// doubles each time so a peer ending every advertisement does not get a request loop. - #[moq_clock::test] + #[kio::test] async fn an_idle_advertisement_that_ends_is_offered_again() { use crate::transport::memory; const VERSION: Version = Version::Draft18; @@ -15844,10 +15844,10 @@ mod tests { declared(Some(false)), VERSION, ); - let run = moq_clock::sim::spawn(publisher.run_publish_namespaces()); + let run = kio::clock::sim::spawn(publisher.run_publish_namespaces()); let offered = async || { - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( Duration::from_secs(10), Stream::accept(&mut crate::driver::Transport::new(peer.clone()), VERSION), ) @@ -15864,12 +15864,12 @@ mod tests { stream.writer.write_all(&mut ok).await.unwrap(); // Paused time advances once every task is idle: the answer was read, and the // advertisement is parked on its idle reader. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; match fin { true => stream.writer.finish().unwrap(), false => stream.writer.abort(&Error::Cancel), } - let ended = moq_clock::Instant::now(); + let ended = kio::clock::Instant::now(); stream = offered().await; assert!( ended.elapsed() >= wait, @@ -15884,7 +15884,7 @@ mod tests { /// A peer that resets or ends one namespace's PUBLISH_NAMESPACE before answering it ends /// only that advertisement: the next namespace is still answered and withdrawn as usual, /// and the failed one is offered again after a backoff rather than in a loop. - #[moq_clock::test] + #[kio::test] async fn a_failed_advertisement_ends_only_its_namespace() { for version in [Version::Draft18] { for fin in [true, false] { @@ -15913,11 +15913,11 @@ mod tests { declared(Some(false)), version, ); - let run = moq_clock::sim::spawn(publisher.run_publish_namespaces()); + let run = kio::clock::sim::spawn(publisher.run_publish_namespaces()); // The next advertisement, with the namespace it names. let offered = async || { - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( Duration::from_secs(10), Stream::accept(&mut crate::driver::Transport::new(peer.clone()), version), ) @@ -15938,7 +15938,7 @@ mod tests { true => failed.writer.finish().unwrap(), false => failed.writer.abort(&Error::Cancel), } - let ended = moq_clock::Instant::now(); + let ended = kio::clock::Instant::now(); let (mut held, second) = offered().await; assert_ne!( @@ -15972,7 +15972,7 @@ mod tests { /// A PUBLISH_NAMESPACE whose header fails to send backs off that namespace rather than /// closing the session. - #[moq_clock::test] + #[kio::test] async fn a_failed_header_backs_off_the_namespace() { use crate::transport::memory; @@ -15999,9 +15999,9 @@ mod tests { version, ) .with_auth(auth.clone()); - let run = moq_clock::sim::spawn(publisher.run_publish_namespaces()); + let run = kio::clock::sim::spawn(publisher.run_publish_namespaces()); - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(10), Stream::accept(&mut crate::driver::Transport::new(peer.clone()), version), ) @@ -16010,7 +16010,7 @@ mod tests { .unwrap(); // Offered again after the backoff, on a session that stays open. - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(10), Stream::accept(&mut crate::driver::Transport::new(peer.clone()), version), ) @@ -16023,7 +16023,7 @@ mod tests { /// A peer that resets a request's stream while its renewal is in flight ends only that /// request: the loop keeps running and advertises the namespace afresh. - #[moq_clock::test] + #[kio::test] async fn a_reset_renewal_ends_only_its_request() { const VERSION: Version = Version::Draft18; @@ -16062,7 +16062,7 @@ mod tests { // The advertisement comes back on the retry, jittered up to RETRY_BASE, which // outlasts poll_until. - moq_clock::sleep(RETRY_BASE).await; + kio::clock::sleep(RETRY_BASE).await; poll_until(&mut run, &log, b"second", 2).await; assert_eq!( occurrences(&log, b"second"), @@ -16074,7 +16074,7 @@ mod tests { /// An update the peer never answers drops its request once the timeout passes, and /// the retry advertises the namespace afresh under the current auth. - #[moq_clock::test] + #[kio::test] async fn an_unanswered_renewal_advertises_again() { advertises_again_unanswered(Version::Draft18).await; } @@ -16102,7 +16102,7 @@ mod tests { break; } assert!(futures::poll!(run.as_mut()).is_pending()); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } assert_eq!( occurrences(&log, b"second"), @@ -16113,7 +16113,7 @@ mod tests { /// moq-transport has no restart: another source winning a namespace without an epoch /// withdraws it and advertises it afresh, so the peer resubscribes. - #[moq_clock::test] + #[kio::test] async fn a_restart_re_advertises_the_namespace() { const VERSION: Version = Version::Draft18; @@ -16171,7 +16171,7 @@ mod tests { /// advertisement. The namespace is then not held at all, so it comes back as a fresh /// PUBLISH_NAMESPACE once the refusal's wait is out, not as another update on a /// stream the peer already ended. - #[moq_clock::test] + #[kio::test] async fn a_refused_update_is_re_advertised_fresh() { const VERSION: Version = Version::Draft18; @@ -16243,7 +16243,7 @@ mod tests { } /// A peer that never answers one advertisement must not hold the next namespace back. - #[moq_clock::test] + #[kio::test] async fn a_silent_answer_still_lets_the_next_namespace_be_advertised() { const VERSION: Version = Version::Draft18; @@ -16283,7 +16283,7 @@ mod tests { /// Local withdrawal, refusal, and peer stream ends release an advertisement even when /// send credit holds back its first message or an update, including a partial message. - #[moq_clock::test] + #[kio::test] async fn stalled_advertisements_observe_local_and_peer_ends() { use crate::lite::test_transport::{Close, Log, ScriptedSession, Sent, SinkSend}; @@ -16369,7 +16369,7 @@ mod tests { ); if !matches!(stage, Stage::FirstAnswer) { // Backpressure alone is not an unanswered request, however long it lasts. - moq_clock::sim::advance(ADVERTISE_TIMEOUT * 2).await; + kio::clock::sim::advance(ADVERTISE_TIMEOUT * 2).await; assert!(futures::poll!(run.as_mut()).is_pending()); assert!(log.resets().is_empty()); } @@ -16403,7 +16403,7 @@ mod tests { /// A blocked replacement retains the previous epoch until its answer, coalesces later /// epochs, and withdraws both streams when the namespace goes away. Even an early OK /// must not let churn build more streams behind a write the peer has not taken. - #[moq_clock::test] + #[kio::test] async fn a_stalled_epoch_replacement_is_bounded_and_withdrawn() { use crate::lite::test_transport::{Log, ScriptedSession, Sent, SinkSend}; @@ -16500,7 +16500,7 @@ mod tests { /// An advertisement the peer never answers is given up at its deadline: its own stream's /// reset ends it. - #[moq_clock::test] + #[kio::test] async fn an_unanswered_advertisement_is_withdrawn() { for version in [Version::Draft18] { let origin = unheld_origin(); @@ -16523,11 +16523,11 @@ mod tests { poll_until(&mut run, &log, b"cam", 1).await; let withdrawn = || !log.resets().is_empty(); - moq_clock::sleep(ADVERTISE_TIMEOUT - Duration::from_millis(10)).await; + kio::clock::sleep(ADVERTISE_TIMEOUT - Duration::from_millis(10)).await; assert!(futures::poll!(run.as_mut()).is_pending()); assert!(!withdrawn(), "{version}: withdrawn before its deadline"); - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; assert!(futures::poll!(run.as_mut()).is_pending()); assert!( withdrawn(), @@ -16540,7 +16540,7 @@ mod tests { /// Credit returning raises no signal of its own, so only the retry timer brings back an /// advertisement refused for credit; without it the namespace stays undiscoverable for /// the life of the session. The refusal itself must not spend a request ID. - #[moq_clock::test] + #[kio::test] async fn an_advertisement_without_credit_is_retried_and_spends_no_id() { use std::sync::atomic::Ordering; for version in [Version::Draft18] { @@ -16591,7 +16591,7 @@ mod tests { /// Send capacity returning raises no signal of its own: no announce, no route change, nothing /// the loop is watching. Only a retry brings the namespace back, and without one it /// stays undiscoverable for the life of the session. - #[moq_clock::test] + #[kio::test] async fn an_advertisement_waiting_for_send_capacity_is_retried_on_its_own() { const VERSION: Version = Version::Draft18; @@ -16640,7 +16640,7 @@ mod tests { /// Advance far enough that a parked open gives up and its retry comes due, without /// making the test wait: time is paused, so this only moves the clock the loop reads. async fn tick() { - moq_clock::sim::advance(Duration::from_millis(200)).await; + kio::clock::sim::advance(Duration::from_millis(200)).await; } fn set_gate(gate: &kio::Producer, open: bool) { @@ -16756,7 +16756,7 @@ mod tests { /// has to survive the trip. `Writer` resets the stream on drop, and a reset that races the /// write discards the bytes the peer has not read yet, which leaves the subscriber waiting /// on a request we already refused. Finishing first makes the drop-time reset a no-op. - #[moq_clock::test] + #[kio::test] async fn missing_broadcast_is_refused_without_resetting_the_stream() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let (writes, resets) = subscribe_missing(version).await; @@ -16773,7 +16773,7 @@ mod tests { /// Every FETCH we refuse goes out through its own error encoder, so it needs the same /// finish: a reset there loses the rejection the same way. - #[moq_clock::test] + #[kio::test] async fn a_refused_fetch_does_not_reset_the_stream() { let refused = || { [ @@ -17173,7 +17173,7 @@ mod range_tests { /// A start past the live edge is what the subscriber asked for, so it is used as given. /// Clamping it to the live edge would serve a group outside the requested range. - #[moq_clock::test] + #[kio::test] async fn a_future_start_is_not_clamped_to_the_live_edge() { let track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), @@ -17735,7 +17735,7 @@ mod compression_tests { } /// The actual JS SETUP offer selects the plain egress of a compressed Rust track. - #[moq_clock::test] + #[kio::test] #[ignore = "requires Bun; run by just test interop"] async fn ietf_compression_fallback_interop() { use crate::coding::Decode; diff --git a/rs/moq-net/src/ietf/request_stream.rs b/rs/moq-net/src/ietf/request_stream.rs index c668fd6b4ce..89ee8c0d369 100644 --- a/rs/moq-net/src/ietf/request_stream.rs +++ b/rs/moq-net/src/ietf/request_stream.rs @@ -430,7 +430,7 @@ impl<'a> Decode<'a, Version> for NamespaceUpdate { mod tests { use super::*; - #[moq_clock::test] + #[kio::test] async fn request_messages_keep_goaway_state_across_response_phases() { use crate::lite::test_transport::ScriptedSession; for version in [Version::Draft18, Version::Draft20, Version::Draft22] { @@ -452,7 +452,7 @@ mod tests { /// A request-stream message counts as its sender counts it: the length and body, not the /// type that selects it, including a GOAWAY read ahead of the response. - #[moq_clock::test] + #[kio::test] async fn request_stream_messages_count_without_their_type() { use crate::lite::test_transport::ScriptedSession; use crate::stats::{Message, Registry, Tier}; @@ -474,7 +474,7 @@ mod tests { assert_eq!(rx(Message::Other), Some(2)); } - #[moq_clock::test] + #[kio::test] async fn a_goaway_does_not_cancel_a_pending_request() { use crate::lite::test_transport::ScriptedSession; for version in [Version::Draft18, Version::Draft20, Version::Draft22] { diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 8e02c29d258..fc5f46125dd 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -1403,7 +1403,7 @@ mod tests { assert!(decode_peer_setup(encode(Some(&[0xff])), version, true).is_err()); } - #[moq_clock::test] + #[kio::test] async fn announce_interest_without_credit_keeps_the_session_alive() { use std::sync::atomic::Ordering; for version in [Version::Draft18] { @@ -1445,7 +1445,7 @@ mod tests { 1, "{version}: interest was attempted" ); - moq_clock::sleep(std::time::Duration::from_secs(20)).await; + kio::clock::sleep(std::time::Duration::from_secs(20)).await; assert!( futures::poll!(driver.as_mut()).is_pending(), "{version}: local refusal ended the session" @@ -1460,7 +1460,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn auth_ids_need_the_peers_parity() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for client in [false, true] { @@ -1528,7 +1528,7 @@ mod tests { extensions: Default::default(), }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("invalid AUTH ID left the session open") .expect_err("invalid request ID must be fatal"); @@ -1542,7 +1542,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn malformed_auth_replies_close_the_session() { for version in [Version::Draft22] { for (id, body) in [ @@ -1585,7 +1585,7 @@ mod tests { extensions: Default::default(), }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("the session outlived a malformed AUTH reply") .expect_err("malformed AUTH is fatal"); @@ -1597,7 +1597,7 @@ mod tests { /// A granted token whose Auth request the peer resets is presented again on the same /// session, backing off while each attempt is lost before a reply: at 0s, 1s, and 3s. - #[moq_clock::test] + #[kio::test] async fn a_lost_auth_request_is_presented_again() { let version = Version::Draft18; let mut grant = Vec::new(); @@ -1639,7 +1639,7 @@ mod tests { .unwrap(); let token = handle.present(bytes::Bytes::from_static(b"token")).unwrap(); - let res = moq_clock::timeout(std::time::Duration::from_secs(5), driver).await; + let res = kio::clock::timeout(std::time::Duration::from_secs(5), driver).await; assert!(res.is_err(), "the session ended: {res:?}"); assert_eq!(occurrences(&log, b"token"), 3); assert!( @@ -1650,7 +1650,7 @@ mod tests { /// A peer that negotiated MoQ Auth but resets a token's request before any reply gave it /// nothing: the token fails as unsupported rather than being presented again. - #[moq_clock::test] + #[kio::test] async fn an_auth_request_reset_before_its_reply_is_unsupported() { let version = Version::Draft18; let mut grant = Vec::new(); @@ -1693,14 +1693,14 @@ mod tests { .unwrap(); let token = handle.present(bytes::Bytes::from_static(b"token")).unwrap(); - let res = moq_clock::timeout(std::time::Duration::from_secs(5), driver).await; + let res = kio::clock::timeout(std::time::Duration::from_secs(5), driver).await; assert!(res.is_err(), "the session ended: {res:?}"); assert_eq!(occurrences(&log, b"token"), 1, "presented again"); let err = futures::FutureExt::now_or_never(token.closed()).expect("the token is still open"); assert!(matches!(err, Error::Unsupported), "{err:?}"); } - #[moq_clock::test] + #[kio::test] async fn malformed_presenter_auth_closes_the_session() { for version in [Version::Draft22] { for body in [vec![0, 2], vec![0, 0, 0]] { @@ -1738,7 +1738,7 @@ mod tests { extensions: Default::default(), }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("malformed presenter AUTH was ignored") .expect_err("malformed AUTH is fatal"); @@ -1803,7 +1803,7 @@ mod tests { /// Driven through `start` rather than `run_subscribe_namespace` directly: the /// stream surfaces the error either way, so only this loop's handling of it decides /// between a close and a warning, and a test below the loop would pass regardless. - #[moq_clock::test] + #[kio::test] async fn a_namespace_without_a_hop_path_closes_the_session() { const VERSION: Version = Version::Draft18; @@ -1848,7 +1848,7 @@ mod tests { }) .expect("start the session"); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("the session ended rather than carrying on") .expect_err("a malformed NAMESPACE fails the session"); @@ -1866,7 +1866,7 @@ mod tests { /// Driven through `start` so the per-prefix fan-out is exercised, not just one stream /// in isolation: a loop that opened a single stream would still satisfy a test that /// called `run_subscribe_namespace` itself. - #[moq_clock::test] + #[kio::test] async fn every_permitted_prefix_gets_its_own_subscribe_namespace() { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let scope: crate::Patterns = ["cam", "mic"] @@ -1906,14 +1906,14 @@ mod tests { extensions: Default::default(), }) .expect("start the session"); - let _driver = moq_clock::sim::spawn(driver); + let _driver = kio::clock::sim::spawn(driver); // Both requests are written before either peer response, which never comes. for _ in 0..100 { if occurrences(&log, b"cam") > 0 && occurrences(&log, b"mic") > 0 { break; } - moq_clock::sleep(std::time::Duration::from_millis(5)).await; + kio::clock::sleep(std::time::Duration::from_millis(5)).await; } assert_eq!(occurrences(&log, b"cam"), 1, "one SUBSCRIBE_NAMESPACE for cam"); @@ -1955,7 +1955,7 @@ mod tests { solicit: Option, ) -> ( crate::lite::test_transport::Log, - moq_clock::sim::JoinHandle>, + kio::clock::sim::JoinHandle>, ) { let gate = kio::Producer::new(true); let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); @@ -1970,7 +1970,7 @@ mod tests { solicit: Option, ) -> ( crate::lite::test_transport::Log, - moq_clock::sim::JoinHandle>, + kio::clock::sim::JoinHandle>, ) { let log = session.log.clone(); let session = crate::driver::Transport::new(session); @@ -2001,7 +2001,7 @@ mod tests { extensions: Default::default(), }) .expect("start the session"); - (log, moq_clock::sim::spawn(driver)) + (log, kio::clock::sim::spawn(driver)) } /// Let the driver run until `needle` reaches the wire, or give up after a while. @@ -2010,13 +2010,13 @@ mod tests { if occurrences(log, needle) > 0 { return true; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } false } /// A client asks nothing until something is watched, then only about what is. - #[moq_clock::test] + #[kio::test] async fn a_client_asks_only_about_what_is_watched() { for version in [Version::Draft18] { let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -2040,7 +2040,7 @@ mod tests { /// Each request has a stream of its own, so at a foreign peer the broader one waits for /// the peer to close the narrower one's, which ends with a FIN on draft-18 and a /// reset on draft-22: a peer that never closes it never sees the two overlap. - #[moq_clock::test] + #[kio::test] async fn a_broader_watch_waits_for_the_narrower_to_leave_the_wire() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -2051,7 +2051,7 @@ mod tests { let _cam = watch(&subscribe, "cam"); for _ in 0..ANNOUNCE_TURNS { - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } assert_eq!(log.bi_opens(), opened, "{version:?} overlapped the narrower request"); let ended = log.trail().into_iter().any(|(_, sent)| match sent { @@ -2065,7 +2065,7 @@ mod tests { /// A request ended while it waits on the peer for stream credit holds nothing: the /// broader request that replaced it goes out alone once the credit arrives. - #[moq_clock::test] + #[kio::test] async fn a_request_ended_before_it_opened_does_not_block_the_broader_one() { for version in [Version::Draft22] { let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -2079,11 +2079,11 @@ mod tests { let _front = watch(&subscribe, "cam/front"); for _ in 0..ANNOUNCE_TURNS { - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } let _cam = watch(&subscribe, "cam"); for _ in 0..ANNOUNCE_TURNS { - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } *credit.write().ok().unwrap() = true; assert!(sent(&log, b"cam").await, "{version:?} never asked the broader prefix"); @@ -2095,7 +2095,7 @@ mod tests { /// A peer that declared MoQ Solicit is ours and holds overlapping requests, so a broader /// watch leaves the narrower request open, as on moq-lite: neither takes the other's /// routes over before it has synced. - #[moq_clock::test] + #[kio::test] async fn a_broader_watch_keeps_the_narrower_open_at_our_peer() { for version in [Version::Draft18] { let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -2157,14 +2157,14 @@ mod tests { extensions: Default::default(), }) .expect("start the session"); - let _driver = moq_clock::sim::spawn(driver); + let _driver = kio::clock::sim::spawn(driver); // Drive until the announce lands, rather than betting on one fixed window. for _ in 0..ANNOUNCE_TURNS { if occurrences(&log, b"solo-cam") > 0 { break; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } occurrences(&log, b"solo-cam") @@ -2172,7 +2172,7 @@ mod tests { /// The peer's SETUP decides whether an advertisement may go out unasked, so nothing /// can be sent before it arrives. - #[moq_clock::test] + #[kio::test] async fn no_announce_before_the_peer_setup() { assert_eq!( announce_occurrences(None).await, @@ -2183,7 +2183,7 @@ mod tests { /// A peer that requires solicitation hears nothing until it asks, which is the /// behavior the IETF draft describes for a relay. - #[moq_clock::test] + #[kio::test] async fn a_peer_requiring_solicitation_is_not_told_unasked() { let declared = peer::Peer { solicit: Some(true), @@ -2200,7 +2200,7 @@ mod tests { /// A peer that declared nothing is told without being asked. Every relay that never /// sends SUBSCRIBE_NAMESPACE depends on this, and the session is what wires the /// unsolicited loop up at all. - #[moq_clock::test] + #[kio::test] async fn a_peer_declaring_nothing_is_told_unasked() { assert_eq!( announce_occurrences(Some(peer::Peer::default())).await, @@ -2227,7 +2227,7 @@ mod tests { _cam: crate::AnnounceProducer, _gate: kio::Producer, _goaway: crate::goaway::Handle, - _driver: moq_clock::sim::JoinHandle>, + _driver: kio::clock::sim::JoinHandle>, } fn auth_session(auth: bool) -> AuthSession { @@ -2272,19 +2272,19 @@ mod tests { _cam: cam, _gate: gate, _goaway: goaway, - _driver: moq_clock::sim::spawn(driver), + _driver: kio::clock::sim::spawn(driver), } } /// A peer that never offered MoQ Auth sees no Auth request and the session keeps /// working. A token resolves promptly rather than hanging, kept with an unknown grant /// for the requests that name it. - #[moq_clock::test] + #[kio::test] async fn a_peer_without_auth_sees_no_auth_request() { let session = auth_session(false); let (handle, log) = (&session.handle, &session.log); - let (auth, answer) = moq_clock::timeout(std::time::Duration::from_secs(1), handle.handle().add("token")) + let (auth, answer) = kio::clock::timeout(std::time::Duration::from_secs(1), handle.handle().add("token")) .await .expect("resolved promptly") .expect("kept for requests"); @@ -2296,7 +2296,7 @@ mod tests { if occurrences(log, b"solo-cam") > 0 { break; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } assert_eq!(occurrences(log, b"solo-cam"), 1, "the session stopped advertising"); assert_eq!( @@ -2307,7 +2307,7 @@ mod tests { } /// A peer that offered it gets the connection's own credential right away. - #[moq_clock::test] + #[kio::test] async fn a_negotiating_peer_gets_the_setup_token() { let session = auth_session(true); let log = &session.log; @@ -2315,7 +2315,7 @@ mod tests { if occurrences(log, &auth_type()) > 0 { break; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } assert_eq!(occurrences(log, &auth_type()), 1, "one AUTH for the setup token"); } @@ -2351,7 +2351,7 @@ mod tests { .expect("start the session"); // The driver parks once SETUP is out. - moq_clock::timeout(std::time::Duration::from_secs(10), driver) + kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect_err("the session ended instead of parking after SETUP"); @@ -2365,7 +2365,7 @@ mod tests { } /// Each extension reaches our SETUP only while this side offers it. - #[moq_clock::test] + #[kio::test] async fn a_declined_extension_stays_out_of_setup() { let all = crate::setup::Extensions::default(); let mut no_auth = all; @@ -2387,7 +2387,7 @@ mod tests { /// A server's handle supports AUTH only when the client offered it too, so a server /// answering a client that did not offer it leaves the option out, whatever it offers. - #[moq_clock::test] + #[kio::test] async fn a_server_offers_auth_only_to_a_client_that_did() { let all = crate::setup::Extensions::default(); assert_eq!(our_setup(false, crate::auth::Link::new(true), all).await, (true, true)); @@ -2452,7 +2452,7 @@ mod tests { }) .expect("start the session"); - let res = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let res = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .ok(); (res, log.closes()) @@ -2460,7 +2460,7 @@ mod tests { /// The Auth draft negotiates the extension only when both sides offer it, so an Auth /// request reaching a side that declined it is a protocol violation, not a token to grant. - #[moq_clock::test] + #[kio::test] async fn an_auth_request_to_a_side_that_declined_it_is_refused() { let (res, closes) = serve_auth_request(true).await; assert!(res.is_none(), "both offered: the request is served, {res:?}"); @@ -2541,7 +2541,7 @@ mod tests { }) .expect("start the session"); - moq_clock::timeout(std::time::Duration::from_secs(10), driver) + kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect_err("the session ended over one dead stream"); @@ -2550,7 +2550,7 @@ mod tests { /// A client advertises its AUTHORITY and connection credential in the SETUP it writes on /// its uni stream. - #[moq_clock::test] + #[kio::test] async fn setup_carries_the_authority_and_token() { const AUTHORITY: &[u8] = b"relay.example.com:4443"; const TOKEN: &[u8] = b"connection-credential"; @@ -2589,7 +2589,7 @@ mod tests { }) .expect("start the session"); - moq_clock::timeout(std::time::Duration::from_secs(10), driver) + kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect_err("the session ended instead of parking after SETUP"); @@ -2605,12 +2605,12 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn a_uni_stream_dead_before_its_type_does_not_end_the_session() { a_dead_incoming_stream_is_not_fatal(crate::lite::test_transport::DeadStreamSession::unis(1)).await; } - #[moq_clock::test] + #[kio::test] async fn a_bidi_stream_dead_before_its_header_does_not_end_the_session() { a_dead_incoming_stream_is_not_fatal(crate::lite::test_transport::DeadStreamSession::bis(1)).await; } @@ -2618,12 +2618,12 @@ mod tests { /// moxygen resets a subgroup stream it opened but never wrote with its own CANCELLED /// (0x1). Over raw QUIC our transport reads that code through the WebTransport space /// and cannot map it, which used to end the session. - #[moq_clock::test] + #[kio::test] async fn a_uni_stream_reset_with_an_unmapped_code_does_not_end_the_session() { a_dead_incoming_stream_is_not_fatal(crate::lite::test_transport::DeadStreamSession::unis(1).unmapped()).await; } - #[moq_clock::test] + #[kio::test] async fn a_bidi_stream_reset_with_an_unmapped_code_does_not_end_the_session() { a_dead_incoming_stream_is_not_fatal(crate::lite::test_transport::DeadStreamSession::bis(1).unmapped()).await; } @@ -2725,14 +2725,14 @@ mod tests { if !log.stops().is_empty() { break; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } (log, None) } /// A late group must reach the dispatch loop and stop with CANCELLED. - #[moq_clock::test] + #[kio::test] async fn a_group_for_a_retired_alias_is_stopped_with_cancelled() { let (log, result) = dispatch_uni(Version::Draft18, subgroup_header(Version::Draft18, 7, 0).await, Some(7)).await; @@ -2752,7 +2752,7 @@ mod tests { /// accepted can be one whose bytes the peer has not sent yet, held back by connection /// flow control that the later streams' unread data is using up. Waiting on its type /// before reading them deadlocks the connection. - #[moq_clock::test] + #[kio::test] async fn a_silent_stream_does_not_hold_up_the_next() { let header = subgroup_header(Version::Draft18, 7, 0).await; let session = @@ -2768,7 +2768,7 @@ mod tests { } /// A stalled bidi header must not block a SUBSCRIBE on the next stream. - #[moq_clock::test] + #[kio::test] async fn a_silent_bidi_does_not_hold_up_the_next() { const VERSION: Version = Version::Draft18; let mut subscribe = Vec::new(); @@ -2803,7 +2803,7 @@ mod tests { .with_incoming_bidis(vec![stalled, subscribe.clone()]); let driver = bidi_driver(session, Some(origin.consume())); let subscribed = Box::pin(async { while track.subscription_changed().await.unwrap().is_none() {} }); - let result = moq_clock::timeout( + let result = kio::clock::timeout( std::time::Duration::from_secs(10), futures::future::select(driver, subscribed), ) @@ -2817,7 +2817,7 @@ mod tests { } /// Child tasks must report malformed and unknown requests to the session driver. - #[moq_clock::test] + #[kio::test] async fn invalid_bidi_requests_still_end_the_session() { for id in [ietf::Subscribe::ID, 0x3f] { let mut header = Vec::new(); @@ -2826,7 +2826,7 @@ mod tests { encoder.slice(&[0, 0]); // Complete, empty body: malformed for SUBSCRIBE. let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![header]); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), bidi_driver(session, None)) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), bidi_driver(session, None)) .await .expect("invalid request did not end the session") .expect_err("invalid request was accepted"); @@ -2867,7 +2867,7 @@ mod tests { } /// A non-zero subgroup is refused on its own stream, never by closing the session. - #[moq_clock::test] + #[kio::test] async fn a_non_zero_subgroup_is_stopped_without_closing_the_session() { let (log, result) = dispatch_uni(Version::Draft18, subgroup_header(Version::Draft18, 7, 1).await, None).await; @@ -2886,7 +2886,7 @@ mod tests { } /// Padding is read and dropped: no STOP_SENDING, and the session stays up. - #[moq_clock::test] + #[kio::test] async fn a_padding_stream_is_discarded() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let (log, result) = dispatch_uni(version, uni_stream(version, PADDING), None).await; @@ -2904,7 +2904,7 @@ mod tests { /// A server waiting on the client's SETUP holds the padding and group streams that beat /// it, then classifies them once the session starts. The drafts say to buffer early /// data; rejecting it reached the wire as INTERNAL_ERROR. - #[moq_clock::test] + #[kio::test] async fn uni_streams_before_setup_are_held_until_it_lands() { const VERSION: Version = Version::Draft18; @@ -2939,7 +2939,7 @@ mod tests { /// An unknown or invalid stream type MUST close the session, so it stops nothing on its own: /// the session close takes the stream with it. - #[moq_clock::test] + #[kio::test] async fn an_unknown_uni_type_closes_the_session() { for (version, kind) in [ (Version::Draft18, 0), @@ -2957,7 +2957,7 @@ mod tests { } /// The bidi dispatcher closes the session for an unknown full-width message type. - #[moq_clock::test] + #[kio::test] async fn an_unknown_bidi_type_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for kind in [0u64, 1 << 53] { @@ -2992,7 +2992,7 @@ mod tests { }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("unknown bidi type must end the session") .expect_err("unknown bidi type must fail the session"); @@ -3009,7 +3009,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn an_invalid_group_order_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (value, nested) in [ @@ -3061,7 +3061,7 @@ mod tests { limits: Default::default(), }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .expect("invalid GROUP_ORDER must close the session") .expect_err("invalid GROUP_ORDER must fail"); @@ -3096,7 +3096,7 @@ mod tests { /// A request's AUTHORIZATION TOKEN decodes by the SETUP option's rules, so one this /// endpoint cannot use closes the session with the draft's code. - #[moq_clock::test] + #[kio::test] async fn a_request_token_that_cannot_be_used_closes_the_session() { for version in [Version::Draft22] { for (token, expected, why) in [ @@ -3148,7 +3148,7 @@ mod tests { }) .unwrap(); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), driver) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), driver) .await .unwrap_or_else(|_| panic!("{version:?} {why}: the session stayed up")) .expect_err("the token must fail the session"); @@ -3212,7 +3212,7 @@ mod tests { } /// What a server may not send in its SETUP closes the session with the draft's code. - #[moq_clock::test] + #[kio::test] async fn a_server_setup_with_path_or_authority_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (param, expected) in [ @@ -3230,7 +3230,7 @@ mod tests { /// The server's AUTHORIZATION TOKEN is decoded even though a client has no use for it: a /// malformed one closes the session, and a registration overflowing our cache of 0 is /// read as the value it carries (draft-22 section 9.1.4). - #[moq_clock::test] + #[kio::test] async fn a_server_setup_token_decodes_by_the_setup_rules() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (token, expected) in [ @@ -3249,7 +3249,7 @@ mod tests { /// The SETUP stream carries one GOAWAY and nothing else: anything more, or a GOAWAY that /// is malformed, closes the session as a PROTOCOL_VIOLATION. One GOAWAY leaves it up. - #[moq_clock::test] + #[kio::test] async fn the_setup_stream_carries_at_most_one_goaway() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let request_id = (version == Version::Draft18).then_some(0); @@ -3295,7 +3295,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn a_control_stream_fin_or_reset_is_a_protocol_violation() { use crate::lite::test_transport::{Close, DeadStreamSession, ScriptedSession}; for version in [Version::Draft18, Version::Draft20, Version::Draft22] { @@ -3328,7 +3328,7 @@ mod tests { /// A second GOAWAY arriving with the first closes the session before the first surfaces, /// so an application leaving over it cannot close first, without our code. - #[moq_clock::test] + #[kio::test] async fn a_goaway_with_more_behind_it_never_surfaces() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let request_id = (version == Version::Draft18).then_some(0); @@ -3358,7 +3358,7 @@ mod tests { /// A fatal error closes the session before its streams drop. A reset of our SETUP stream /// reaching a strict peer first has it close over that, and it never sees our code. - #[moq_clock::test] + #[kio::test] async fn the_session_closes_before_its_streams_reset() { const VERSION: Version = Version::Draft22; let mut params = ietf::Parameters::default(); @@ -3389,7 +3389,7 @@ mod tests { extensions: Default::default(), }) .unwrap(); - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), driver).await; + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), driver).await; let closes = log.closes(); assert_eq!(closes.len(), 1, "{closes:?}"); @@ -3408,7 +3408,7 @@ mod tests { /// A draft-18 GOAWAY names one of the receiver's own Request IDs, so one with the sender's /// parity closes the session with INVALID_REQUEST_ID rather than redirecting it, and one /// without a Request ID closes it as a PROTOCOL_VIOLATION. - #[moq_clock::test] + #[kio::test] async fn a_draft18_goaway_request_id_has_the_receivers_parity() { const VERSION: Version = Version::Draft18; // The loop runs as a client, whose Request IDs are even. @@ -3428,7 +3428,7 @@ mod tests { /// Draft-18 GOAWAY names the first peer ID past every one used, preserving the peer's /// parity, and still admits one a reordered stream skipped below it. - #[moq_clock::test] + #[kio::test] async fn our_draft18_goaway_names_the_admitted_request_cutoff() { const VERSION: Version = Version::Draft18; for client in [false, true] { @@ -3496,7 +3496,7 @@ mod tests { extensions: Default::default(), }) .unwrap(); - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), driver).await; + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), driver).await; let closes = log.closes(); // A request stream closes at the source and its task may close again; the transport // keeps the first, so only a disagreeing code would reach the peer. @@ -3510,7 +3510,7 @@ mod tests { /// A request past our GOAWAY cutoff is refused in the answer its kind reads: an AUTH /// with AUTH_ERROR carrying GOING_AWAY, since its presenter takes anything else as a /// violation, and the rest with REQUEST_ERROR. - #[moq_clock::test] + #[kio::test] async fn a_request_past_our_goaway_is_refused_in_its_own_answer() { const VERSION: Version = Version::Draft18; let reason = b"going away"; @@ -3535,7 +3535,7 @@ mod tests { /// A malformed request closes the session with the draft's code: a Request ID of the /// wrong parity, a namespace or name outside its bounds, or a body that does not fill /// its length. - #[moq_clock::test] + #[kio::test] async fn a_malformed_request_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let subscribe = |body: &[u8]| frame(version, ietf::Subscribe::ID, body); @@ -3606,7 +3606,7 @@ mod tests { /// A request stream may carry one GOAWAY, migrating that request alone: it leaves the /// session up, even on two streams at once. A second on one stream, or an unknown /// message, closes the session as a PROTOCOL_VIOLATION. - #[moq_clock::test] + #[kio::test] async fn a_request_stream_carries_at_most_one_goaway() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let one = goaway(version, None); @@ -3635,7 +3635,7 @@ mod tests { /// Only a server may name a new session in a request stream GOAWAY: a client that does /// closes the session as a PROTOCOL_VIOLATION. - #[moq_clock::test] + #[kio::test] async fn a_request_stream_goaway_redirects_only_from_a_server() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let mut body = Vec::new(); diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 7d9584285d8..8d9f6557334 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -6252,7 +6252,7 @@ mod tests { (live, consumer) } - #[moq_clock::test] + #[kio::test] async fn internal_alias_resolution_ends_with_its_session() { let aliases = TrackAliases::default(); let consumer = aliases.consume(); @@ -6305,14 +6305,14 @@ mod tests { responses } - #[moq_clock::test] + #[kio::test] async fn bare_fin_requires_publish_done() { for clean in [false, true] { check_publish_fin(fin_responses(clean), clean).await; } } - #[moq_clock::test] + #[kio::test] #[ignore = "requires Bun; run by just test bare-fin in interop CI"] async fn bare_fin_interop() { for clean in [false, true] { @@ -6321,7 +6321,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn track_alias_waits_for_control_message() { let runtime = crate::time::sim(); let aliases = TrackAliases::default(); @@ -6337,7 +6337,7 @@ mod tests { /// SUBSCRIBE_OK has not accepted the track, so the map holds no producer. /// Abort still has to reject the parked origin request with the session error. - #[moq_clock::test] + #[kio::test] async fn session_death_rejects_a_subscribe_still_setting_up() { let broadcast = crate::broadcast::Info::new().produce(); let mut dynamic = broadcast.requests(); @@ -6373,7 +6373,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn unknown_track_alias_times_out() { let aliases = TrackAliases::default(); assert!(matches!( @@ -6383,7 +6383,7 @@ mod tests { } async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } fn occurrences(log: &crate::lite::test_transport::Log, needle: &[u8]) -> usize { @@ -6427,7 +6427,7 @@ mod tests { /// A side that declined MoQ Solicit invited unsolicited advertisements, so one is /// expected even from a peer that implements the extension. - #[moq_clock::test] + #[kio::test] async fn an_announce_to_a_side_that_declined_solicit_is_fine() { for solicit in [Some(true), Some(false), None] { assert!( @@ -6443,7 +6443,7 @@ mod tests { /// /// Writing the option is the proof of support, whichever value it carries: an explicit /// 0 says "no requirement of my own" and still says "I read yours". - #[moq_clock::test] + #[kio::test] async fn an_announce_from_a_peer_that_implements_solicit_is_fatal() { assert!( unsolicited_is_a_violation(Some(true), Version::Draft18), @@ -6458,7 +6458,7 @@ mod tests { /// A peer that declared nothing has never heard of the extension, so it cannot have /// honored ours. Announcing at us is what it is supposed to do, and #2730 is what /// happens when nobody does. - #[moq_clock::test] + #[kio::test] async fn an_announce_from_a_peer_that_declared_nothing_is_fine() { assert!(!unsolicited_is_a_violation(None, Version::Draft18)); } @@ -6466,7 +6466,7 @@ mod tests { /// A rooted subscriber asks the peer for its permitted SCOPE. The root names where /// replies mount on our side, which is meaningless to a peer outside our namespace, /// so sending it asks for a prefix that matches nothing there. - #[moq_clock::test] + #[kio::test] async fn a_rooted_subscriber_asks_for_its_scope_not_its_root() { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let scope = crate::Patterns::from(crate::Pattern::subtree("cam").unwrap()); @@ -6518,7 +6518,7 @@ mod tests { /// A SUBSCRIBE_NAMESPACE the peer's send window holds back part-way still ends as soon as /// `live` closes, resetting the stream: a FIN would hand the peer a truncated request, /// and there is no answer to wait for. - #[moq_clock::test] + #[kio::test] async fn a_namespace_request_stalled_on_credit_ends_when_cancelled() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_send_window(1); @@ -6604,7 +6604,7 @@ mod tests { /// Driven through the real response stream rather than by recomputing the join /// here: a test that did its own `prefix.join(suffix)` would still pass if the /// NAMESPACE arm went back to joining the root. - #[moq_clock::test] + #[kio::test] async fn a_rooted_subscriber_mounts_a_reply_under_its_root_once() { const VERSION: Version = Version::Draft18; @@ -6667,7 +6667,7 @@ mod tests { /// A NAMESPACE that loops back through us detaches its route, but the advertisement /// stays live on the wire until its NAMESPACE_DONE: a repeat that restores a clean path /// while gaining or losing an epoch is still the violation it would be without the loop. - #[moq_clock::test] + #[kio::test] async fn a_reflected_namespace_keeps_its_epoch_live() { const VERSION: Version = Version::Draft18; let us = crate::Hop::new(5).unwrap(); @@ -6762,7 +6762,7 @@ mod tests { /// A namespace the peer holds on a SUBSCRIBE_NAMESPACE stream takes an announce slot /// whatever we make of it, so reflected ones the origin never sees still exhaust the /// session's budget, and a NAMESPACE_DONE gives the slot back. - #[moq_clock::test] + #[kio::test] async fn a_reflected_namespace_holds_an_announce_slot() { const VERSION: Version = Version::Draft18; let us = crate::Hop::new(5).unwrap(); @@ -6854,7 +6854,7 @@ mod tests { /// MoQ Active Count is negotiated, so a REQUEST_OK that breaks the negotiation /// either way is the peer's fault: a count we cannot rely on, or one missing where we /// would otherwise wait on it forever. - #[moq_clock::test] + #[kio::test] async fn a_count_the_negotiation_did_not_promise_is_a_violation() { const VERSION: Version = Version::Draft18; @@ -6985,7 +6985,7 @@ mod tests { } /// With MoQ Active Count, the origin syncs once the counted NAMESPACEs are in. - #[moq_clock::test] + #[kio::test] async fn counted_namespaces_catch_up() { const VERSION: Version = Version::Draft18; for (entries, synced) in [(&["a"][..], false), (&["a", "b"][..], true)] { @@ -7015,7 +7015,7 @@ mod tests { } /// Without MoQ Active Count, REQUEST_OK is the best boundary there is. - #[moq_clock::test] + #[kio::test] async fn an_uncounted_answer_catches_up_on_the_ok() { const VERSION: Version = Version::Draft18; let session = crate::lite::test_transport::ScriptedSession::new(counted_response(VERSION, None, &[]).await); @@ -7036,7 +7036,7 @@ mod tests { } /// A counted set cut short, by a NAMESPACE_DONE or the stream ending, is the peer's fault. - #[moq_clock::test] + #[kio::test] async fn a_counted_set_cut_short_is_a_violation() { const VERSION: Version = Version::Draft18; for (entries, fin) in [(&["a", "-a"][..], false), (&["a"][..], true)] { @@ -7069,7 +7069,7 @@ mod tests { /// A cancelled subscription leaves its alias behind, so the groups the publisher is /// still sending are discarded at once instead of stalling out the timeout and being /// reported as unknown. - #[moq_clock::test] + #[kio::test] async fn retired_alias_drops_late_groups_immediately() { let aliases = TrackAliases::default(); insert_track_alias(&aliases, 7, RequestId(11)).unwrap(); @@ -7093,7 +7093,7 @@ mod tests { /// Covers the error this path produces and the code it maps to, not the dispatch loop /// that sends it. `session::a_group_for_a_retired_alias_is_stopped_with_cancelled` /// drives that loop over a real receive stream. - #[moq_clock::test] + #[kio::test] async fn a_retired_alias_maps_to_the_cancelled_code() { let aliases = TrackAliases::default(); insert_track_alias(&aliases, 7, RequestId(11)).unwrap(); @@ -7187,7 +7187,7 @@ mod tests { /// same alias. Our filters are all LargestObject, so we cannot re-apply them to tell the /// groups apart, but that is one subscription's problem. Killing the session over a /// legal choice would take every other broadcast down with it. - #[moq_clock::test] + #[kio::test] async fn a_shared_alias_for_one_track_costs_only_that_subscription() { let subscriber = subscriber_with_tracks(&[(RequestId(11), "cam", "video"), (RequestId(13), "cam", "video")]); @@ -7201,7 +7201,7 @@ mod tests { /// Relays keep datagram Object IDs, while plain readers see only normal object 0. /// An unbound alias is dropped, and a malformed datagram is the peer's violation. - #[moq_clock::test] + #[kio::test] async fn an_object_datagram_is_a_datagram_group() { use crate::coding::Encode as _; use futures::FutureExt as _; @@ -7274,7 +7274,7 @@ mod tests { /// A datagram that lands before SUBSCRIBE_OK binds its alias is dropped, not held for the /// subscription to replay once it is bound. The reader was already subscribed, so only the /// missing alias can have dropped it. - #[moq_clock::test] + #[kio::test] async fn a_datagram_before_its_alias_is_dropped() { use crate::coding::Encode as _; use futures::FutureExt as _; @@ -7320,7 +7320,7 @@ mod tests { } /// One alias naming two different tracks is the collision section 11.1 makes fatal. - #[moq_clock::test] + #[kio::test] async fn an_alias_reused_for_another_track_is_fatal() { let subscriber = subscriber_with_tracks(&[(RequestId(11), "cam", "video"), (RequestId(13), "cam", "audio")]); @@ -7334,7 +7334,7 @@ mod tests { /// Same track name under a different broadcast is a different full track name, so it is /// a collision too. - #[moq_clock::test] + #[kio::test] async fn an_alias_reused_across_broadcasts_is_fatal() { let subscriber = subscriber_with_tracks(&[(RequestId(11), "cam", "video"), (RequestId(13), "screen", "video")]); @@ -7351,7 +7351,7 @@ mod tests { /// until STOP_SENDING arrives on the direction it writes (section 6.4.2.3), /// so a subscriber that only finishes leaves it feeding an alias forever. That is what /// turns a routine unsubscribe into an endless "unknown track alias" stream. - #[moq_clock::test] + #[kio::test] async fn cancelling_a_subscription_stops_the_publisher() { for version in [Version::Draft22] { let log = cancel_a_subscription(version).await; @@ -7374,7 +7374,7 @@ mod tests { /// polled. The publisher destroyed the request when it sent the error, so treating that /// as abandonment would cancel a request that no longer exists and name a dead id back at /// a peer entitled to object. The answer wins. - #[moq_clock::test] + #[kio::test] async fn a_ready_rejection_beats_local_abandonment() { const VERSION: Version = Version::Draft18; @@ -7431,13 +7431,13 @@ mod tests { drop(track); drop(consumer); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; }); - moq_clock::timeout(std::time::Duration::from_secs(1), serving) + kio::clock::timeout(std::time::Duration::from_secs(1), serving) .await .expect("run_subscribe did not finish") .unwrap(); @@ -7485,7 +7485,7 @@ mod tests { /// A subscribe whose readers leave while it waits on a token ends, rather than holding /// its task and track until a token that may never be answered. - #[moq_clock::test] + #[kio::test] async fn an_abandoned_subscribe_stops_waiting_for_auth() { const VERSION: Version = Version::Draft18; let (mut subscriber, log, _auth, _tokens, _task_set) = waiting_on_auth(VERSION); @@ -7497,13 +7497,13 @@ mod tests { let subscription = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); - let mut serving = moq_clock::sim::spawn(async move { + let mut serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; }); assert!( - moq_clock::timeout(std::time::Duration::from_secs(1), &mut serving) + kio::clock::timeout(std::time::Duration::from_secs(1), &mut serving) .await .is_err(), "finished while the track was wanted" @@ -7512,7 +7512,7 @@ mod tests { drop(subscription); drop(track); drop(consumer); - moq_clock::timeout(std::time::Duration::from_secs(1), serving) + kio::clock::timeout(std::time::Duration::from_secs(1), serving) .await .expect("an abandoned subscribe kept waiting on its token") .unwrap(); @@ -7524,7 +7524,7 @@ mod tests { /// A subscribe under an announced route that is withdrawn while it waits on a token /// ends, judged against the union as it stands, so routing can recover. - #[moq_clock::test] + #[kio::test] async fn a_withdrawn_route_ends_a_subscribe_waiting_for_auth() { const VERSION: Version = Version::Draft18; let (mut subscriber, log, _auth, _tokens, _task_set) = waiting_on_auth(VERSION); @@ -7538,20 +7538,20 @@ mod tests { let route = kio::Producer::<()>::default(); let live = route.consume(); - let mut serving = moq_clock::sim::spawn(async move { + let mut serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, Some(live), request) .await; }); assert!( - moq_clock::timeout(std::time::Duration::from_secs(1), &mut serving) + kio::clock::timeout(std::time::Duration::from_secs(1), &mut serving) .await .is_err(), "finished while the route stood" ); drop(route); - moq_clock::timeout(std::time::Duration::from_secs(1), serving) + kio::clock::timeout(std::time::Duration::from_secs(1), serving) .await .expect("a withdrawn route kept the subscribe waiting on its token") .unwrap(); @@ -7566,7 +7566,7 @@ mod tests { /// independent of the request stream. If the last consumer leaves in that window, the /// subscriber still owes it a cancellation: walking away silently is what leaves it /// serving a track nobody reads. - #[moq_clock::test] + #[kio::test] async fn abandoning_before_subscribe_ok_still_cancels() { const VERSION: Version = Version::Draft18; @@ -7597,7 +7597,7 @@ mod tests { let request = dynamic.requested_track().await.expect("no track requested"); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -7611,7 +7611,7 @@ mod tests { drop(track); drop(consumer); - moq_clock::timeout(std::time::Duration::from_secs(1), serving) + kio::clock::timeout(std::time::Duration::from_secs(1), serving) .await .expect("run_subscribe parked waiting for a response that never came") .unwrap(); @@ -7634,7 +7634,7 @@ mod tests { /// A grant revoked while the SUBSCRIBE waits for its answer refuses the request and /// cancels the subscribe at once, not once the peer answers or acknowledges the cancel. - #[moq_clock::test] + #[kio::test] async fn a_revocation_never_waits_behind_subscribe_ok() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { // A peer that accepts the stream and then says nothing at all, not even @@ -7665,7 +7665,7 @@ mod tests { let subscription = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -7675,7 +7675,7 @@ mod tests { assert!(occurrences(&log, &[ietf::Subscribe::ID as u8]) > 0, "{version}"); auth.ended(0, Error::Session(SessionError::Unauthorized)); - let result = moq_clock::timeout(Duration::from_secs(1), subscription) + let result = kio::clock::timeout(Duration::from_secs(1), subscription) .await .unwrap_or_else(|_| panic!("{version}: the revocation waited behind SUBSCRIBE_OK")); assert!( @@ -7695,7 +7695,7 @@ mod tests { /// An unanswered epochless request cannot prove which instance the peer resolved. /// Retiring its source cancels it even while the caller keeps its demand. - #[moq_clock::test] + #[kio::test] async fn a_retirement_before_subscribe_ok_refuses_the_subscription() { const VERSION: Version = Version::Draft18; @@ -7729,7 +7729,7 @@ mod tests { let request = dynamic.requested_track().await.expect("no track requested"); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -7948,7 +7948,7 @@ mod tests { macro_rules! setup_wait_test { ($name:ident, $stage:ident, [$($version:ident),+]) => { - #[moq_clock::test] + #[kio::test] async fn $name() { for version in [$(Version::$version),+] { for cause in [Invalidated::Retired, Invalidated::Revoked, Invalidated::Narrowed, Invalidated::Expired] { @@ -8003,7 +8003,7 @@ mod tests { /// finished is still retransmitting, so the writer's Drop reset would discard the message /// before the peer read it. Closing consumes the writer, which is what removes that /// fallback, so a reset here means the cancellation never landed. - #[moq_clock::test] + #[kio::test] async fn cancelling_does_not_reset_away_the_unsubscribe() { for version in [Version::Draft22] { let log = cancel_a_subscription(version).await; @@ -8020,7 +8020,7 @@ mod tests { window: Option, ) -> ( crate::lite::test_transport::ScriptedSession, - moq_clock::sim::JoinHandle<()>, + kio::clock::sim::JoinHandle<()>, crate::track::Consumer, kio::Pending, ) { @@ -8058,7 +8058,7 @@ mod tests { let track = producer.consume().track("video").unwrap(); let first = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { let _producer = producer; subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) @@ -8071,7 +8071,7 @@ mod tests { /// A REQUEST_UPDATE the peer's send window holds back part-way is still buffered when /// PUBLISH_DONE ends the subscription, so the stream resets rather than FIN a truncated /// update. - #[moq_clock::test] + #[kio::test] async fn a_stalled_update_resets_when_the_publisher_ends() { // The SUBSCRIBE alone, measured over an open window. let subscribe = { @@ -8113,7 +8113,7 @@ mod tests { .await .unwrap(); // Past the grace PUBLISH_DONE waits out for its data streams; the copy then lingers. - moq_clock::sleep(crate::ledger::GRACE * 2).await; + kio::clock::sleep(crate::ledger::GRACE * 2).await; assert_eq!(session.log.resets(), vec![crate::ietf::error::CANCELLED]); assert!( !session @@ -8201,7 +8201,7 @@ mod tests { // subscription reached Established rather than assume it. let probe = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -8224,7 +8224,7 @@ mod tests { drop(track); drop(consumer); - moq_clock::timeout(crate::track::IDLE_LINGER * 2, serving) + kio::clock::timeout(crate::track::IDLE_LINGER * 2, serving) .await .expect("run_subscribe did not finish") .unwrap(); @@ -8283,7 +8283,7 @@ mod tests { let request = dynamic.requested_track().await.expect("no track requested"); let probe = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -8335,7 +8335,7 @@ mod tests { /// Serve the front's request on its wake, before the requesting call can return. /// A peer that refuses TRACK_STATUS must still receive SUBSCRIBE for a catalog reader. - #[moq_clock::test] + #[kio::test] async fn a_catalog_subscription_never_requests_track_status() { use std::sync::{Arc, Mutex}; use std::task::{Context, Wake, Waker}; @@ -8411,7 +8411,7 @@ mod tests { // Run the request classification before the front can add demand after // its query. The simulator takes over only once the wire work parks. if std::future::Future::poll(serving.as_mut(), &mut Context::from_waker(Waker::noop())).is_pending() { - drop(moq_clock::sim::spawn(serving)); + drop(kio::clock::sim::spawn(serving)); } } } @@ -8440,7 +8440,7 @@ mod tests { /// Query-only and fetch-only demand fail with the peer's TRACK_STATUS refusal, /// including NOT_SUPPORTED and undefined codes, without opening a subscription. - #[moq_clock::test] + #[kio::test] async fn a_refused_track_status_never_subscribes() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for code in [3, u64::from(u32::MAX)] { @@ -8508,7 +8508,7 @@ mod tests { /// A copy that already knows its track, here from TRACK_STATUS_OK, opts out of the /// properties when a subscriber returns only if the track is untimed: a publisher stamps /// objects only for a subscriber that took the TIMESCALE. - #[moq_clock::test] + #[kio::test] async fn a_resumed_subscribe_opts_out_only_when_untimed() { let declared = Timescale::new(90_000).unwrap(); for (version, timed) in [Version::Draft18, Version::Draft20, Version::Draft22] @@ -8568,7 +8568,7 @@ mod tests { let request = dynamic.requested_track().await.expect("no track requested"); let probe = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -8623,7 +8623,7 @@ mod tests { /// The publisher opens no fetch stream for an empty range, so a fill against a track /// with no content is owed nothing. Leaving it outstanding would withhold every later /// group behind a head that is never coming. - #[moq_clock::test] + #[kio::test] async fn an_empty_track_settles_the_fill() { assert!( !fill_after_subscribe_ok(None, Some(37)).await, @@ -8633,7 +8633,7 @@ mod tests { /// A track with content does owe one, so the fill stays outstanding until its fetch /// stream arrives. - #[moq_clock::test] + #[kio::test] async fn a_track_with_content_still_awaits_its_fill() { assert!( fill_after_subscribe_ok(Some(ietf::Location { group: 3, object: 4 }), Some(37)).await, @@ -8641,7 +8641,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn an_older_peer_without_priority_property_uses_wire_default() { assert!(!fill_after_subscribe_ok(None, None).await); } @@ -8665,7 +8665,7 @@ mod tests { /// A namespace past the session's cap closes the session with TOO_MANY_REQUESTS, a /// repeat of a held namespace costs nothing, and a retraction frees its slot. - #[moq_clock::test] + #[kio::test] async fn namespaces_past_the_cap_close_the_session() { let session = crate::lite::test_transport::SinkSession::new(Default::default()); let log = session.log.clone(); @@ -8721,7 +8721,7 @@ mod tests { /// moq-transport carries no hop ids, so a peer's broadcasts are marked /// anonymous (hop 0). An identity assigned via `Client::with_peer_hop` is /// stored as `via` for split-horizon and never written into the chain. - #[moq_clock::test] + #[kio::test] async fn assigned_peer_hop_attributes_announces() { let session = crate::lite::test_transport::SinkSession::new(Default::default()); let assigned = crate::Hop::new(777).unwrap(); @@ -8764,7 +8764,7 @@ mod tests { /// claiming the path: taking it over would leave only a route we refuse to /// advertise back to the peer, and the publish direction would withdraw the /// announce it just made. - #[moq_clock::test] + #[kio::test] async fn reflected_announce_does_not_evict_the_source_we_publish() { let session = crate::lite::test_transport::SinkSession::new(Default::default()); let peer = crate::Hop::new(777).unwrap(); @@ -8818,7 +8818,7 @@ mod tests { /// Two sessions assigned the same identity announce the same anonymous chain. /// Without an epoch the fresh session is another source, so consumers restart /// once, and retracting the stale session leaves the fresh route standing quietly. - #[moq_clock::test] + #[kio::test] async fn reconnecting_peer_restarts_the_route() { let peer = crate::Hop::new(777).unwrap(); let self_origin = crate::Hop::new(1).unwrap(); @@ -8851,13 +8851,13 @@ mod tests { }; let first = connect(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; announced.expect_next_active("room/host").await; // The peer reconnects before the old session is retired: an identical route // from the fresh session wins at once, as another source. let _second = connect(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; announced.expect_next_restarted("room/host").await; announced.assert_next_wait(); @@ -8866,7 +8866,7 @@ mod tests { // The stale session finally retracting leaves the fresh route standing. drop(first); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; announced.assert_next_wait(); assert!(routed_now(&consumer, "room/host").is_some()); } @@ -8915,7 +8915,7 @@ mod tests { /// A negotiated advertisement carries the whole path and its accumulated cost, and /// the receiving relay charges its own link on top (saturating, so an absurd /// upstream value ranks last rather than wrapping to best). - #[moq_clock::test] + #[kio::test] async fn cluster_advert_becomes_a_route_with_the_link_charged() { let (subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -8951,7 +8951,7 @@ mod tests { /// An advertisement whose path already contains our own Hop ID looped back: /// forwarding it would extend the loop and subscribing through it would route us /// back to ourselves. Hop ID 0 identifies nothing, so it is never a loop. - #[moq_clock::test] + #[kio::test] async fn cluster_advert_loop_is_discarded() { let (subscriber, _origin) = cluster_subscriber(crate::Hop::new(5).unwrap()); let peer = cluster::Peer { @@ -8974,7 +8974,7 @@ mod tests { /// An unpriced link costs 1, so an unpriced mesh accumulates a cost equal to the /// hop count and degenerates to shortest-path routing. - #[moq_clock::test] + #[kio::test] async fn unpriced_link_costs_one() { let (subscriber, _origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let peer = cluster::Peer { @@ -9003,7 +9003,7 @@ mod tests { /// /// Driven through the real exit path rather than by calling `stop_announce`: a test /// that picked the detach itself would still pass if the stream stopped using it. - #[moq_clock::test] + #[kio::test] async fn a_lost_namespace_stream_closes_the_broadcast() { const VERSION: Version = Version::Draft18; @@ -9057,7 +9057,7 @@ mod tests { /// NAMESPACE has no REQUEST_UPDATE, so a peer reprices one by re-sending it on the /// SUBSCRIBE_NAMESPACE stream. The repeat is neither a duplicate nor a violation: it /// replaces the advertisement in place, and the route is never retracted for it. - #[moq_clock::test] + #[kio::test] async fn a_re_sent_namespace_reprices_in_place() { const VERSION: Version = Version::Draft18; @@ -9150,7 +9150,7 @@ mod tests { /// The peer explicitly retracting a namespace ends the broadcast immediately: it /// said the namespace is gone, so a later create at the path is new content. - #[moq_clock::test] + #[kio::test] async fn an_explicit_namespace_done_closes_the_broadcast() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9169,7 +9169,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn publish_namespace_requester_fin_keeps_the_route() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for reset in [false, true] { @@ -9227,7 +9227,7 @@ mod tests { /// /// Driven through the real exit path rather than by calling `stop_announce`: a test /// that picked the detach itself would still pass if the stream stopped using it. - #[moq_clock::test] + #[kio::test] async fn a_broken_publish_namespace_stream_closes_the_broadcast() { const VERSION: Version = Version::Draft18; @@ -9292,7 +9292,7 @@ mod tests { /// which is what these advertisements would be had they arrived on two sessions. The /// refcount is a detail of sharing one `SourceGuard` per session; it must not change /// what the origin sees. - #[moq_clock::test] + #[kio::test] async fn the_last_owner_out_decides_the_detach() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9330,7 +9330,7 @@ mod tests { /// A source minted under a namespace goes once nothing holds it, so the session keeps /// nothing for a path its fronts let go of, and goes at once as the namespace is /// retracted, held or not. - #[moq_clock::test] + #[kio::test] async fn a_minted_source_closes_unheld_or_retracted() { let (subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let run = |route: &kio::Producer<()>| { @@ -9339,7 +9339,7 @@ mod tests { ); let (holder, dynamic) = (source.consume(), source.requests()); let (this, route) = (subscriber.clone(), route.consume()); - let task = moq_clock::sim::spawn(async move { + let task = kio::clock::sim::spawn(async move { this.run_broadcast(crate::Path::from_static("pool/p"), source, dynamic, Some(route)) .await }); @@ -9365,7 +9365,7 @@ mod tests { /// An advertisement with no path of its own (a peer that did not negotiate the /// extension) still pays for the link it arrived over. Forwarding it as free would /// advertise a paid upstream as the cheapest route in the mesh. - #[moq_clock::test] + #[kio::test] async fn a_pathless_advert_still_pays_for_its_link() { let (unpriced, _origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let peer = cluster::Peer::default(); @@ -9391,7 +9391,7 @@ mod tests { /// An update replaces the advertisement in place: the route moves, the refcount does /// not, and the source is not torn down. - #[moq_clock::test] + #[kio::test] async fn cluster_update_replaces_in_place() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9432,7 +9432,7 @@ mod tests { /// relay signals that it started carrying the namespace), so the source and every /// live subscription on it must survive. Reading the repeat as a new publisher /// detached the source milliseconds after SUBSCRIBE went out. - #[moq_clock::test] + #[kio::test] async fn anonymous_publisher_survives_a_repricing_update() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9482,7 +9482,7 @@ mod tests { /// another, on separate streams that arrive in either order. The newest advertisement /// stands, so neither the old one's late update nor its withdrawal reverts the route /// to the instance it named. - #[moq_clock::test] + #[kio::test] async fn a_reordered_replacement_keeps_the_new_instance() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9530,7 +9530,7 @@ mod tests { /// MoQ Epoch: a namespace advertised both inline and by a later PUBLISH_NAMESPACE takes /// another epoch from either. An inline repeat under the new epoch is the newest /// advertisement, not an update to the older of the two. - #[moq_clock::test] + #[kio::test] async fn a_repeat_under_another_epoch_becomes_the_newest() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9572,7 +9572,7 @@ mod tests { /// Two *separate* advertisements for one namespace refcount a single route: /// it takes both retractions to retract it. - #[moq_clock::test] + #[kio::test] async fn separate_adverts_refcount_the_route() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9610,7 +9610,7 @@ mod tests { /// one namespace are then two messages about a single source, and treating the /// second as a different publisher would tear down what the first attached, right /// as a subscriber is resolving a track through it. - #[moq_clock::test] + #[kio::test] async fn pathless_adverts_never_replace_the_source() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -9641,7 +9641,7 @@ mod tests { /// An update replaces the advertisement it repeats. When the replacement loops back /// through us it is a retraction, so the route we were holding must go: keeping it /// would leave subscriptions on a path the peer no longer offers. - #[moq_clock::test] + #[kio::test] async fn reflected_replacement_retracts_the_route() { let self_origin = crate::Hop::new(5).unwrap(); let (mut subscriber, origin) = cluster_subscriber(self_origin); @@ -9822,7 +9822,7 @@ mod tests { /// namespace even when the peer's path goes clean again. It is also not ours to /// close: a peer MAY legitimately send a path carrying our Hop ID when a redundant /// sibling shares it, which the draft answers with "discard", not PROTOCOL_VIOLATION. - #[moq_clock::test] + #[kio::test] async fn a_reflected_update_detaches_but_keeps_the_stream() { let self_origin = crate::Hop::new(5).unwrap(); let peer = peer_9(); @@ -9872,7 +9872,7 @@ mod tests { /// Having kept the stream, a later usable path re-attaches on it. This is the whole /// reason the stream stays open. - #[moq_clock::test] + #[kio::test] async fn a_clean_update_after_a_reflection_reattaches() { let self_origin = crate::Hop::new(5).unwrap(); let peer = peer_9(); @@ -9915,7 +9915,7 @@ mod tests { /// A token-authorized announce re-attaching after a reflection reuses the slot its grant /// still holds: with a cap of one, taking a second would close the session. - #[moq_clock::test] + #[kio::test] async fn a_token_announce_reattaches_on_its_own_slot() { let self_origin = crate::Hop::new(5).unwrap(); let peer = peer_9(); @@ -10005,7 +10005,7 @@ mod tests { /// The expected update: a relay that started carrying the namespace reprices it to /// 0. REQUEST_UPDATE keeps an omitted parameter, so the 0 arrives explicit and alone, /// lands on the path already held, and is answered REQUEST_OK. - #[moq_clock::test] + #[kio::test] async fn an_explicit_zero_reprices_the_held_path() { const VERSION: Version = Version::Draft18; let self_origin = crate::Hop::new(5).unwrap(); @@ -10077,7 +10077,7 @@ mod tests { /// closed, which withdraws the advertisement (moq-transport Section 9.5.1). The /// caller releases the route, so the loop must return cleanly rather than fault the /// session. - #[moq_clock::test] + #[kio::test] async fn a_failed_update_withdraws_the_advertisement() { let self_origin = crate::Hop::new(5).unwrap(); let peer = peer_9(); @@ -10135,7 +10135,7 @@ mod tests { /// An update whose first Hop ID differs names a different publisher. It still /// replaces the advertisement in place and the stream stays open: the origin, not the /// session, keeps the two publishers' content apart. - #[moq_clock::test] + #[kio::test] async fn an_update_that_changes_the_publisher_applies_in_place() { let self_origin = crate::Hop::new(5).unwrap(); let peer = peer_9(); @@ -10183,7 +10183,7 @@ mod tests { /// A second PUBLISH_NAMESPACE on the stream that already carries one is not an /// update any more: it is the base draft's duplicate request, a protocol violation. - #[moq_clock::test] + #[kio::test] async fn a_repeated_publish_namespace_is_a_duplicate() { const VERSION: Version = Version::Draft18; let self_origin = crate::Hop::new(5).unwrap(); @@ -10250,7 +10250,7 @@ mod tests { /// without a NAMESPACE_DONE for each, those refcounts must still be released, or the /// source stays attached for the rest of the session (the stream can die while the /// session keeps running). - #[moq_clock::test] + #[kio::test] async fn namespace_stream_close_releases_live_paths() { let (mut subscriber, origin) = cluster_subscriber(crate::Hop::new(1).unwrap()); let consumer = origin.consume(); @@ -10280,7 +10280,7 @@ mod tests { /// PUBLISH offers one track, but a source attaches per namespace and serves every /// track under it. Rather than invent a namespace-level source from a track-level /// offer, decline the request with NOT_SUPPORTED and leave the session running. - #[moq_clock::test] + #[kio::test] async fn publish_is_rejected_without_announcing() { for version in [Version::Draft18] { // An open gate, so the rejection actually reaches the wire. @@ -10323,7 +10323,7 @@ mod tests { // Errors are surfaced to the peer on the stream, not raised as a session error. subscriber.run_publish_stream(stream, msg).await.unwrap(); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert!( routed_now(&consumer, "room/host").is_none(), @@ -10509,7 +10509,7 @@ mod tests { /// A request token on a PUBLISH_NAMESPACE the session grant does not cover authorizes /// the announce: the subscriber verifies it through the acceptor and attaches the route. - #[moq_clock::test] + #[kio::test] async fn a_publish_namespace_token_authorizes_an_uncovered_announce() { const VERSION: Version = Version::Draft18; let (mut subscriber, mut requests, _cred, consumer, session) = auth_announce_harness(VERSION, Vec::new()); @@ -10548,7 +10548,7 @@ mod tests { /// An announce's grant ending while its first answer waits on a peer that stopped /// reading retracts the route at once, not once the answer drains: the peer is told /// only afterwards. - #[moq_clock::test] + #[kio::test] async fn a_revoked_token_retracts_an_announce_whose_ok_is_blocked() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let gate = kio::Producer::new(false); @@ -10599,7 +10599,7 @@ mod tests { }; *open = true; drop(open); - let _ = moq_clock::timeout(std::time::Duration::from_secs(1), run.as_mut()) + let _ = kio::clock::timeout(std::time::Duration::from_secs(1), run.as_mut()) .await .unwrap_or_else(|_| panic!("{version}: outlived its grant")); @@ -10628,7 +10628,7 @@ mod tests { /// A refused request token is answered UNAUTHORIZED and the announce is not attached; the /// session is untouched. - #[moq_clock::test] + #[kio::test] async fn a_refused_publish_namespace_token_is_not_announced() { const VERSION: Version = Version::Draft18; let (mut subscriber, mut requests, _cred, consumer, session) = auth_announce_harness(VERSION, Vec::new()); @@ -10668,7 +10668,7 @@ mod tests { /// What the peer's AUTH_OK grants us never authorizes what the peer asks of us: with a /// covering peer grant and no limit, the application still verifies the announce's token, /// and its refusal refuses the announce. - #[moq_clock::test] + #[kio::test] async fn a_covering_peer_grant_never_skips_the_verifier() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(true); @@ -10718,7 +10718,7 @@ mod tests { /// one stands outside the limit: narrowing the limit away from it leaves it attached, as the /// publisher, which counts it token-backed, expects. Admitted on the limit instead, the /// narrowing would withhold a route the publisher still believes its token backs. - #[moq_clock::test] + #[kio::test] async fn a_covering_limit_still_verifies_the_token() { const VERSION: Version = Version::Draft18; let limit = |subtree: &str| crate::auth::Grant { @@ -10780,7 +10780,7 @@ mod tests { /// A token-authorized announce stands outside the limit while it lasts: a narrower limit /// leaves it attached, and only its own end retracts it. - #[moq_clock::test] + #[kio::test] async fn a_token_authorized_announce_is_exempt_from_the_limit() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(false); @@ -10831,7 +10831,7 @@ mod tests { /// A token-authorized announce authorizes the tracks subscribed under it, outside the /// limit, and only while its token lasts. - #[moq_clock::test] + #[kio::test] async fn a_token_authorized_announce_admits_its_subscriptions() { const VERSION: Version = Version::Draft18; let auth = crate::auth::Link::new(false); @@ -10930,7 +10930,7 @@ mod tests { /// A REQUEST_UPDATE the acceptor renews keeps a token-authorized announce alive past the /// old grant's expiry: the subscriber re-verifies the token off the announce stream and /// re-arms the deadline. - #[moq_clock::test] + #[kio::test] async fn a_publish_namespace_renewal_extends_past_the_old_expiry() { for version in [Version::Draft18] { let (mut subscriber, mut requests, _cred, consumer, session) = @@ -10988,7 +10988,7 @@ mod tests { // Past the original 60s expiry: the renewal re-armed the deadline, so the announce // stays attached. - moq_clock::sim::advance(std::time::Duration::from_secs(120)).await; + kio::clock::sim::advance(std::time::Duration::from_secs(120)).await; for _ in 0..50 { let _ = futures::poll!(acceptor.as_mut()); assert!( @@ -11006,7 +11006,7 @@ mod tests { /// A lapsed grant retracts its announce at once, even while the withdrawal waits on a peer /// that never acknowledges the closed stream. - #[moq_clock::test] + #[kio::test] async fn a_lapsed_announce_grant_retracts_before_the_peer_reads() { const VERSION: Version = Version::Draft18; let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new()]).with_unacked_fin(); @@ -11042,7 +11042,7 @@ mod tests { } assert!(routed, "the token must authorize the announce"); - moq_clock::sim::advance(std::time::Duration::from_secs(120)).await; + kio::clock::sim::advance(std::time::Duration::from_secs(120)).await; let mut retracted = false; for _ in 0..50 { let _ = futures::poll!(acceptor.as_mut()); @@ -11064,7 +11064,7 @@ mod tests { /// An update repeating its token withdraws a token-authorized announce, retracting the route /// at once even while the withdrawal waits on a peer that never acknowledges it. - #[moq_clock::test] + #[kio::test] async fn a_repeated_token_update_retracts_before_the_peer_reads() { const VERSION: Version = Version::Draft18; const TOKEN: &[u8] = &[0x03, 0x00, 0xAA]; @@ -11116,7 +11116,7 @@ mod tests { /// Per draft-18 section 10.9.1, a refused PUBLISH_NAMESPACE /// renewal ends only that announce at once, by closing its stream, not by waiting for /// the old 60s grant to lapse. The session stays up. - #[moq_clock::test] + #[kio::test] async fn a_refused_publish_namespace_renewal_ends_the_announce() { for version in [Version::Draft18] { let (mut subscriber, mut requests, _cred, _consumer, session) = @@ -11178,7 +11178,7 @@ mod tests { /// Where tokens decide, a token arriving on an update for an announce the limit admitted /// without one is refused rather than taken unread: it ends only that announce, unverified. - #[moq_clock::test] + #[kio::test] async fn a_token_on_an_announce_admitted_without_one_is_refused() { for version in [Version::Draft18] { let (mut subscriber, mut requests, _cred, consumer, session) = @@ -11224,7 +11224,7 @@ mod tests { /// renewal re-arms the grant and the HOP_PATH/ROUTE_COST re-route the advertisement, /// answered with the renewal's single response. Before the fix the token branch /// short-circuited the loop and the cluster parameters on the same update were dropped. - #[moq_clock::test] + #[kio::test] async fn an_update_applies_both_a_renewal_and_cluster_params() { const VERSION: Version = Version::Draft18; let (mut subscriber, mut requests, _cred, consumer, session) = @@ -11305,7 +11305,7 @@ mod tests { /// (0x05) changes only ROUTE_COST (4 to 1) and the last (0x07) only HOP_PATH, so the final /// cost shows the middle delta survived; the single slot this replaced dropped 0x05, /// leaving the cost at the initial 4 and never verifying its token. - #[moq_clock::test] + #[kio::test] async fn two_announce_renewals_buffered_behind_a_pending_verdict_each_apply_and_answer() { const VERSION: Version = Version::Draft18; @@ -11385,7 +11385,7 @@ mod tests { /// an announce stream broke the negotiated limit: draft-22 section 9.1.7 closes the session /// with TOO_MANY_REQUEST_UPDATES. run_publish_namespace_updates must close explicitly (the /// dispatcher does not close on an Error::Session), and surface that error too. - #[moq_clock::test] + #[kio::test] async fn announce_renewals_past_the_advertised_limit_close_the_session() { const VERSION: Version = Version::Draft22; @@ -11446,7 +11446,7 @@ mod tests { /// Exactly MAX_REQUEST_UPDATES outstanding (the one being verified plus the queue) is within /// the advertised limit, so a draft-22 peer holding that many is not faulted: the announce /// keeps running and the session stays up. - #[moq_clock::test] + #[kio::test] async fn announce_renewals_at_the_advertised_limit_keep_the_announce() { const VERSION: Version = Version::Draft18; @@ -11492,7 +11492,7 @@ mod tests { /// Drafts below 19 carry no MAX_REQUEST_UPDATES option, so a peer there agreed to no ceiling: /// the same flood that closes a draft-22 session must neither end the announce nor close the /// session on draft-18, because a conforming peer must not be stranded for a limit it never saw. - #[moq_clock::test] + #[kio::test] async fn older_drafts_do_not_strand_an_announce_flood() { const VERSION: Version = Version::Draft18; @@ -11535,7 +11535,7 @@ mod tests { /// On drafts without the option the guard is a memory backstop, not a protocol limit: a flood /// past it ends the one announce by finishing the stream, never the session. - #[moq_clock::test] + #[kio::test] async fn an_older_draft_announce_flood_past_the_guard_ends_the_announce() { const VERSION: Version = Version::Draft18; @@ -11584,7 +11584,7 @@ mod tests { /// A flood past the guard retracts the announce at once, even while the withdrawal waits on /// a peer that never acknowledges the finished stream. - #[moq_clock::test] + #[kio::test] async fn a_flood_past_the_guard_retracts_before_the_peer_reads() { const VERSION: Version = Version::Draft18; @@ -11706,7 +11706,7 @@ mod tests { /// On a session without the AUTH extension, a token-bearing PUBLISH_NAMESPACE the limit /// does not cover is verified by the application. Admitted on a covering grant; refused /// UNAUTHORIZED (not admitted) on refusal. This is the standard moq-transport peer shape. - #[moq_clock::test] + #[kio::test] async fn a_request_token_on_a_no_auth_session_is_verified() { const VERSION: Version = Version::Draft18; @@ -11799,7 +11799,7 @@ mod tests { /// A peer that ends the announce while a renewal is still being verified ends it here too: /// with a grant that never expires and an acceptor that never answers the renewal, only /// the stream closing can end the request, and it must. - #[moq_clock::test] + #[kio::test] async fn a_closed_announce_ends_while_a_renewal_is_pending() { const VERSION: Version = Version::Draft18; let session = crate::lite::test_transport::ScriptedSession::per_stream_eof(vec![ @@ -11854,7 +11854,7 @@ mod tests { /// An update queued behind a pending renewal spends its request ID on arrival, so the /// announce ending before the queue drains leaves no ID the peer could reuse. - #[moq_clock::test] + #[kio::test] async fn a_queued_update_spends_its_request_id_when_the_announce_ends() { const VERSION: Version = Version::Draft18; let queued = { @@ -11916,7 +11916,7 @@ mod tests { /// An update queued behind a pending renewal is decoded on arrival, so a session-fatal one /// still closes the session when the peer withdraws before the queue drains. - #[moq_clock::test] + #[kio::test] async fn a_queued_malformed_update_is_fatal_despite_a_withdrawal() { const VERSION: Version = Version::Draft18; let queued = { @@ -11996,7 +11996,7 @@ mod tests { /// An announcing peer's token grant is checked on its `publish` patterns: a read-only grant /// does not admit a PUBLISH_NAMESPACE, a write-only one does. - #[moq_clock::test] + #[kio::test] async fn an_announce_token_needs_a_publish_grant() { const VERSION: Version = Version::Draft18; let read_only = crate::auth::Grant { @@ -12050,7 +12050,7 @@ mod tests { /// The additive constraint: a token-LESS PUBLISH_NAMESPACE on a no-auth session (None union) /// is admitted by the origin model exactly as before; the token path is never entered. - #[moq_clock::test] + #[kio::test] async fn a_token_less_request_on_a_no_auth_session_is_unchanged() { const VERSION: Version = Version::Draft18; let (mut subscriber, _requests, consumer, session) = auth_announce_harness_no_ext(VERSION, None); @@ -12736,7 +12736,7 @@ mod stitch_tests { /// The tail is read first, so it has to wait for the head rather than start a group of /// its own: with newest-first group order the publisher can prioritize the tail's stream /// ahead of the fill's. - #[moq_clock::test] + #[kio::test] async fn a_fill_and_its_tail_stitch_into_one_group() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -12771,7 +12771,7 @@ mod stitch_tests { /// History groups finish at the next group's header; only the newest head waits /// for the live tail. A gap in group numbering is not a missing object. - #[moq_clock::test] + #[kio::test] async fn a_multi_group_fill_finishes_history_before_stitching_the_tail() { let history: &[&[u8]] = &[b"history"]; let head: &[&[u8]] = &[b"head"]; @@ -12814,7 +12814,7 @@ mod stitch_tests { /// Cancelling an update fill in a partial payload releases its tail without /// cancelling the live subscription: its next whole group still arrives. - #[moq_clock::test] + #[kio::test] async fn cancelling_an_update_fill_does_not_park_the_live_tail() { const UPDATE: RequestId = RequestId(99); let h = Harness::new( @@ -12839,7 +12839,7 @@ mod stitch_tests { assert!(futures::poll!(filling.as_mut()).is_pending()); } let mut tail = h.stream().await; - let result = moq_clock::timeout(Duration::from_secs(1), h.subscriber.clone().recv_group(&mut tail)) + let result = kio::clock::timeout(Duration::from_secs(1), h.subscriber.clone().recv_group(&mut tail)) .await .expect("cancelled fill left its tail parked"); result.expect("the live tail still supports passthrough delivery"); @@ -12855,7 +12855,7 @@ mod stitch_tests { /// A tail parked on its head stops holding the end open, so the finished fill does until /// the head is claimed: otherwise the subscription looks settled between the fill /// finishing and the tail waking, and ends before the tail is read. - #[moq_clock::test] + #[kio::test] async fn an_unclaimed_fill_holds_the_end_open() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -13095,7 +13095,7 @@ mod stitch_tests { relay_passthrough(script, ingress, egress, None).await } - #[moq_clock::test] + #[kio::test] async fn passthrough_preserves_object_properties_through_dispatch() { for version in [Version::Draft22] { let mut script = Vec::new(); @@ -13131,7 +13131,7 @@ mod stitch_tests { /// A relayed Timestamp leaves in the units the publisher declared: the cache holds the /// track on the publisher's grid, so a copy of the same instance over another route /// matches it, including across a moq-lite hop that negotiated the `ietf` extension. - #[moq_clock::test] + #[kio::test] async fn passthrough_keeps_the_publishers_timestamp_units() { let version = Version::Draft22; // Timestamp 42 (ms), then an unknown property that must survive beside it. @@ -13189,7 +13189,7 @@ mod stitch_tests { bytes } - #[moq_clock::test] + #[kio::test] async fn passthrough_fetch_requires_marked_gaps_and_preserves_fields() { for version in [Version::Draft22] { for marked in [false, true] { @@ -13247,7 +13247,7 @@ mod stitch_tests { /// A relayed FETCH ends its answer at the last frame rather than carrying the /// END_OF_GROUP object, and the next relay fills its cache from that answer. - #[moq_clock::test] + #[kio::test] async fn passthrough_fetch_ends_at_the_last_frame() { for version in [Version::Draft22] { let objects = [ @@ -13287,7 +13287,7 @@ mod stitch_tests { /// Only a Normal object may carry properties: a status object with them is refused on /// ingest. - #[moq_clock::test] + #[kio::test] async fn passthrough_keeps_properties_off_status_objects() { for version in [Version::Draft22] { for status in [END_OF_GROUP, END_OF_TRACK] { @@ -13304,7 +13304,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_refuses_contradictory_gap_properties() { for properties in [vec![0x3e, 2], vec![0x3e, 3], vec![0x3e, 1, 0, 1]] { let script = object_stream(VERSION, true, &[(0, &[], None), (2, &properties, None)]); @@ -13317,7 +13317,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_fetch_ingest_keeps_marked_gaps_and_stitches_its_tail() { for version in [Version::Draft22] { let mut objects = Vec::new(); @@ -13383,7 +13383,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_preserves_ids_first_object_and_end_status() { for version in [Version::Draft22] { for first in [false, true] { @@ -13413,7 +13413,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_preserves_immutable_bytes() { for ingress in [Version::Draft18, Version::Draft20, Version::Draft22] { let mut inner = Vec::new(); @@ -13442,7 +13442,7 @@ mod stitch_tests { /// dropped on its way to draft 22 when mutable, and refused when sealed, through a /// moq-lite hop too: drafts 18 and 22 serialize a block alike, so only the track's /// carried ingress draft tells them apart. - #[moq_clock::test] + #[kio::test] async fn passthrough_keeps_0x06_from_crossing_to_draft_22() { let (ingress, egress) = (Version::Draft18, Version::Draft22); // 0x06 = 42 and 0x20 = 7, mutable. @@ -13473,7 +13473,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_preserves_datagram_objects_through_dispatch() { // Also through a second relay behind a moq-lite hop with the `ietf` extension. for (version, ranged, hop) in [Version::Draft22] @@ -13587,7 +13587,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_translates_mutable_property_encodings() { for ingress in [Version::Draft22] { let mut properties = Vec::new(); @@ -13613,7 +13613,7 @@ mod stitch_tests { } } - #[moq_clock::test] + #[kio::test] async fn passthrough_accepts_nonzero_first_objects_and_gaps() { for version in [Version::Draft22] { let mut script = Vec::new(); @@ -13642,7 +13642,7 @@ mod stitch_tests { } /// Relays retain a datagram's Object ID; a plain reader skips it until object 0 arrives. - #[moq_clock::test] + #[kio::test] async fn passthrough_accepts_datagrams_past_object_zero() { let version = Version::Draft22; let mut h = Harness::with_timescale(Fill::Done, vec![], None); @@ -13680,7 +13680,7 @@ mod stitch_tests { ); } - #[moq_clock::test] + #[kio::test] async fn an_overflowing_object_id_reaches_session_teardown() { let mut bytes = tail_stream(SEQUENCE, 0, &[b"head"]); crate::coding::Encoder::new(&mut bytes, VERSION.into()) @@ -13696,7 +13696,7 @@ mod stitch_tests { } /// A subgroup 1 stream costs only itself: the track's subgroup 0 stream still arrives. - #[moq_clock::test] + #[kio::test] async fn a_non_zero_subgroup_leaves_the_track_flowing() { let mut refused = Vec::new(); ietf::GroupHeader { @@ -13733,7 +13733,7 @@ mod stitch_tests { /// 2 is subgroup 2: refused like an explicit one, never taken as subgroup 0, even when the /// rest of that object is cut off. A compact stream with no objects names no subgroup and /// is subgroup 0. - #[moq_clock::test] + #[kio::test] async fn a_compact_non_zero_subgroup_is_refused() { for version in [Version::Draft22] { let compact = |sequence: u64, first: Option| { @@ -13824,7 +13824,7 @@ mod stitch_tests { } /// A truncated property inside a later object's extension block is a malformed group. - #[moq_clock::test] + #[kio::test] async fn a_malformed_extension_block_is_refused() { // Delta 0, then a 1-byte extension block holding half of a 2-byte varint. let mut stream = tail_stream(SEQUENCE, 0, &[b"ok"]); @@ -13834,14 +13834,14 @@ mod stitch_tests { } /// A FIN before the declared payload ends. - #[moq_clock::test] + #[kio::test] async fn a_payload_cut_short_is_refused() { let h = Harness::with_timescale(Fill::Done, vec![raw_stream(SEQUENCE, &[0, 4], &[1, 2])], None); h.dispatch_refused().await; } /// A declared object size past what a group may hold. - #[moq_clock::test] + #[kio::test] async fn an_oversized_frame_is_refused() { let size = crate::group::MAX_CACHE_BYTES + 1; let h = Harness::with_timescale(Fill::Done, vec![raw_stream(SEQUENCE, &[0, size], &[])], None); @@ -13849,7 +13849,7 @@ mod stitch_tests { } /// A second stream for a group the track already holds. - #[moq_clock::test] + #[kio::test] async fn a_second_stream_for_a_group_is_refused() { let whole = raw_stream(SEQUENCE, &[0, 1], &[42]); let h = Harness::with_timescale(Fill::Done, vec![whole.clone(), whole], None); @@ -13858,7 +13858,7 @@ mod stitch_tests { h.dispatch_refused().await; } - #[moq_clock::test] + #[kio::test] async fn object_extension_limit() { for size in [65536usize, 65537] { for first in [true, false] { @@ -13932,7 +13932,7 @@ mod stitch_tests { /// A fill object without a Timestamp on a timed track ends the track, as a subgroup /// object does: the fill is the head of a group the subscription carries. - #[moq_clock::test] + #[kio::test] async fn an_unstamped_fill_object_ends_the_track() { use futures::FutureExt; @@ -13969,7 +13969,7 @@ mod stitch_tests { /// A subgroup object without a Timestamp on a timed track makes the whole track /// malformed, so the track ends rather than only its group. - #[moq_clock::test] + #[kio::test] async fn an_unstamped_subgroup_object_ends_the_track() { use futures::FutureExt; @@ -14000,7 +14000,7 @@ mod stitch_tests { } /// END_OF_TRACK after a group's last object ends the track right after that group. - #[moq_clock::test] + #[kio::test] async fn an_end_of_track_after_a_group_ends_the_track_after_it() { let h = Harness::new( Fill::Done, @@ -14024,7 +14024,7 @@ mod stitch_tests { assert!(consumer.recv_group().await.unwrap().is_none(), "then the track ends"); } - #[moq_clock::test] + #[kio::test] async fn a_standalone_end_of_track_preserves_a_nonzero_object() { let mut marker = tail_stream(5, 5, &[]); for value in [5u64, 0, 0, END_OF_TRACK] { @@ -14043,7 +14043,7 @@ mod stitch_tests { /// A group at or past the end an END_OF_TRACK declared contradicts that end, which no /// later stream can repair, so the whole track fails rather than ending clean without it. - #[moq_clock::test] + #[kio::test] async fn a_group_past_the_declared_end_aborts_the_track() { use futures::FutureExt; @@ -14061,7 +14061,7 @@ mod stitch_tests { /// END_OF_TRACK at object 0 says the group does not exist, so the track ends before it /// and no group is created for it. - #[moq_clock::test] + #[kio::test] async fn an_end_of_track_at_object_zero_creates_no_group() { let h = Harness::new( Fill::Done, @@ -14076,7 +14076,7 @@ mod stitch_tests { /// The group ended exactly where we joined it, so the subscription's stream carries no /// objects at all. That still ends the group, which is what publishes the head. - #[moq_clock::test] + #[kio::test] async fn an_empty_tail_finishes_the_filled_group() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14101,7 +14101,7 @@ mod stitch_tests { /// A fill that ends without the head it owed settles before the mid-group tail arrives. /// The tail then has a hole at the front, so it is dropped as it would be had it waited /// on the fill, rather than cached as a whole group starting at its first object. - #[moq_clock::test] + #[kio::test] async fn a_headless_tail_after_the_fill_settles_is_dropped() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14129,7 +14129,7 @@ mod stitch_tests { /// The same headless tail arriving first waits on the fill, and is dropped once the fill /// ends without the head. - #[moq_clock::test] + #[kio::test] async fn a_headless_tail_before_the_fill_settles_is_dropped() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14159,7 +14159,7 @@ mod stitch_tests { /// A subscription that requested no head was owed none, so a stream starting mid-group /// still stands alone. - #[moq_clock::test] + #[kio::test] async fn a_mid_group_stream_without_a_fill_stands_alone() { let h = Harness::new(Fill::Done, vec![tail_stream(SEQUENCE, 2, &[b"tail-2"])]); let mut consumer = h.track.subscribe(None); @@ -14175,7 +14175,7 @@ mod stitch_tests { /// cannot reach a producer the fetch stream still owns. The handoff has to settle it, or /// the head outlives the subscription unfinished and a consumer blocks on it. It is /// cancelled rather than finished, since nothing says the group ended there. - #[moq_clock::test] + #[kio::test] async fn a_head_finishing_after_teardown_is_cancelled_not_installed() { let track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), @@ -14201,7 +14201,7 @@ mod stitch_tests { /// A joining FETCH whose request fails while its stream is still writing has already /// dropped the headless tail, so a head landing afterwards is cancelled, not installed /// for a tail that is gone. - #[moq_clock::test] + #[kio::test] async fn a_head_finishing_after_its_fill_failed_is_cancelled() { let track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), @@ -14229,7 +14229,7 @@ mod stitch_tests { /// A joining FETCH is not in PUBLISH_DONE's Stream Count, so the subscription can end /// cleanly after its request failed and its headless tail was dropped, with the head /// still writing. That head is cancelled when it lands, not published as the whole group. - #[moq_clock::test] + #[kio::test] async fn a_clean_end_keeps_a_failed_fill_terminal() { let track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), @@ -14258,7 +14258,7 @@ mod stitch_tests { /// Widening updates replaced fills that failed to head this group and the next, and the /// current fill has settled. A mid-group tail at or below the last failed group is still /// headless, so it is dropped, while a whole group there stands alone. - #[moq_clock::test] + #[kio::test] async fn a_headless_tail_after_its_fill_was_replaced_is_dropped() { let h = Harness::new( Fill::Done, @@ -14288,7 +14288,7 @@ mod stitch_tests { /// Leaving a track while its head waits for the tail cancels that group rather than /// finishing it: the group may still be open upstream, and a finished copy would cut it /// short for a rejoin. - #[moq_clock::test] + #[kio::test] async fn an_unclaimed_head_is_cancelled_when_the_subscription_goes() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14306,7 +14306,7 @@ mod stitch_tests { } /// Closing locally cancels a filled head whose live tail never arrived. - #[moq_clock::test] + #[kio::test] async fn an_unclaimed_head_is_cancelled_when_the_session_closes() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14331,7 +14331,7 @@ mod stitch_tests { /// A publisher that serves a head and then opens a whole group for the same sequence /// has contradicted its own fill. The model holds one producer per group, so the /// duplicate stream and unfinished head are refused without caching a cut group. - #[moq_clock::test] + #[kio::test] async fn a_whole_group_for_a_headed_sequence_is_refused() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14358,7 +14358,7 @@ mod stitch_tests { /// A fill head parked waiting for its tail is still a live group producer. Dropping the /// session has to end it, or the consumer waits on a group nobody will ever write again. /// The guard is `State`'s own `Drop`, so it runs however the driver was torn down. - #[moq_clock::test] + #[kio::test] async fn a_cancelled_session_aborts_a_waiting_fill_head() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14384,7 +14384,7 @@ mod stitch_tests { ); } - #[moq_clock::test] + #[kio::test] async fn session_death_keeps_a_waiting_fill_heads_resume_position() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14416,7 +14416,7 @@ mod stitch_tests { /// group lands before the fill has written its head. The model holds one producer per /// live sequence, so the fill loses the race to create it and gives up, rather than a /// second producer appearing and the objects being delivered twice. - #[moq_clock::test] + #[kio::test] async fn a_whole_group_that_precedes_the_head_wins_the_sequence() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14447,7 +14447,7 @@ mod stitch_tests { } /// A standalone subgroup tail keeps its identity while plain readers see its payload. - #[moq_clock::test] + #[kio::test] async fn a_tail_without_a_fill_is_preserved() { let h = Harness::new(Fill::Done, vec![tail_stream(SEQUENCE, 2, &[b"tail-2"])]); let mut consumer = h.track.subscribe(None); @@ -14459,7 +14459,7 @@ mod stitch_tests { /// Object IDs are absolute whatever FIRST_OBJECT says, and they start at 0, so a /// draft-18 stream that leaves the bit clear and starts at object 0 is the whole /// group. The publisher is out of spec on the bit, not missing a head. - #[moq_clock::test] + #[kio::test] async fn a_clear_first_object_at_zero_delivers_the_group() { let bytes = draft18_subgroup(SEQUENCE, false, 0, &[b"whole", b"next"]); assert_eq!( @@ -14484,7 +14484,7 @@ mod stitch_tests { /// The END_OF_GROUP header bit only lets a FIN imply the group's end, so an explicit /// END_OF_GROUP status on the same stream ends the group there rather than failing it. - #[moq_clock::test] + #[kio::test] async fn an_end_of_group_status_on_a_marked_stream_finishes_the_group() { use futures::FutureExt; @@ -14512,7 +14512,7 @@ mod stitch_tests { } /// FIRST_OBJECT and the starting ID are independent relay metadata. - #[moq_clock::test] + #[kio::test] async fn a_clear_first_object_past_zero_is_preserved() { let partial = draft18_subgroup(SEQUENCE, false, 3, &[b"tail-3"]); let whole = draft18_subgroup(SEQUENCE + 1, true, 0, &[b"next"]); @@ -14543,7 +14543,7 @@ mod stitch_tests { /// A received group whose first object rewinds past the group before it is accepted: a /// moq-transport peer may stamp arrival times, so its timed tracks are unchecked. - #[moq_clock::test] + #[kio::test] async fn a_received_rewind_is_accepted() { use futures::FutureExt; @@ -14574,7 +14574,7 @@ mod stitch_tests { /// A head that stops short of where the tail starts would leave a hole in the middle of /// the group. Refusing it aborts the incomplete group instead of caching a cut prefix. - #[moq_clock::test] + #[kio::test] async fn a_head_that_misses_the_tail_is_refused() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14598,7 +14598,7 @@ mod stitch_tests { assert!(matches!(head.read_frame().await, Err(Error::Unsupported))); } - #[moq_clock::test] + #[kio::test] async fn receive_drain_keeps_bound_aliases_and_ends_unknown_alias_waits() { let h = Harness::new(Fill::Done, vec![]); let aliases = h.subscriber.state.lock().aliases.consume(); @@ -14612,7 +14612,7 @@ mod stitch_tests { assert!(matches!(resolve_track_alias(&h.subscriber.runtime, aliases, ALIAS).await, Ok(id) if id == REQUEST)); } - #[moq_clock::test] + #[kio::test] async fn receive_drain_ends_a_fill_waiting_for_subscribe_ok() { let h = Harness::new(Fill::Requested, vec![fill_stream(SEQUENCE, &[b"head"])]); let mut stream = h.stream().await; @@ -14626,7 +14626,7 @@ mod stitch_tests { )); } - #[moq_clock::test] + #[kio::test] async fn receive_drain_ends_a_tail_waiting_for_a_missing_fill() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14640,7 +14640,7 @@ mod stitch_tests { assert!(futures::FutureExt::now_or_never(receiving).is_some()); } - #[moq_clock::test] + #[kio::test] async fn receive_drain_preserves_a_buffered_fill_and_tail() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14667,7 +14667,7 @@ mod stitch_tests { ); } - #[moq_clock::test] + #[kio::test] async fn receive_drain_ends_a_group_fetch_waiting_for_fetch_ok() { let h = Harness::new(Fill::Done, vec![fill_stream(SEQUENCE, &[b"head"])]); h.subscriber @@ -14688,7 +14688,7 @@ mod stitch_tests { /// A fetch stream can arrive before SUBSCRIBE_OK commits the pending track. It waits /// for that response instead of looking up a producer that does not exist yet. - #[moq_clock::test] + #[kio::test] async fn an_early_fill_waits_for_subscribe_ok() { let h = Harness::new(Fill::Requested, vec![fill_stream(SEQUENCE, &[b"head-0"])]); { @@ -14710,7 +14710,7 @@ mod stitch_tests { /// A fetch stream answering a subscription that asked for no fill duplicates a group the /// subscription itself is delivering, so it is refused rather than written. - #[moq_clock::test] + #[kio::test] async fn an_unsolicited_fill_is_refused() { let h = Harness::new(Fill::Done, vec![fill_stream(SEQUENCE, &[b"head-0"])]); let mut fill = h.stream().await; @@ -14725,7 +14725,7 @@ mod stitch_tests { /// A mid-group subscribe stream waits for the joining FETCH's head and stitches onto it, /// the same rendezvous a draft-22 fill uses. The FETCH is named by its own request id. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_stitches_a_mid_group_tail() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14756,7 +14756,7 @@ mod stitch_tests { /// A subscribe stream that starts at object 0 stands alone; the joining FETCH's answer /// is discarded rather than delivered twice. - #[moq_clock::test] + #[kio::test] async fn a_whole_group_stream_discards_the_joining_fetch() { let h = Harness::new( Fill::Serving(Some(Timescale::MICRO)), @@ -14796,7 +14796,7 @@ mod stitch_tests { /// A joining FETCH carries the one group its subscription joins, so a second group on /// it is refused rather than published as a head no tail continues. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_spanning_several_groups_is_refused() { let groups: &[(u64, &[&[u8]])] = &[(9, &[b"g9-0"]), (10, &[b"g10-0"])]; let h = Harness::new( @@ -14813,7 +14813,7 @@ mod stitch_tests { /// The first object on a fetch stream has no prior object, so leaving any field to /// the prior one is a violation, not "the requested group, from its start". - #[moq_clock::test] + #[kio::test] async fn a_group_fetch_refuses_a_first_object_that_inherits() { use ietf::FetchSubgroup::{Prior, Zero}; let header = |group, object, subgroup, priority| ietf::FetchObject::Object { @@ -14854,7 +14854,7 @@ mod stitch_tests { /// On a timed track every Normal object carries a Timestamp, so one without is /// malformed rather than stamped with its arrival time. - #[moq_clock::test] + #[kio::test] async fn an_unstamped_object_on_a_timed_track_is_malformed() { let mut run = GroupFetchRun::new(VERSION, group_fetch_objects(SEQUENCE, 0, &[b"a"])).await; let track = track::Producer::new( @@ -14876,7 +14876,7 @@ mod stitch_tests { /// fails the group instead of caching it. Before draft-22 the End Location also promises /// every object before it, so a stream that FINs short fails too. From draft-22 it is the /// range covered, and the objects missing before it do not exist (section 9.11). - #[moq_clock::test] + #[kio::test] async fn a_group_fetch_stays_within_its_end_location() { const END: u64 = 3; for version in [Version::Draft18, VERSION] { @@ -14912,7 +14912,7 @@ mod stitch_tests { /// A stream that FINs before the group its End Location bounds, with no objects or after /// an earlier group, is short before draft-22. From draft-22 the bounded group is refused /// for now, since objects past the bound may still be written. - #[moq_clock::test] + #[kio::test] async fn a_range_fetch_must_reach_its_bounded_group() { let last = SEQUENCE + 2; for version in [Version::Draft18, VERSION] { @@ -14951,7 +14951,7 @@ mod stitch_tests { ), true => { assert!(res.is_ok(), "{version} empty={empty}: {res:?}"); - let bounded = moq_clock::timeout(Duration::from_secs(1), bounded) + let bounded = kio::clock::timeout(Duration::from_secs(1), bounded) .await .expect("refused"); assert!( @@ -14987,7 +14987,7 @@ mod stitch_tests { /// A datagram group is never fetchable, so a group fetch answered with one names it /// dropped as not fetchable, caching nothing, and reads on past its payload. - #[moq_clock::test] + #[kio::test] async fn a_group_fetch_drops_a_datagram_group() { let mut run = GroupFetchRun::new(VERSION, datagram_object(SEQUENCE)).await; let (slot, fetch) = run.slot(None, None).await; @@ -15000,7 +15000,7 @@ mod stitch_tests { /// A third-party publisher may answer a range even though ours refuses it. The subscriber /// caches the supplied groups and reports the gaps between them as misses. - #[moq_clock::test] + #[kio::test] async fn a_range_fetch_caches_the_groups_with_the_groups_between_dropped() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let mut objects = group_fetch_objects(4, 0, &[b"4-0", b"4-1"]); @@ -15037,7 +15037,7 @@ mod stitch_tests { start: 0, end: None, })); - let res = moq_clock::timeout( + let res = kio::clock::timeout( Duration::from_secs(1), run.subscriber.recv_group_fetch(&mut run.stream, slot), ) @@ -15058,7 +15058,7 @@ mod stitch_tests { assert!(group.read_frame().await.unwrap().is_none(), "{version}"); } for fetched in missing { - let fetched = moq_clock::timeout(Duration::from_secs(1), fetched) + let fetched = kio::clock::timeout(Duration::from_secs(1), fetched) .await .expect("dropped"); assert!( @@ -15072,7 +15072,7 @@ mod stitch_tests { /// A fill answered with a datagram Object is refused the same way. Only the fill goes: /// the subscription keeps delivering the groups after it. - #[moq_clock::test] + #[kio::test] async fn a_datagram_fill_fails_only_the_fill() { let mut fill = Vec::new(); crate::coding::Encoder::new(&mut fill, VERSION.into()) @@ -15132,7 +15132,7 @@ mod stitch_tests { /// A group aborted under a stalled fetch stream, as by eviction, ends the run with its /// error instead of leaving the run's readers waiting on the stream. - #[moq_clock::test] + #[kio::test] async fn a_group_aborted_under_a_stalled_fetch_ends_the_run() { let mut run = GroupFetchRun::stalled(VERSION, group_fetch_objects(SEQUENCE, 0, &[b"0"])).await; let (slot, _fetch) = run.slot(None, None).await; @@ -15147,7 +15147,7 @@ mod stitch_tests { assert!(matches!(receive.await, Err(Error::Evicted))); } - #[moq_clock::test] + #[kio::test] async fn internal_group_fetch_setup_cancellation_is_cancel() { let mut run = GroupFetchRun::new(VERSION, Vec::new()).await; let slot = kio::Producer::new(GroupFetch::Pending); @@ -15268,7 +15268,7 @@ mod joining_fetch_tests { const JOINING_DRAFTS: [Version; 1] = [Version::Draft18]; async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } fn message_bytes<'m, M: Message<'m>>(id: u64, msg: &M, version: Version) -> Vec { @@ -15344,7 +15344,7 @@ mod joining_fetch_tests { kio::Pending, ), _tasks: (Tasks, TaskSet), - serving: moq_clock::sim::JoinHandle<()>, + serving: kio::clock::sim::JoinHandle<()>, } impl JoinRun { @@ -15385,7 +15385,7 @@ mod joining_fetch_tests { let request = dynamic.requested_track().await.expect("no track requested"); let mut serving_subscriber = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { serving_subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -15521,12 +15521,12 @@ mod joining_fetch_tests { } } - #[moq_clock::test] + #[kio::test] async fn revocation_cancels_a_group_fetch_before_the_subscribe_fin_is_acked() { revoked_child_fetch(false).await; } - #[moq_clock::test] + #[kio::test] async fn revocation_cancels_an_answered_fetch_before_the_subscribe_fin_is_acked() { revoked_child_fetch(true).await; } @@ -15534,7 +15534,7 @@ mod joining_fetch_tests { /// From draft 18 the joining FETCH's request stays open after FETCH_OK. Its failure while /// the head is still being written settles the fill, so a mid-group tail is not parked /// on a head that may never finish. - #[moq_clock::test] + #[kio::test] async fn a_request_failing_mid_head_settles_the_fill() { let version = Version::Draft18; let session = ScriptedSession::per_stream_reset(vec![fetch_ok(version)]); @@ -15552,7 +15552,7 @@ mod joining_fetch_tests { assert!(matches!(*fill.read(), Fill::Done), "{version}: the head is released"); } - #[moq_clock::test] + #[kio::test] async fn invalid_joining_open_is_refused() { for version in JOINING_DRAFTS { for retired in [false, true] { @@ -15580,7 +15580,7 @@ mod joining_fetch_tests { } } - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_waits_for_stream_credit() { for version in JOINING_DRAFTS { let session = ScriptedSession::new(Vec::new()).without_credit(); @@ -15599,7 +15599,7 @@ mod joining_fetch_tests { /// A committed joining FETCH the peer's send window holds back part-way is reset once /// its subscription lets go, rather than waiting for credit to finish the header. - #[moq_clock::test] + #[kio::test] async fn a_joining_fetch_stalled_on_credit_resets_when_cancelled() { for version in JOINING_DRAFTS { let session = ScriptedSession::new(Vec::new()).with_send_window(1); @@ -15623,7 +15623,7 @@ mod joining_fetch_tests { } /// Abandoning a blocked open leaves the next sequential ID available to unrelated work. - #[moq_clock::test] + #[kio::test] async fn cancelling_a_joining_fetch_open_spends_no_id() { for version in JOINING_DRAFTS { let gate = kio::Producer::new(false); @@ -15642,7 +15642,7 @@ mod joining_fetch_tests { /// Every draft-18 live join is Largest Object on the SUBSCRIBE and a relative /// joining FETCH at offset 0 that names the subscribe's request id. - #[moq_clock::test] + #[kio::test] async fn a_live_join_is_spelled_as_largest_object_plus_relative_fetch() { let largest = Some(ietf::Location { group: 4, object: 1 }); for version in JOINING_DRAFTS { @@ -15674,7 +15674,7 @@ mod joining_fetch_tests { /// A start below, at, or past the Largest group joins that group alone: a group below it /// is left to the copy's fills. - #[moq_clock::test] + #[kio::test] async fn a_join_from_any_start_fetches_only_the_largest_group() { let largest = Some(ietf::Location { group: 9, object: 0 }); for version in JOINING_DRAFTS { @@ -15701,7 +15701,7 @@ mod joining_fetch_tests { /// the Largest group and nothing more, as a failed draft-22 fill does: the fill settles, /// so a stream starting mid-group no longer waits on it, and the subscription keeps /// delivering whole groups. - #[moq_clock::test] + #[kio::test] async fn a_refused_fetch_joins_at_the_next_whole_group() { let largest = Some(ietf::Location { group: 4, object: 1 }); for version in JOINING_DRAFTS { @@ -15722,7 +15722,7 @@ mod joining_fetch_tests { /// A malformed answer to the joining FETCH is not a refusal: the peer broke the /// protocol, so the session closes. - #[moq_clock::test] + #[kio::test] async fn a_malformed_fetch_answer_closes_the_session() { let largest = Some(ietf::Location { group: 4, object: 1 }); for version in JOINING_DRAFTS { @@ -15744,7 +15744,7 @@ mod joining_fetch_tests { /// A joining FETCH is not one of the subscription's counted streams, so a clean /// PUBLISH_DONE can settle while its head is still being written. The head is then the /// whole group, as it is when it lands first, rather than cut short as on a leave. - #[moq_clock::test] + #[kio::test] async fn a_head_landing_after_a_clean_end_finishes_its_group() { let largest = Some(ietf::Location { group: 4, object: 0 }); for version in JOINING_DRAFTS { @@ -15798,7 +15798,7 @@ mod joining_fetch_tests { // The grace runs out with the head still being written, ending the subscription. // The finished copy lingers for fills while the reader holds it. while !run.subscriber.state.lock().subscribes.is_empty() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } assert!(!run.serving.is_finished(), "{version}: the finished copy lingers"); @@ -15816,7 +15816,7 @@ mod joining_fetch_tests { /// for a later reader to subscribe afresh rather than lingering as if the track ended. Its /// reader sees an error, not a clean end: the fresh copy's groups continue past this one's, /// so an end here would be one the track runs past. - #[moq_clock::test] + #[kio::test] async fn a_subscription_ended_copy_does_not_linger() { for version in JOINING_DRAFTS { let mut ok = subscribe_ok(version, None); @@ -16040,35 +16040,35 @@ mod joining_fetch_tests { assert!(subscriber.state.lock().group_fetches.is_empty(), "request retired"); } - #[moq_clock::test] + #[kio::test] async fn a_retired_group_fetch_before_fetch_ok_is_cancelled() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::Retired).await; } } - #[moq_clock::test] + #[kio::test] async fn an_abandoned_group_fetch_before_fetch_ok_is_cancelled() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::Unanswered).await; } } - #[moq_clock::test] + #[kio::test] async fn an_abandoned_group_fetch_after_fetch_ok_is_cancelled() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::Accepted).await; } } - #[moq_clock::test] + #[kio::test] async fn an_abandoned_partial_group_fetch_is_cancelled() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::Receiving).await; } } - #[moq_clock::test] + #[kio::test] async fn a_complete_group_fetch_is_cached_when_the_reader_leaves() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::Complete).await; @@ -16076,14 +16076,14 @@ mod joining_fetch_tests { } /// A request reset after the group is written must not abort the cached group. - #[moq_clock::test] + #[kio::test] async fn a_complete_group_fetch_survives_a_request_reset() { for version in JOINING_DRAFTS { abandon_group_fetch(version, FetchStage::CompleteReset).await; } } - #[moq_clock::test] + #[kio::test] async fn a_claimed_fetch_waits_only_while_wanted() { for version in JOINING_DRAFTS { for stage in [FetchStage::Credit, FetchStage::CreditRetired, FetchStage::CreditGranted] { @@ -16095,7 +16095,7 @@ mod joining_fetch_tests { /// A publisher that resets the request after FETCH_OK owes no fetch stream, so the /// group it accepted is aborted instead of left open for every reader to wait on. /// Without that, `run_group_fetch` never returns. - #[moq_clock::test] + #[kio::test] async fn a_group_fetch_reset_after_fetch_ok_aborts_the_group() { const VERSION: Version = Version::Draft18; const GROUP: u64 = 4; @@ -16150,7 +16150,7 @@ mod joining_fetch_tests { /// From draft-22 an End Location outside the FETCH's range is malformed: /// the session closes with PROTOCOL_VIOLATION rather than reading it as an empty answer. - #[moq_clock::test] + #[kio::test] async fn a_draft22_end_location_outside_the_range_closes_the_session() { const GROUP: u64 = 4; const START: u64 = 3; @@ -16233,7 +16233,7 @@ mod joining_fetch_tests { /// A cache miss for a group's tail asks upstream from the frame the reader wants and /// numbers what arrives from there, so a publisher that evicted the prefix can answer. - #[moq_clock::test] + #[kio::test] async fn a_group_fetch_asks_from_the_wanted_frame() { for version in JOINING_DRAFTS.into_iter().chain([Version::Draft22]) { for ended in [false, true] { @@ -16243,7 +16243,7 @@ mod joining_fetch_tests { } /// Legacy moxygen/cache answers one group past the requested group remain readable. - #[moq_clock::test] + #[kio::test] async fn a_legacy_group_fetch_answer_still_covers_the_requested_group() { for version in JOINING_DRAFTS { for ended in [false, true] { @@ -16340,7 +16340,7 @@ mod joining_fetch_tests { assert!(futures::poll!(fetch.as_mut()).is_pending()); let request = dynamic.requested_fill().await.expect("no group requested"); - let serving = moq_clock::sim::spawn(subscriber.clone().run_group_fetch( + let serving = kio::clock::sim::spawn(subscriber.clone().run_group_fetch( Path::from_static("broadcast"), "video".into(), request, @@ -16413,7 +16413,7 @@ mod new_group_tests { use crate::{model::ProduceTest, transport::memory}; async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } const VERSION: Version = Version::Draft22; @@ -16424,7 +16424,7 @@ mod new_group_tests { track: track::Consumer, probe: Subscriber, peer: memory::Session, - serving: moq_clock::sim::JoinHandle<()>, + serving: kio::clock::sim::JoinHandle<()>, /// Landed groups stay open, as a live publisher's would. landed: Vec, _broadcast: crate::broadcast::Producer, @@ -16454,7 +16454,7 @@ mod new_group_tests { let first = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); let probe = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -16476,7 +16476,7 @@ mod new_group_tests { let id = stream.reader.varint().await.unwrap(); (id, stream.reader.decode::().await.unwrap()) }; - moq_clock::timeout(Duration::from_secs(1), read) + kio::clock::timeout(Duration::from_secs(1), read) .await .expect("the relay sent nothing") } @@ -16568,7 +16568,7 @@ mod new_group_tests { /// A copy with nothing cached has no group to judge a join by, so its SUBSCRIBE asks for /// none. - #[moq_clock::test] + #[kio::test] async fn a_first_subscribe_asks_for_no_group() { let (mut relay, _first) = relay().await; let (_stream, sent) = relay.accept().await; @@ -16578,7 +16578,7 @@ mod new_group_tests { /// A join over the ratio goes upstream in a REQUEST_UPDATE for the group past the /// newest. Joins until that group lands ask for the same one and go no further. - #[moq_clock::test] + #[kio::test] async fn a_join_over_the_ratio_requests_a_group() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16600,7 +16600,7 @@ mod new_group_tests { } /// A join under the ratio reads the current group and asks for nothing. - #[moq_clock::test] + #[kio::test] async fn a_join_under_the_ratio_asks_nothing() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16613,7 +16613,7 @@ mod new_group_tests { } /// One REQUEST_UPDATE is in flight at a time; a join meanwhile goes up once it is answered. - #[moq_clock::test] + #[kio::test] async fn a_join_behind_an_unanswered_update_waits() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16635,7 +16635,7 @@ mod new_group_tests { /// A refused update ends the subscription, so nothing more goes up while PUBLISH_DONE /// is on its way, even for a join that waited behind it. - #[moq_clock::test] + #[kio::test] async fn a_refused_update_sends_no_more() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16662,7 +16662,7 @@ mod new_group_tests { /// A group the publisher already has is on its way, so a join asking for it goes no /// further. - #[moq_clock::test] + #[kio::test] async fn a_group_upstream_has_is_not_requested() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16676,7 +16676,7 @@ mod new_group_tests { /// A publisher that did not advertise DYNAMIC_GROUPS refreshes on no join, so it never /// hears a REQUEST_UPDATE carrying one. - #[moq_clock::test] + #[kio::test] async fn a_publisher_without_dynamic_groups_hears_no_updates() { let (mut relay, _first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16690,7 +16690,7 @@ mod new_group_tests { /// A group still wanted when the copy goes idle rides the SUBSCRIBE that resumes it, and /// is outstanding from there. - #[moq_clock::test] + #[kio::test] async fn a_resumed_copy_carries_its_request() { let (mut relay, first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16714,7 +16714,7 @@ mod new_group_tests { /// An identified fill keeps ownership until its head is handed off. A fill with no /// header can instead be superseded, since a reset may have discarded that header. - #[moq_clock::test] + #[kio::test] async fn only_an_identified_fill_holds_back_a_widening() { let (mut relay, mut first) = relay().await; let (mut stream, _) = relay.accept().await; @@ -16755,7 +16755,7 @@ mod new_group_tests { /// Delayed headers, including one already waiting for REQUEST_OK, belong to the /// request they answer and cannot consume a later widening's fill. - #[moq_clock::test] + #[kio::test] async fn superseded_fill_headers_cannot_claim_the_new_request() { use crate::{coding::Encode, lite::test_transport::ScriptedSession}; @@ -16839,7 +16839,7 @@ mod new_group_tests { /// A widening update replaces a fill that failed to head its group, while that group's /// mid-group tail can still be in flight. The tail stays headless both to a stream /// already opening on the old fill and to one opening after either replacement. - #[moq_clock::test] + #[kio::test] async fn a_replaced_failed_fill_keeps_its_group_headless() { use crate::{coding::Encode, lite::test_transport::ScriptedSession}; @@ -16954,7 +16954,7 @@ mod track_property_tests { let subscribing = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); let probe = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -16984,10 +16984,10 @@ mod track_property_tests { frame.extend(body); stream.writer.write_all(&mut bytes::Bytes::from(frame)).await.unwrap(); - let subscribed = moq_clock::timeout(Duration::from_secs(1), subscribing) + let subscribed = kio::clock::timeout(Duration::from_secs(1), subscribing) .await .expect("the subscription was never answered"); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; serving.abort(); (subscribed, probe) } @@ -17011,7 +17011,7 @@ mod track_property_tests { /// An even property the draft defines but moq-net does not implement /// (OBJECT_DELIVERY_TIMEOUT) and an odd one from the application range reach the track /// unchanged, for the relay's own answers downstream to forward. - #[moq_clock::test] + #[kio::test] async fn unknown_properties_reach_the_track() { for version in VERSIONS { let unknown = vec![ @@ -17038,7 +17038,7 @@ mod track_property_tests { /// A Mandatory Track Property we do not understand, mutable or sealed, refuses the /// track with UNSUPPORTED_EXTENSION instead of forwarding it. - #[moq_clock::test] + #[kio::test] async fn a_mandatory_property_refuses_the_track() { for version in VERSIONS { let mandatory = Property { @@ -17066,7 +17066,7 @@ mod track_property_tests { /// A sealed DEFAULT_PUBLISHER_GROUP_ORDER is advisory: the relay accepts the track, serves /// its own order, and keeps the sealed block to forward unchanged. - #[moq_clock::test] + #[kio::test] async fn a_sealed_group_order_the_relay_does_not_serve_is_accepted() { for version in VERSIONS { for order in [2, 1] { @@ -17097,7 +17097,7 @@ mod track_property_tests { /// A TIMESCALE keeps the publisher's units, mutable or sealed: a sealed one travels /// downstream unchanged, and a mutable one matches a copy that arrived over another route. - #[moq_clock::test] + #[kio::test] async fn a_timescale_keeps_its_units() { for version in VERSIONS { let timescale = Property { @@ -17124,7 +17124,7 @@ mod full_track_name_tests { /// A Full Track Name too long for the wire fails only its own subscription, and the /// session carries the next one. - #[moq_clock::test] + #[kio::test] async fn an_unencodable_track_name_fails_only_its_subscription() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let (session, peer) = memory::pair(memory::Config::default()); @@ -17151,7 +17151,7 @@ mod full_track_name_tests { let mut subscribing = std::pin::pin!(track.subscribe(None)); let request = dynamic.requested_track().await.expect("no track requested"); let mut subscriber = subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("broadcast"), dynamic, None, request) .await; @@ -17168,7 +17168,7 @@ mod full_track_name_tests { }; assert_eq!(id, ietf::Subscribe::ID, "{version}"); } else { - let refused = moq_clock::timeout(Duration::from_secs(1), &mut subscribing) + let refused = kio::clock::timeout(Duration::from_secs(1), &mut subscribing) .await .expect("the subscription was never refused"); assert!( diff --git a/rs/moq-net/src/ietf/subscriber/tracks.rs b/rs/moq-net/src/ietf/subscriber/tracks.rs index 6634c4f19be..e6affb5d75b 100644 --- a/rs/moq-net/src/ietf/subscriber/tracks.rs +++ b/rs/moq-net/src/ietf/subscriber/tracks.rs @@ -1272,11 +1272,11 @@ mod tests { listening: Listening, version: Version, _broadcast: crate::broadcast::Producer, - _driver: moq_clock::sim::JoinHandle<()>, + _driver: kio::clock::sim::JoinHandle<()>, } async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } fn harness(version: Version) -> Harness { @@ -1286,7 +1286,7 @@ mod tests { fn harness_with(version: Version, config: memory::Config) -> Harness { let (session, peer) = memory::pair(config); let (tasks, mut task_set) = TaskSet::new(); - let driver = moq_clock::sim::spawn(async move { kio::wait(|waiter| task_set.poll(waiter)).await }); + let driver = kio::clock::sim::spawn(async move { kio::wait(|waiter| task_set.poll(waiter)).await }); let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), @@ -1320,7 +1320,7 @@ mod tests { let id = stream.reader.varint().await.unwrap(); (id, stream.reader.decode::().await.unwrap()) }; - moq_clock::timeout(TIMEOUT, read) + kio::clock::timeout(TIMEOUT, read) .await .expect("the subscriber sent nothing") } @@ -1347,7 +1347,7 @@ mod tests { impl Harness { /// Accept the SUBSCRIBE_TRACKS and establish it. async fn establish(&mut self) -> PeerStream { - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(self.peer.clone()), self.version), ) @@ -1385,14 +1385,14 @@ mod tests { ) -> ( crate::track::Consumer, kio::Pending, - moq_clock::sim::JoinHandle<()>, + kio::clock::sim::JoinHandle<()>, ) { let mut dynamic = self._broadcast.requests(); let track = self._broadcast.consume().track(name).unwrap(); let reader = track.subscribe(None); let request = dynamic.requested_track().await.expect("no track requested"); let mut subscriber = self.subscriber.clone(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { subscriber .run_subscribe(Path::from_static("bcast"), dynamic, None, request) .await; @@ -1407,7 +1407,7 @@ mod tests { ) -> ( crate::track::Consumer, crate::track::Subscriber, - moq_clock::sim::JoinHandle<()>, + kio::clock::sim::JoinHandle<()>, ) { let (track, reader, serving) = self.read_track("video").await; let (id, body) = read(video).await; @@ -1419,7 +1419,7 @@ mod tests { largest: None, }; write(video, ietf::RequestOk::ID, &ok).await; - let reader = moq_clock::timeout(TIMEOUT, reader) + let reader = kio::clock::timeout(TIMEOUT, reader) .await .expect("never accepted") .unwrap(); @@ -1430,7 +1430,7 @@ mod tests { async fn resume_and_pause( &mut self, video: &mut PeerStream, - ) -> (crate::track::Consumer, moq_clock::sim::JoinHandle<()>) { + ) -> (crate::track::Consumer, kio::clock::sim::JoinHandle<()>) { let (track, reader, serving) = self.resume(video).await; drop(reader); let (id, body) = read(video).await; @@ -1456,7 +1456,7 @@ mod tests { let body: ietf::Body = ours.reader.decode().await.unwrap(); let mut subscriber = self.subscriber.clone(); let version = self.version; - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let msg = body.message::(version).unwrap().into_owned(); let _ = subscriber.serve_publish(ours, msg).await; }); @@ -1468,7 +1468,7 @@ mod tests { /// Readers coming and going while the peer withholds credit on a held track never pile /// updates up behind it: the held subscription is handed over only once its pause is out, /// and a reader leaving meanwhile stops waiting for it. - #[moq_clock::test] + #[kio::test] async fn churn_under_withheld_credit_buffers_one_resume_and_pause() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { // One message in flight per stream, so a peer that stops reading withholds credit. @@ -1485,14 +1485,14 @@ mod tests { settle().await; drop(reader); drop(track); - moq_clock::timeout(TIMEOUT, serving) + kio::clock::timeout(TIMEOUT, serving) .await .unwrap_or_else(|_| panic!("{version}: the abandoned resume stayed alive")) .unwrap(); } let mut updates = Vec::new(); - while let Ok(Ok(id)) = moq_clock::timeout(TIMEOUT, video.reader.varint()).await { + while let Ok(Ok(id)) = kio::clock::timeout(TIMEOUT, video.reader.varint()).await { let body: ietf::Body = video.reader.decode().await.unwrap(); assert_eq!(id, ietf::SubscribeUpdate::ID, "{version}"); updates.push(body.message::(version).unwrap().forward); @@ -1555,7 +1555,7 @@ mod tests { /// A PUBLISH no listing asked for stays refused, and one for a track already held is /// redundant: DUPLICATE_SUBSCRIPTION on draft-18, which allows one subscription per /// track, and UNINTERESTED after. - #[moq_clock::test] + #[kio::test] async fn an_unasked_or_redundant_publish_is_refused() { for (version, duplicate) in [(Version::Draft18, 0x19), (Version::Draft22, 0x20)] { let mut h = harness(version); @@ -1569,7 +1569,7 @@ mod tests { } /// A PUBLISH_DONE with TRACK_ENDED unlists the track as finished, and the listing stands. - #[moq_clock::test] + #[kio::test] async fn a_track_ended_publish_finishes_the_track() { let version = Version::Draft22; let mut h = harness(version); @@ -1589,7 +1589,7 @@ mod tests { /// Any other PUBLISH_DONE, INTERNAL_ERROR included, fails the listing rather than hide a /// track that may be live. - #[moq_clock::test] + #[kio::test] async fn another_publish_done_fails_the_listing() { let version = Version::Draft22; for (status, expected) in [ @@ -1616,7 +1616,7 @@ mod tests { /// A resumed listed track ending any way but TRACK_ENDED fails the listing, even a /// clean SUBSCRIPTION_ENDED (draft 18), which says nothing of the track itself. - #[moq_clock::test] + #[kio::test] async fn a_resumed_track_ending_otherwise_fails_the_listing() { let version = Version::Draft18; let mut h = harness(version); @@ -1635,12 +1635,12 @@ mod tests { }; write(&mut video, ietf::PublishDone::ID, &done).await; // The subscription waits out its data streams before it ends. - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; assert!(h.listening.poll_failed(&kio::Waiter::noop()).is_ready()); } /// A skipped track is listed through a paused SUBSCRIBE of ours, once it answers. - #[moq_clock::test] + #[kio::test] async fn a_skipped_track_lists_once_its_paused_subscribe_answers() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let mut h = harness(version); @@ -1652,7 +1652,7 @@ mod tests { write(&mut listing, ietf::PublishSkipped::ID, &skipped).await; assert_eq!(event(&mut h.tracks), None, "{version}: listed before it answered"); - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(h.peer.clone()), version), ) @@ -1684,7 +1684,7 @@ mod tests { } /// A refused paused SUBSCRIBE fails the listing. - #[moq_clock::test] + #[kio::test] async fn a_refused_paused_subscribe_fails_the_listing() { let version = Version::Draft22; let mut h = harness(version); @@ -1694,7 +1694,7 @@ mod tests { track_name: "audio".into(), }; write(&mut listing, ietf::PublishSkipped::ID, &skipped).await; - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(h.peer.clone()), version), ) @@ -1716,7 +1716,7 @@ mod tests { /// A listed PUBLISH whose properties we cannot take fails the listing: the peer sends /// nothing else for that track, so a listing left standing would silently miss it. - #[moq_clock::test] + #[kio::test] async fn an_unsupported_publish_fails_the_listing() { let version = Version::Draft22; let mut h = harness(version); @@ -1739,7 +1739,7 @@ mod tests { /// On draft-22 a PUBLISH that forwards contradicts the paused listing it answers, and /// nothing we send can pause it: it is refused and the listing fails, rather than have its /// objects refused unseen. On draft-18 our PUBLISH_OK pauses it. - #[moq_clock::test] + #[kio::test] async fn a_forwarding_publish_fails_the_listing_on_draft_22() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let mut h = harness(version); @@ -1769,7 +1769,7 @@ mod tests { /// A listed track that finishes before its resume is answered goes back to lingering, and /// its waiting reader SUBSCRIBEs: the idle copy cannot place the end, which the SUBSCRIBE /// learns, rather than abort a clean finish. - #[moq_clock::test] + #[kio::test] async fn a_track_ending_before_its_resume_resubscribes() { let version = Version::Draft22; let mut h = harness(version); @@ -1795,7 +1795,7 @@ mod tests { "TRACK_ENDED failed the listing" ); - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(h.peer.clone()), version), ) @@ -1808,7 +1808,7 @@ mod tests { /// A paused track's upstream failing aborts the copy a reader left lingering, rather /// than leave it open with nothing upstream. - #[moq_clock::test] + #[kio::test] async fn a_paused_track_failing_aborts_its_lingering_copy() { let version = Version::Draft22; let mut h = harness(version); @@ -1829,7 +1829,7 @@ mod tests { /// The answer a pause owes is decoded like any other, so a malformed one closes the /// session rather than count as an answer. - #[moq_clock::test] + #[kio::test] async fn a_malformed_pause_answer_closes_the_session() { let version = Version::Draft22; let mut h = harness(version); @@ -1846,19 +1846,19 @@ mod tests { .unwrap(); let peer = h.peer.clone(); let closed = kio::wait(move |waiter| crate::transport::poll::Session::poll_closed(&peer, waiter)); - moq_clock::timeout(TIMEOUT, closed) + kio::clock::timeout(TIMEOUT, closed) .await .expect("the session stayed up"); } /// A peer that refuses SUBSCRIBE_TRACKS, resets it, or never answers it fails at most /// that listing: a plain SUBSCRIBE still goes out and is accepted on the session. - #[moq_clock::test] + #[kio::test] async fn a_peer_not_answering_the_listing_still_serves_subscribe() { let version = Version::Draft22; for case in ["refused", "reset", "silent"] { let mut h = harness(version); - let mut listing = moq_clock::timeout( + let mut listing = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(h.peer.clone()), version), ) @@ -1896,7 +1896,7 @@ mod tests { } let (_track, reader, _serving) = h.read_track("video").await; - let mut stream = moq_clock::timeout( + let mut stream = kio::clock::timeout( TIMEOUT, Stream::accept(&mut crate::driver::Transport::new(h.peer.clone()), version), ) @@ -1913,7 +1913,7 @@ mod tests { properties: ietf::Properties::default(), }; write(&mut stream, ietf::SubscribeOk::ID, &ok).await; - moq_clock::timeout(TIMEOUT, reader) + kio::clock::timeout(TIMEOUT, reader) .await .expect("never accepted") .unwrap_or_else(|err| panic!("{case}: {err}")); @@ -1922,7 +1922,7 @@ mod tests { /// Dropping the listing cancels its SUBSCRIBE_TRACKS: FIN on draft-18, RESET_STREAM on /// draft-22, where a FIN is no cancel. The held PUBLISHes are let go with it. - #[moq_clock::test] + #[kio::test] async fn dropping_the_listing_cancels_it() { let version = Version::Draft18; let mut h = harness(version); @@ -1930,14 +1930,14 @@ mod tests { let mut video = h.publish("video", 1).await; drop(h.listening); settle().await; - let ended = moq_clock::timeout(TIMEOUT, listing.reader.varint_maybe()) + let ended = kio::clock::timeout(TIMEOUT, listing.reader.varint_maybe()) .await .expect("the listing stayed open"); match version { Version::Draft18 => assert!(matches!(ended, Ok(None)), "{version}: {ended:?}"), _ => assert!(ended.is_err(), "{version}: {ended:?}"), } - let ended = moq_clock::timeout(TIMEOUT, video.reader.varint_maybe()) + let ended = kio::clock::timeout(TIMEOUT, video.reader.varint_maybe()) .await .expect("the PUBLISH stayed held"); assert!(!matches!(ended, Ok(Some(_))), "{version}: {ended:?}"); diff --git a/rs/moq-net/src/lite/ietf.rs b/rs/moq-net/src/lite/ietf.rs index b59f5d376de..c2a9c3b2c91 100644 --- a/rs/moq-net/src/lite/ietf.rs +++ b/rs/moq-net/src/lite/ietf.rs @@ -979,13 +979,13 @@ pub(crate) async fn test_hop( .with_publisher(upstream.consume()); let (client, server) = futures::join!( async { - let (session, driver) = dial.connect(moq_clock::now(), client).await.unwrap(); - drop(moq_clock::sim::spawn(crate::time::run(driver))); + let (session, driver) = dial.connect(kio::clock::now(), client).await.unwrap(); + drop(kio::clock::sim::spawn(crate::time::run(driver))); session }, async { - let (session, driver) = serve.accept(moq_clock::now(), server).await.unwrap(); - drop(moq_clock::sim::spawn(crate::time::run(driver))); + let (session, driver) = serve.accept(kio::clock::now(), server).await.unwrap(); + drop(kio::clock::sim::spawn(crate::time::run(driver))); session }, ); @@ -1064,19 +1064,19 @@ mod hop_tests { } async fn next(group: &mut group::Consumer) -> Option { - moq_clock::timeout(TIMEOUT, kio::wait(|waiter| group.poll_read_object(waiter))) + kio::clock::timeout(TIMEOUT, kio::wait(|waiter| group.poll_read_object(waiter))) .await .expect("no frame") .unwrap() } async fn subscribe(origin: &crate::origin::Producer) -> (track::Consumer, track::Subscriber) { - let broadcast = moq_clock::timeout(TIMEOUT, origin.consume().request("room", None)) + let broadcast = kio::clock::timeout(TIMEOUT, origin.consume().request("room", None)) .await .expect("no broadcast") .unwrap(); let track = broadcast.track("video").unwrap(); - let subscriber = moq_clock::timeout(TIMEOUT, track.subscribe(None)) + let subscriber = kio::clock::timeout(TIMEOUT, track.subscribe(None)) .await .expect("no subscription") .unwrap(); @@ -1084,7 +1084,7 @@ mod hop_tests { } async fn recv(subscriber: &mut track::Subscriber) -> group::Consumer { - moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .expect("no group") .unwrap() @@ -1095,7 +1095,7 @@ mod hop_tests { /// Object IDs, properties, and END_OF_GROUP position, and its track's properties. /// A side that does not offer the extension gets the plain frames alone. The track info /// moq-transport egress restates as Track Properties crosses either way. - #[moq_clock::test] + #[kio::test] async fn relayed_state_crosses_while_the_group_is_open() { for offer in [[true, true], [true, false], [false, true]] { let negotiated = offer == [true, true]; @@ -1174,7 +1174,7 @@ mod hop_tests { let frame = next(&mut received).await.unwrap(); assert_eq!(&frame.payload.contiguous(0)[..], b"b"); assert!(next(&mut received).await.is_none()); - let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); + let info = kio::clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert_eq!( (info.max_age, info.timescale, info.priority, info.refresh), ( @@ -1216,11 +1216,11 @@ mod hop_tests { let _track = broadcast.create_track("video", info).unwrap(); let (downstream, _sessions) = test_hop(&upstream, "room", [true, true]).await; - let broadcast = moq_clock::timeout(TIMEOUT, downstream.consume().request("room", None)) + let broadcast = kio::clock::timeout(TIMEOUT, downstream.consume().request("room", None)) .await .expect("no broadcast") .unwrap(); - moq_clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) + kio::clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) .await .expect("no answer") .map(drop) @@ -1229,7 +1229,7 @@ mod hop_tests { /// A track with a Mandatory Track Property, mutable or sealed, is refused across the hop /// as moq-transport ingress refuses it: one we do not understand is neither processed /// nor forwarded. - #[moq_clock::test] + #[kio::test] async fn mandatory_track_properties_are_refused() { let mut sealed = Vec::new(); let e = &mut Encoder::new(&mut sealed, crate::ietf::Version::Draft22.into()); @@ -1252,7 +1252,7 @@ mod hop_tests { /// A sealed TIMESCALE that contradicts TRACK_INFO is refused across the hop: the relay /// times frames by TRACK_INFO, while egress would forward the sealed one. - #[moq_clock::test] + #[kio::test] async fn a_sealed_property_must_match_track_info() { for (timescale, ok) in [(1000, true), (900, false), (0, false)] { let mut sealed = Vec::new(); @@ -1273,7 +1273,7 @@ mod hop_tests { /// A sealed DYNAMIC_GROUPS must match the refresh TRACK_INFO carries across the hop, /// which moq-transport egress restates as DYNAMIC_GROUPS. - #[moq_clock::test] + #[kio::test] async fn a_sealed_dynamic_groups_must_match_track_info() { for (refresh, value, ok) in [ (Some(0), 1, true), @@ -1304,7 +1304,7 @@ mod hop_tests { /// A relay forwards only as many Track Properties as leave room for the ones it /// restates from TRACK_INFO, so one more is refused across the hop. - #[moq_clock::test] + #[kio::test] async fn forwarded_track_properties_leave_room_for_track_info() { let max = crate::ietf::properties::MAX_FORWARDED; for (count, ok) in [(max, true), (max + 1, false)] { @@ -1318,7 +1318,7 @@ mod hop_tests { /// Groups and datagrams from a moq-lite publisher cross a negotiated hop as plain as /// they left: no relay state appears on the way, nor a moq-transport draft. - #[moq_clock::test] + #[kio::test] async fn plain_media_crosses_unchanged() { let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); let broadcast = upstream.publish("room", crate::origin::Route::default()).unwrap(); @@ -1327,7 +1327,7 @@ mod hop_tests { .unwrap(); let (downstream, sessions) = test_hop(&upstream, "room", [true, true]).await; let (copy, mut subscriber) = subscribe(&downstream).await; - let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); + let info = kio::clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert!(info.properties.is_none()); let mut group = track.append_group().unwrap(); @@ -1351,7 +1351,7 @@ mod hop_tests { assert!(received.end_object().is_none()); track.insert_datagram(7, ts(9), b"datagram".to_vec()).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, kio::wait(|waiter| subscriber.poll_recv_wire_datagram(waiter))) + let datagram = kio::clock::timeout(TIMEOUT, kio::wait(|waiter| subscriber.poll_recv_wire_datagram(waiter))) .await .expect("no datagram") .unwrap() @@ -1364,7 +1364,7 @@ mod hop_tests { /// Only a negotiated hop can preserve several datagram Object IDs. A late or lost /// object 0 never lets another object's payload pose as the whole group. - #[moq_clock::test] + #[kio::test] async fn datagram_objects_cross_only_an_identifying_hop() { for offer in [[false, false], [false, true], [true, false], [true, true]] { for objects in [&[0, 1, 2][..], &[1, 2, 0], &[1, 2]] { @@ -1441,7 +1441,7 @@ mod hop_tests { /// Provenance keeps IETF times unchecked after a hop, while a peer declining the /// extension gets no timeline. SUBSCRIBE, FETCH, and datagrams must agree with TRACK_INFO, /// while a listing stays untimed. - #[moq_clock::test] + #[kio::test] async fn ietf_timestamps_keep_their_provenance_across_a_hop() { for offer in [[true, true], [true, false], [false, true]] { let negotiated = offer == [true, true]; @@ -1461,7 +1461,7 @@ mod hop_tests { // negotiated: a relay re-listing it would otherwise advertise it as native lite. let mut tracks = broadcast.tracks().unwrap(); let listed = loop { - match moq_clock::timeout(TIMEOUT, tracks.next()).await.unwrap().unwrap() { + match kio::clock::timeout(TIMEOUT, tracks.next()).await.unwrap().unwrap() { Some(crate::broadcast::TracksEvent::Added { name, info }) if &*name == "video" => break info, Some(_) => continue, None => panic!("listing ended before the track"), @@ -1469,7 +1469,7 @@ mod hop_tests { }; assert_eq!((listed.timescale, listed.ietf()), (None, None), "{offer:?}"); let copy = broadcast.track("video").unwrap(); - let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); + let info = kio::clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert_eq!(info.timescale, negotiated.then_some(Timescale::MILLI), "{offer:?}"); assert_eq!( info.ietf(), @@ -1478,14 +1478,14 @@ mod hop_tests { ); // Before any subscription, this must fetch the head over the hop, rather // than reading an already subscribed copy's cache. - let mut fetched = moq_clock::timeout(TIMEOUT, copy.fetch_group(0, None)) + let mut fetched = kio::clock::timeout(TIMEOUT, copy.fetch_group(0, None)) .await .unwrap() .unwrap(); assert_eq!(next(&mut fetched).await.unwrap().timestamp, negotiated.then(|| ts(100))); assert!(next(&mut fetched).await.is_none()); let mut subscriber = - moq_clock::timeout(TIMEOUT, copy.subscribe(track::Subscription::default().with_start(1))) + kio::clock::timeout(TIMEOUT, copy.subscribe(track::Subscription::default().with_start(1))) .await .unwrap() .unwrap(); @@ -1501,7 +1501,7 @@ mod hop_tests { assert_eq!(&frame.payload.contiguous(0)[..], b"frame"); assert!(next(&mut received).await.is_none()); track.insert_datagram(2, ts(25), b"datagram".to_vec()).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, kio::wait(|waiter| subscriber.poll_recv_wire_datagram(waiter))) + let datagram = kio::clock::timeout(TIMEOUT, kio::wait(|waiter| subscriber.poll_recv_wire_datagram(waiter))) .await .unwrap() .unwrap() @@ -1514,7 +1514,7 @@ mod hop_tests { /// A compressed track crosses a negotiated hop as stored: each frame's Inflated Size /// follows its Object Record, and a datagram's follows its Datagram State. - #[moq_clock::test] + #[kio::test] async fn compressed_media_crosses_a_negotiated_hop() { let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); let broadcast = upstream.publish("room", crate::origin::Route::default()).unwrap(); @@ -1543,7 +1543,7 @@ mod hop_tests { assert!(next(&mut received).await.is_none()); track.insert_datagram(7, ts(9), payload(3)).unwrap(); - let datagram = moq_clock::timeout( + let datagram = kio::clock::timeout( TIMEOUT, kio::wait(|waiter| subscriber.poll_recv_stored_datagram(waiter)), ) diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 2522df0b4d5..bc787c94773 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -2511,7 +2511,7 @@ mod test { /// An unfloored join adopts the first served group: the cursor rises to it, so a /// group created below it is not served. An explicit floor does not; see /// [`explicit_floor_delivers_a_late_lower_group`]. - #[moq_clock::test] + #[kio::test] async fn start_floor_suppresses_late_lower_arrivals() { use futures::FutureExt; @@ -2548,7 +2548,7 @@ mod test { /// The explicit-floor twin of [`start_floor_suppresses_late_lower_arrivals`]. /// The subscription named group 0, so group 5 is still inside the floor when /// it is created after group 7. - #[moq_clock::test] + #[kio::test] async fn explicit_floor_delivers_a_late_lower_group() { let mut producer = track_producer("test"); let mut subscriber = producer.subscribe( @@ -2578,7 +2578,7 @@ mod test { } } - #[moq_clock::test] + #[kio::test] async fn recv_next_drains_datagram_before_finished() { let mut producer = track_producer("test"); let mut subscriber = producer.subscribe(None); @@ -2599,7 +2599,7 @@ mod test { } } - #[moq_clock::test] + #[kio::test] async fn recv_next_reports_future_boundary_before_finished() { let mut producer = track_producer("test"); let mut subscriber = producer.subscribe(None); @@ -2644,7 +2644,7 @@ mod test { /// Without the end error on the wire, an errored end is not declared early: a clean /// boundary could let the subscriber settle before the reset at the end arrives. - #[moq_clock::test] + #[kio::test] async fn recv_next_withholds_an_errored_boundary_without_the_end_error() { use futures::FutureExt; @@ -2676,7 +2676,7 @@ mod test { /// A relay can ingest back-to-back groups micro-reordered (the upstream leg /// sends newest-first). The older group is cached and in demand, so serving /// must still deliver it; a sequence cursor would skip it permanently. - #[moq_clock::test] + #[kio::test] async fn recv_next_serves_late_arrival_after_newer_group() { use futures::FutureExt; @@ -3026,13 +3026,13 @@ mod announce_test { /// The initial announcement; drop to retract, update to restart. announcement: crate::model::AnnounceProducer, wire: Wire, - task: moq_clock::sim::JoinHandle>, + task: kio::clock::sim::JoinHandle>, } impl Harness { /// Assert the loop is quiet *and* still alive. A panicked announce task /// also writes nothing, so silence alone would pass for the wrong reason - /// (`moq_clock::sim::spawn` parks the panic in the handle until it's joined). + /// (`kio::clock::sim::spawn` parks the panic in the handle until it's joined). fn assert_idle(&self) { self.wire.assert_quiet(); assert!(!self.task.is_finished(), "the announce loop ended unexpectedly"); @@ -3040,7 +3040,7 @@ mod announce_test { } async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } /// Announce one route with cost 7 and run the announce loop against it. @@ -3055,7 +3055,7 @@ mod announce_test { /// A relay answers with what it holds now: an upstream still delivering its own /// initial set never delays the ANNOUNCE_OK, so a peer syncs with this relay. - #[moq_clock::test] + #[kio::test] async fn a_silent_upstream_never_delays_the_answer() { let origin = Hop::new(1).unwrap().produce(); let _route = origin.announce("cam", crate::origin::Route::default()).unwrap(); @@ -3070,7 +3070,7 @@ mod announce_test { writer: Writer::new(crate::transport::boxed::SendStream::new(SinkSend::new(log)), VERSION), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), VERSION), }; - let _task = moq_clock::sim::spawn(async move { + let _task = kio::clock::sim::spawn(async move { let mut announced = consumer.announced(); let self_origin = consumer.hop(); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, VERSION, None).await @@ -3103,7 +3103,7 @@ mod announce_test { writer: Writer::new(crate::transport::boxed::SendStream::new(SinkSend::new(log)), version), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), version), }; - let task = moq_clock::sim::spawn(async move { + let task = kio::clock::sim::spawn(async move { let mut announced = consumer.announced(); let self_origin = consumer.hop(); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, version, auth).await @@ -3143,7 +3143,7 @@ mod announce_test { /// A live announce goes out as an Active with a fresh id; its retraction /// references the id. - #[moq_clock::test] + #[kio::test] async fn announce_and_retract() { let mut h = harness().await; @@ -3168,14 +3168,14 @@ mod announce_test { } /// A metadata update restarts the advertisement in place, keeping its id. - #[moq_clock::test] + #[kio::test] async fn update_restarts_in_place() { let mut h = harness().await; h.announcement .update(crate::origin::Route::default().with_hops(pub_hops()).with_cost(3)) .unwrap(); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; match h.wire.take_announces().as_slice() { [lite::AnnounceBroadcast::Update { id: 0, hops, cost }] => { @@ -3188,7 +3188,7 @@ mod announce_test { } /// An identical update never reaches the wire: the origin coalesces it away. - #[moq_clock::test] + #[kio::test] async fn identical_update_is_quiet() { let h = harness().await; h.announcement @@ -3202,14 +3202,14 @@ mod announce_test { /// cost) and without an epoch is another source, in either direction: an /// ANNOUNCE_RESTART on lite-07, which may carry an epoch, and an end and a fresh /// start before it. - #[moq_clock::test] + #[kio::test] async fn source_flip_restarts() { for version in [Version::Lite06, Version::Lite07] { let mut h = harness_on(version).await; let route = crate::origin::Route::default().with_hops(pub_hops()).with_cost(7); let newer = h.origin.announce("cam", route.clone()).unwrap(); // A restart waits out the update hold like an update. - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; let restarted = |msgs: Vec| match (version, msgs.as_slice()) { ( @@ -3239,7 +3239,7 @@ mod announce_test { restarted(h.wire.take_announces()); drop(newer); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; restarted(h.wire.take_announces()); h.assert_idle(); @@ -3247,7 +3247,7 @@ mod announce_test { } /// A newer epoch restarts the advertisement, carrying the epoch on lite-07. - #[moq_clock::test] + #[kio::test] async fn a_newer_epoch_restarts_with_it() { let mut h = harness_on(Version::Lite07).await; let epoch = crate::Epoch::mint(); @@ -3261,7 +3261,7 @@ mod announce_test { .with_cost(7), ) .unwrap(); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; match h.wire.take_announces().as_slice() { [ @@ -3279,7 +3279,7 @@ mod announce_test { /// A grant that grows while a new instance replaces an advertised one still restarts it, /// whether the instance carries a newer epoch or is an anonymous source: the regrant takes /// in what the old cursor had pending rather than dropping it. - #[moq_clock::test] + #[kio::test] async fn a_restart_pending_when_the_grant_grows_still_restarts() { // The peer's ceiling: what it may subscribe to is what we may announce to it. let grant = |paths: &[&str]| crate::auth::Grant { @@ -3304,7 +3304,7 @@ mod announce_test { }; let _newer = h.origin.announce("cam", route).unwrap(); auth.handle().authorize(&grant(&["cam", "other"])); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; match h.wire.take_announces().as_slice() { [lite::AnnounceBroadcast::Restart { id: 0, epoch: sent, .. }] => { @@ -3318,24 +3318,24 @@ mod announce_test { /// Costs past the wire ceiling clamp to the same value, so moving between them /// sends nothing. - #[moq_clock::test] + #[kio::test] async fn clamped_cost_change_is_quiet() { let mut h = harness().await; let route = |cost| crate::origin::Route::default().with_hops(pub_hops()).with_cost(cost); h.announcement.update(route(u64::MAX)).unwrap(); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; assert_eq!(h.wire.take_announces().len(), 1, "expected the clamped restart"); h.announcement.update(route(u64::MAX - 1)).unwrap(); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; h.assert_idle(); } /// A route whose chain contains the excluded peer is invisible to that peer's /// announce stream (control-plane split horizon via the cursor). - #[moq_clock::test] + #[kio::test] async fn excluded_routes_are_filtered() { let peer = Hop::new(42).unwrap(); let origin = Hop::new(1).unwrap().produce(); @@ -3355,7 +3355,7 @@ mod announce_test { writer: Writer::new(crate::transport::boxed::SendStream::new(SinkSend::new(log)), VERSION), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), VERSION), }; - let task = moq_clock::sim::spawn(async move { + let task = kio::clock::sim::spawn(async move { let mut announced = consumer.announced(); let self_origin = consumer.hop(); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, VERSION, None).await @@ -3376,7 +3376,7 @@ mod announce_test { } /// A route announced after the initial burst goes out as ANNOUNCE_START. - #[moq_clock::test] + #[kio::test] async fn late_route_emits_announce_start() { let mut h = harness().await; let _late = h @@ -3392,7 +3392,7 @@ mod announce_test { } /// A cost past the wire ceiling is clamped rather than rejected. - #[moq_clock::test] + #[kio::test] async fn cost_clamps_to_the_wire_ceiling() { let mut h = harness().await; h.announcement @@ -3402,7 +3402,7 @@ mod announce_test { .with_cost(u64::MAX), ) .unwrap(); - moq_clock::sleep(crate::origin::Config::default().update_hold).await; + kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; match h.wire.take_announces().as_slice() { [lite::AnnounceBroadcast::Update { cost, .. }] => { @@ -5179,7 +5179,7 @@ mod serve_group_test { /// A track served untimed to lite-05/06 carries its send time, never its frames' own /// timestamps: those of an unchecked track may be moq-transport arrival times. - #[moq_clock::test] + #[kio::test] async fn an_unchecked_track_goes_out_with_send_times() { let runtime = crate::time::sim(); let stamped = Timestamp::from_millis(36_000_000).unwrap(); @@ -5202,7 +5202,7 @@ mod serve_group_test { assert_eq!(stamp.wire(Some(stamped), &runtime).unwrap(), stamped.value()); } - #[moq_clock::test] + #[kio::test] async fn resets_with_the_abort_code() { let log = Log::default(); let session = SinkSession::new(log.clone()); @@ -5249,7 +5249,7 @@ mod serve_group_test { /// A subscription group keeps checking the max delay while a transport write is /// flow-control blocked, so a stalled send cannot pin the stream indefinitely. - #[moq_clock::test] + #[kio::test] async fn blocked_transport_write_expires_with_the_group() { let gate = kio::Producer::new(false); let session = SinkSession::gated_uni(gate.consume()); @@ -5289,7 +5289,7 @@ mod serve_group_test { "transport write is blocked" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -5301,7 +5301,7 @@ mod serve_group_test { /// A group parked at its tail when the budget gives up resets with `Old`. A FIN would /// tell the next hop the frames it already has are the whole group. - #[moq_clock::test] + #[kio::test] async fn a_group_parked_at_its_tail_expires_with_old() { let log = Log::default(); let session = SinkSession::new(log.clone()); @@ -5339,7 +5339,7 @@ mod serve_group_test { "parked waiting for the next frame" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -5351,7 +5351,7 @@ mod serve_group_test { } /// The final payload remains guarded after its frame has advanced the group cursor. - #[moq_clock::test] + #[kio::test] async fn blocked_final_transport_chunk_expires_with_the_group() { let gate = kio::Producer::new(true); let session = SinkSession::gated_uni(gate.consume()); @@ -5408,7 +5408,7 @@ mod serve_group_test { "the final byte is transport-blocked" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -5420,7 +5420,7 @@ mod serve_group_test { /// A subscription group keeps checking the max delay while transport stream credit is /// exhausted, so returning credit is reserved for content that is still live. - #[moq_clock::test] + #[kio::test] async fn blocked_transport_open_expires_with_the_group() { let gate = kio::Producer::new(false); let session = SinkSession::gated_open_uni(gate.consume()); @@ -5459,7 +5459,7 @@ mod serve_group_test { "stream credit is exhausted" ); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -5472,14 +5472,14 @@ mod serve_group_test { /// under the simulator's per-poll limit. async fn settle_run(run: &mut TrackRun, writer: &mut Writer) { while run.poll_step(writer, &kio::Waiter::noop()).is_ready() { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } } /// A peer withholding stream credit makes each subscription hold one group machine, however /// many tracks it subscribes to and groups they publish: the backlog waits in the cache. /// Granting credit then serves every group still worth sending. - #[moq_clock::test] + #[kio::test] async fn withheld_credit_holds_one_group_machine_per_subscription() { for (tracks, groups) in [(1, 1), (1, 64), (16, 1), (16, 64)] { let gate = kio::Producer::new(false); @@ -5520,7 +5520,7 @@ mod serve_group_test { /// A group waiting for stream credit that the cache evicts leaves at once, named with /// SUBSCRIBE_DROP, rather than spending the credit on a reset once it arrives. The next /// group takes its place. - #[moq_clock::test] + #[kio::test] async fn an_evicted_group_waiting_for_credit_leaves_at_once() { let version = Version::Lite07; let gate = kio::Producer::new(false); @@ -5557,7 +5557,7 @@ mod serve_group_test { /// After a stall, the credit goes to the live edge: the group parked when credit ran out /// expires, and the cursor skips the backlog the budget gave up on while it waited. - #[moq_clock::test] + #[kio::test] async fn credit_after_a_stall_serves_the_live_edge() { let version = Version::Lite07; let gate = kio::Producer::new(false); @@ -5572,7 +5572,7 @@ mod serve_group_test { write_group(&mut track, sequence, sequence * 1000); while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} assert!(run.machines() <= 1); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; } *gate.write().ok().unwrap() = true; @@ -5593,7 +5593,7 @@ mod serve_group_test { /// A stream parked on the transport resets once the cache evicts the part of its group /// it has not read: the rest can never be sent, so the buffered bytes are released /// rather than held until the peer grants flow control. - #[moq_clock::test] + #[kio::test] async fn blocked_transport_write_resets_once_the_group_is_evicted() { let gate = kio::Producer::new(false); let session = SinkSession::gated_uni(gate.consume()); @@ -5666,7 +5666,7 @@ mod serve_group_test { /// releases the stream via `poll_close`; leaving the writer to drop after /// `finish()` would fire the Drop fallback and tack a spurious Cancel reset /// onto a stream the peer already acknowledged. - #[moq_clock::test] + #[kio::test] async fn completed_group_does_not_reset() { let log = Log::default(); let session = SinkSession::new(log.clone()); @@ -5717,7 +5717,7 @@ mod serve_group_test { /// A FIN holds the group's bytes until the peer acknowledges it, so a group that /// goes stale while waiting still expires instead of pinning them. - #[moq_clock::test] + #[kio::test] async fn unacknowledged_fin_expires_with_the_group() { let session = SinkSession::new(Log::default()).with_unacked_fin(); let log = session.log.clone(); @@ -5754,7 +5754,7 @@ mod serve_group_test { assert!(futures::poll!(serve.as_mut()).is_pending(), "the FIN is unacknowledged"); assert!(log.resets().is_empty()); - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -5766,7 +5766,7 @@ mod serve_group_test { /// The transport keeps scheduling a finished stream's retransmissions until the /// FIN is acknowledged, so queue and SUBSCRIBE_UPDATE reorders still reach it. - #[moq_clock::test] + #[kio::test] async fn unacknowledged_fin_follows_priority_changes() { let session = SinkSession::new(Log::default()).with_unacked_fin(); let log = session.log.clone(); @@ -5854,7 +5854,7 @@ mod serve_group_test { (TrackRun::new(ctx, track, bounds, 0, steer), writer, log) } - #[moq_clock::test] + #[kio::test] async fn wanted_updates_ignore_stale_groups_and_recheck_the_ratio() { let track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -5899,7 +5899,7 @@ mod serve_group_test { /// group streams join it, ranked newest first by sequence alone: the session-wide queue /// takes no part. A SUBSCRIBE_UPDATE moves the group once, and an order flip re-stamps /// the open streams. - #[moq_clock::test] + #[kio::test] async fn grouped_streams_rank_within_their_subscription() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -5950,7 +5950,7 @@ mod serve_group_test { } /// The encoded body must fit both the wire cap and the transport's smaller limit. - #[moq_clock::test] + #[kio::test] async fn datagrams_fit_the_wire_and_transport_limits() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for transport in [900usize, 1200, 1400] { @@ -5984,7 +5984,7 @@ mod serve_group_test { /// A datagram goes in its subscription's send group, ranked like the stream carrying /// its group from the start, so the transport merges it into the group order. - #[moq_clock::test] + #[kio::test] async fn datagrams_rank_within_their_subscription() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -6016,7 +6016,7 @@ mod serve_group_test { /// With `ietf` negotiated, frame bounds cut datagrams by Object ID: a public datagram is frame 0, a /// relayed moq-transport one keeps its own, and both ends are inclusive. - #[moq_clock::test] + #[kio::test] async fn frame_bounds_cut_datagrams_by_object_id() { for (sequence, object_id, served) in [ (5, None, false), @@ -6078,7 +6078,7 @@ mod serve_group_test { /// An object this hop cannot identify is never egress payload. An admitted object's /// existing best-effort accounting still counts a transport-size drop as an attempt. - #[moq_clock::test] + #[kio::test] async fn unidentified_datagram_objects_are_not_metered() { use crate::model::ProduceTest; @@ -6179,7 +6179,7 @@ mod serve_group_test { /// A SUBSCRIBE_UPDATE that flips the group order reranks the next datagram, even with no /// group served in between. - #[moq_clock::test] + #[kio::test] async fn datagrams_follow_an_updated_group_order() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -6223,7 +6223,7 @@ mod serve_group_test { /// A group with more frames ready than one poll's budget drains over several polls, /// so a sibling (the transport's driver, say) runs in between. - #[moq_clock::test] + #[kio::test] async fn a_long_group_drains_within_the_budget() { /// `GroupServe`'s passes per poll; each writes at most one frame. const BUDGET: usize = 32; @@ -6283,7 +6283,7 @@ mod serve_group_test { /// SUBSCRIBE_START tells the subscriber where each range's start landed, which a relative /// or time start leaves it no way to work out from the groups it receives. - #[moq_clock::test] + #[kio::test] async fn lite07_start_names_each_resolved_range_start() { use crate::track::{Anchor, Range}; @@ -6332,7 +6332,7 @@ mod serve_group_test { } /// A skipped sequence is accounted for by DROP rather than a stream count. - #[moq_clock::test] + #[kio::test] async fn lite07_end_drops_skipped_sequences() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -6360,7 +6360,7 @@ mod serve_group_test { /// A relay that holds only the first group of a backlog answers with the largest its /// source reported, so a live joiner downstream starts at the newest group rather than /// the oldest one the budget serves. - #[moq_clock::test] + #[kio::test] async fn lite07_start_reports_the_sources_largest() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -6411,7 +6411,7 @@ mod serve_group_test { /// A stale group already named in SUBSCRIBE_DROP stays dropped once SUBSCRIBE_UPDATE /// widens the max age past it: the subscriber may have settled it already. - #[moq_clock::test] + #[kio::test] async fn a_reported_stale_drop_survives_a_widened_max_age() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut track = track::Producer::new( @@ -6450,7 +6450,7 @@ mod serve_group_test { /// Lite-05 and later name every sequence below the end that the subscription never /// got once the track ends: one skipped between groups, and one past the last. - #[moq_clock::test] + #[kio::test] async fn the_end_drops_the_sequences_never_served() { for version in [Version::Lite05, Version::Lite06] { let mut track = track::Producer::new( @@ -6476,7 +6476,7 @@ mod serve_group_test { /// An upstream DROP is forwarded while the track is still live, and the end sweep /// does not name it again. - #[moq_clock::test] + #[kio::test] async fn an_explicit_drop_is_forwarded_early_once() { for version in [Version::Lite05, Version::Lite06] { let mut track = track::Producer::new( @@ -6507,7 +6507,7 @@ mod serve_group_test { /// A group the publisher cuts is dropped once, while the track is live, and the end /// sweep does not name it again. - #[moq_clock::test] + #[kio::test] async fn a_cut_is_dropped_early_once() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6535,7 +6535,7 @@ mod serve_group_test { /// A wide upstream DROP is held and forwarded as a range, never one entry per sequence, /// and a wider one later forwards only what is new. - #[moq_clock::test] + #[kio::test] async fn a_wide_drop_is_forwarded_as_a_range() { const WIDE: u64 = 1 << 40; let version = Version::Lite06; @@ -6565,7 +6565,7 @@ mod serve_group_test { /// An upstream drop below the floor is forwarded once an update lowers the floor to it, /// not only at the end. - #[moq_clock::test] + #[kio::test] async fn a_lowered_start_forwards_a_drop_held_below_it() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6598,7 +6598,7 @@ mod serve_group_test { } /// A group the publisher cuts and then re-creates is served, not dropped. - #[moq_clock::test] + #[kio::test] async fn a_recreated_cut_is_not_dropped() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6623,7 +6623,7 @@ mod serve_group_test { /// A cut this run already dropped stays dropped: the subscriber accounted for it, so a /// group the publisher re-creates under it afterwards is not served. - #[moq_clock::test] + #[kio::test] async fn a_cut_dropped_then_recreated_is_not_served() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6657,7 +6657,7 @@ mod serve_group_test { /// A late group the cursor skips as stale is dropped at once, even when it is the only /// unread group and nothing else wakes the run. - #[moq_clock::test] + #[kio::test] async fn a_late_stale_group_is_dropped_early() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6674,7 +6674,7 @@ mod serve_group_test { assert_eq!(drops(&mut writer, &log, version).await, []); // Its successor arrived a full budget ago, so group 1 is stale on the wall clock. - moq_clock::sim::advance(Duration::from_secs(2)).await; + kio::clock::sim::advance(Duration::from_secs(2)).await; write_group(&mut track, 1, 1); while run.poll_step(&mut writer, &kio::Waiter::noop()).is_ready() {} assert_eq!( @@ -6687,7 +6687,7 @@ mod serve_group_test { /// A group skipped for a missing head after SUBSCRIBE_START is dropped at once, not /// left for the end sweep. - #[moq_clock::test] + #[kio::test] async fn a_missing_head_is_dropped_early() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6722,7 +6722,7 @@ mod serve_group_test { } /// A missing head at the model's largest sequence has no successor to name. - #[moq_clock::test] + #[kio::test] async fn a_missing_head_at_the_maximum_sequence_does_not_panic() { let track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -6743,10 +6743,10 @@ mod serve_group_test { } /// A long-budget reader warms the relay without changing a live reader's resolved start. - #[moq_clock::test] + #[kio::test] async fn cold_and_warm_relays_resolve_the_same_start() { fn drive(mut driver: D) { - drop(moq_clock::sim::spawn(moq_clock::drive(move |now, waiter| { + drop(kio::clock::sim::spawn(kio::clock::drive(move |now, waiter| { crate::time::Driver::poll(&mut driver, now, waiter) }))); } @@ -6776,12 +6776,12 @@ mod serve_group_test { .with_publisher(publisher); futures::join!( async { - let (session, driver) = client.connect(moq_clock::now(), client_transport).await.unwrap(); + let (session, driver) = client.connect(kio::clock::now(), client_transport).await.unwrap(); drive(driver); session }, async { - let (session, driver) = server.accept(moq_clock::now(), server_transport).await.unwrap(); + let (session, driver) = server.accept(kio::clock::now(), server_transport).await.unwrap(); drive(driver); session } @@ -6820,7 +6820,7 @@ mod serve_group_test { assert_eq!(keeper.recv_group().await.unwrap().unwrap().sequence, sequence); } } - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let subscriber = origin(3); let _downstream = connect(version, &relay, &subscriber).await; let remote = subscriber @@ -6848,7 +6848,7 @@ mod serve_group_test { } /// A relay's retained stale groups must not change the start it answers downstream. - #[moq_clock::test] + #[kio::test] async fn the_start_names_past_the_stale_groups_it_skips() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut starts = Vec::new(); @@ -6862,7 +6862,7 @@ mod serve_group_test { for sequence in (if warm { 0 } else { 2 })..3 { write_group(&mut track, sequence, sequence * 10); } - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; let subscriber = track.subscribe(track::Subscription::default()); let (mut run, mut writer, log) = lite_run(version, SinkSession::new(Log::default()), subscriber); assert!( @@ -6883,7 +6883,7 @@ mod serve_group_test { } /// Upstream drops received before the start exclude the entire range, even on lite-07. - #[moq_clock::test] + #[kio::test] async fn the_start_names_past_the_upstream_dropped_range() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut track = track::Producer::new( @@ -6912,7 +6912,7 @@ mod serve_group_test { } /// A range given up before the start resolves, but above it, is still named promptly. - #[moq_clock::test] + #[kio::test] async fn a_range_skipped_above_the_start_is_dropped() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut track = track::Producer::new( @@ -6938,7 +6938,7 @@ mod serve_group_test { /// A SUBSCRIBE_UPDATE that lowers the start below SUBSCRIBE_START asks for those groups /// too, so the drops at the end count from there. - #[moq_clock::test] + #[kio::test] async fn the_end_drops_below_a_lowered_start() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -6981,7 +6981,7 @@ mod serve_group_test { /// A lowered start restarts the age of the gaps it newly asks for, as the subscriber does, /// so a gap below the old start isn't folded away on the time before the update. - #[moq_clock::test] + #[kio::test] async fn the_end_drops_below_a_lowered_start_after_the_grace() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -7000,7 +7000,7 @@ mod serve_group_test { assert!(step.is_ready(), "the start never resolved"); } - moq_clock::sim::advance(Duration::from_secs(2)).await; + kio::clock::sim::advance(Duration::from_secs(2)).await; run.update(lite::SubscribeUpdate { wanted_group: None, order: crate::track::Order::Descending, @@ -7027,7 +7027,7 @@ mod serve_group_test { /// After a raised start, lowering it again restarts the gaps below the raised floor, not /// only those below the lowest start ever asked for. - #[moq_clock::test] + #[kio::test] async fn the_end_drops_below_a_start_raised_then_lowered() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -7060,9 +7060,9 @@ mod serve_group_test { assert!(futures::poll!(run.as_mut()).is_pending()); } - moq_clock::sim::advance(Duration::from_millis(900)).await; + kio::clock::sim::advance(Duration::from_millis(900)).await; run.update(update(2)); - moq_clock::sim::advance(Duration::from_millis(200)).await; + kio::clock::sim::advance(Duration::from_millis(200)).await; track.finish_at(track::Position::group(6), None).unwrap(); drop(track); kio::wait(|waiter| run.poll(&mut writer, waiter)).await.unwrap(); @@ -7072,7 +7072,7 @@ mod serve_group_test { /// A raised floor sends no early drop: a later update may lower it again, and the /// subscriber cannot take back a drop for the groups that reopens. - #[moq_clock::test] + #[kio::test] async fn a_raised_floor_is_not_dropped_early() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -7113,7 +7113,7 @@ mod serve_group_test { /// Pre-06 an absent Group Start is the latest group, so an update that drops a named /// floor re-pins the cursor there: a group created below it afterwards is not served. - #[moq_clock::test] + #[kio::test] async fn a_pre06_update_dropping_the_floor_repins_to_the_latest_group() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7151,7 +7151,7 @@ mod serve_group_test { /// On an empty track the re-pin has no latest group to name, so the first group the /// track produces is served, even below the dropped floor. - #[moq_clock::test] + #[kio::test] async fn a_pre06_update_dropping_the_floor_on_an_empty_track_serves_the_next_group() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7184,7 +7184,7 @@ mod serve_group_test { /// A never-arrived gap remains owed after the publisher's grace: only the subscriber /// may age it out, and the end sweep must still name it before the FIN. - #[moq_clock::test] + #[kio::test] async fn the_end_drops_a_never_arrived_gap_past_the_grace() { let version = Version::Lite06; let mut track = track::Producer::new( @@ -7201,7 +7201,7 @@ mod serve_group_test { write_group(&mut track, 2, 0); assert!(futures::poll!(run.as_mut()).is_pending()); - moq_clock::sim::advance(Duration::from_secs(2)).await; + kio::clock::sim::advance(Duration::from_secs(2)).await; write_group(&mut track, 4, 0); assert!(futures::poll!(run.as_mut()).is_pending()); track.finish_at(track::Position::group(5), None).unwrap(); @@ -7286,7 +7286,7 @@ mod serve_group_test { /// A resume past the only finished group leaves that group below the cursor. /// Widening to no floor serves it: it is the live edge until a newer group /// exists, and a catalog never publishes the next one. - #[moq_clock::test] + #[kio::test] async fn a_widening_update_serves_the_finished_group_it_had_skipped() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7311,7 +7311,7 @@ mod serve_group_test { /// Widening the floor serves a cached group below the old one, even though it arrived /// before the groups already served, and serves those only once. - #[moq_clock::test] + #[kio::test] async fn a_widening_update_serves_a_cached_group_below_the_old_floor() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7340,7 +7340,7 @@ mod serve_group_test { /// A SUBSCRIBE_UPDATE landing while the first group waits on the source's start keeps /// the floor it raised: resolving the start from the held group must not lower it. - #[moq_clock::test] + #[kio::test] async fn held_first_group_keeps_an_updated_floor() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7375,7 +7375,7 @@ mod serve_group_test { /// A source whose feed starts below the subscriber's floor serves the floor's group, so /// a newer group arriving first must not resolve the start past it. - #[moq_clock::test] + #[kio::test] async fn held_first_group_resolves_to_the_floor_under_the_source() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7398,7 +7398,7 @@ mod serve_group_test { /// A group skipped for a missing head before the start resolves is never served, so /// SUBSCRIBE_START must not name it, even where the source's feed starts. - #[moq_clock::test] + #[kio::test] async fn held_first_group_starts_past_a_skipped_head() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7425,7 +7425,7 @@ mod serve_group_test { /// Adjacent ranges skipped with different errors before the start resolves are all /// passed over, so SUBSCRIBE_START names neither. - #[moq_clock::test] + #[kio::test] async fn held_first_group_starts_past_adjacent_skips() { let mut track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7452,7 +7452,7 @@ mod serve_group_test { } /// A track that ends without a group still ends the subscription, with no stream owed. - #[moq_clock::test] + #[kio::test] async fn lite07_empty_track_ends_without_a_start() { let track = track::Producer::new( Arc::new(broadcast::Info::default()), @@ -7468,7 +7468,7 @@ mod serve_group_test { } /// A declared end is sent before stream credit, and a group that expires first is dropped. - #[moq_clock::test] + #[kio::test] async fn lite07_end_precedes_blocked_streams_and_reports_expiry() { let gate = kio::Producer::new(false); let mut track = track::Producer::new( @@ -7484,7 +7484,7 @@ mod serve_group_test { assert!(futures::poll!(run.as_mut()).is_pending()); // Group 1 lands a second later, expiring group 0 before it ever opened. - moq_clock::sim::advance(Duration::from_secs(1)).await; + kio::clock::sim::advance(Duration::from_secs(1)).await; write_group(&mut track, 1, 1000); track.finish().unwrap(); assert!(futures::poll!(run.as_mut()).is_pending(), "group 1 is still opening"); @@ -7520,7 +7520,7 @@ mod tests { /// the caller assigned it, on the data plane and not just the announce filter. /// Otherwise it can subscribe its way back to content that already flowed through /// it, which is the loop the announce filter exists to prevent. - #[moq_clock::test] + #[kio::test] async fn serving_origin_falls_back_to_the_assigned_identity() { let assigned = crate::Hop::new(777).unwrap(); let upstream = crate::Hop::new(778).unwrap(); @@ -7580,7 +7580,7 @@ mod tests { /// same per-peer route selection as the live loop: a broadcast whose only /// route flows through the excluded hop (here the peer's assigned identity, /// `Client::with_peer_hop`) is filtered from the initial set too. - #[moq_clock::test] + #[kio::test] async fn announce_init_applies_route_selection() { let assigned = crate::Hop::new(777).unwrap(); let clean_publisher = crate::Hop::new(778).unwrap(); @@ -7636,7 +7636,7 @@ mod tests { /// A broadcast sent in ANNOUNCE_INIT is live like any other, so its end reaches /// the peer instead of being treated as never advertised. - #[moq_clock::test] + #[kio::test] async fn announce_init_broadcast_ends() { let self_origin = crate::Hop::new(1).unwrap(); let origin = crate::origin::Config::new(self_origin).produce(); @@ -7660,10 +7660,10 @@ mod tests { )); assert!(futures::poll!(run.as_mut()).is_pending()); drop(cam); - moq_clock::timeout(std::time::Duration::from_secs(10), async { + kio::clock::timeout(std::time::Duration::from_secs(10), async { while log.writes.lock().unwrap().windows(3).filter(|w| *w == b"cam").count() < 2 { assert!(futures::poll!(run.as_mut()).is_pending()); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } }) .await @@ -7672,7 +7672,7 @@ mod tests { /// A close that lands before the initial burst still sends it, then ends every /// broadcast, so the peer never sees a FIN in place of ANNOUNCE_INIT. - #[moq_clock::test] + #[kio::test] async fn withdraw_before_init_sends_the_initial_burst() { let self_origin = crate::Hop::new(1).unwrap(); let origin = crate::origin::Config::new(self_origin).produce(); @@ -7738,7 +7738,7 @@ mod tests { ProbeServe::new(publisher.shared.clone(), publisher.runtime.clone(), stream) } - #[moq_clock::test] + #[kio::test] async fn malformed_complete_goaway_closes_the_session() { use kio::Task; for version in [Version::Lite04, Version::Lite05, Version::Lite06, Version::Lite07] { @@ -7765,7 +7765,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn unknown_control_types_reset_only_their_stream() { use kio::Task; // An unassigned type everywhere, then types a version predates: PROBE before lite-03, @@ -7844,7 +7844,7 @@ mod tests { async fn reports(&mut self, after: Duration) -> Vec { let server = &mut self.server; let run = kio::wait(|waiter| server.poll_probe(waiter)); - assert!(moq_clock::timeout(after, run).await.is_err(), "the stream never ends"); + assert!(kio::clock::timeout(after, run).await.is_err(), "the stream never ends"); decode_probes(&self.log.writes.lock().unwrap(), self.version) } } @@ -7868,7 +7868,7 @@ mod tests { /// The two PROBE fields are independent, each using 0 for unknown, so discarding /// the whole message for want of a bitrate leaves a subscriber with no RTT at /// all. That is what pins a qmux viewer to its fallback jitter buffer. - #[moq_clock::test] + #[kio::test] async fn reports_rtt_without_a_bitrate() { let stats = crate::lite::test_transport::SinkStats::default().with_rtt(std::time::Duration::from_millis(40)); let probes = probe_writes(stats).await; @@ -7879,7 +7879,7 @@ mod tests { } /// The mirror case: a send rate with no RTT still reports. - #[moq_clock::test] + #[kio::test] async fn reports_bitrate_without_an_rtt() { let stats = crate::lite::test_transport::SinkStats::default().with_send_rate(1_000_000); let probes = probe_writes(stats).await; @@ -7891,7 +7891,7 @@ mod tests { /// A transport measuring neither has nothing to say, and must not emit a report /// claiming two zeroes. - #[moq_clock::test] + #[kio::test] async fn reports_nothing_when_nothing_is_measurable() { let probes = probe_writes(crate::lite::test_transport::SinkStats::default()).await; assert!(probes.is_empty(), "expected no report, got {probes:?}"); @@ -7900,7 +7900,7 @@ mod tests { /// Lite03's PROBE carries no RTT field, so an RTT-only report has nothing to /// say there. Sending one anyway would serialize as a bare "bitrate unknown" /// and, worse, fire again on every RTT movement. - #[moq_clock::test] + #[kio::test] async fn lite03_sends_nothing_for_an_rtt_only_report() { let stats = crate::lite::test_transport::SinkStats::default().with_rtt(std::time::Duration::from_millis(40)); let probes = probe_writes_version(stats, Version::Lite03).await; @@ -7908,7 +7908,7 @@ mod tests { } /// Lite03 still reports the half it can carry. - #[moq_clock::test] + #[kio::test] async fn lite03_reports_the_bitrate() { let stats = crate::lite::test_transport::SinkStats::default() .with_send_rate(1_000_000) @@ -7922,7 +7922,7 @@ mod tests { /// A bitrate that becomes unknown is worth one report: the peer is still /// holding the last value we sent. But only one, however long the stream runs. - #[moq_clock::test] + #[kio::test] async fn a_bitrate_going_unknown_is_retracted_once() { let stats = crate::lite::test_transport::SinkStats::default().with_send_rate(1_000_000); let mut probing = Probing::new(stats, Version::Lite05).await; @@ -7944,7 +7944,7 @@ mod tests { /// An estimate that never moves is refreshed once per PROBE_MAX_AGE, and costs /// nothing in between. - #[moq_clock::test] + #[kio::test] async fn an_unchanged_estimate_refreshes_at_max_age() { let stats = crate::lite::test_transport::SinkStats::default().with_send_rate(1_000_000); let mut probing = Probing::new(stats, Version::Lite05).await; @@ -7955,7 +7955,7 @@ mod tests { } /// A move past PROBE_MAX_DELTA is reported as soon as the estimate changes. - #[moq_clock::test] + #[kio::test] async fn a_large_move_reports_at_once() { let stats = crate::lite::test_transport::SinkStats::default().with_send_rate(1_000_000); let mut probing = Probing::new(stats, Version::Lite05).await; @@ -7969,7 +7969,7 @@ mod tests { /// A smaller move waits for the threshold to decay to it, even though the /// estimate does not change again. - #[moq_clock::test] + #[kio::test] async fn a_small_move_waits_for_the_threshold() { let stats = crate::lite::test_transport::SinkStats::default().with_send_rate(1_000_000); let mut probing = Probing::new(stats, Version::Lite05).await; @@ -7995,7 +7995,7 @@ mod tests { /// Drive `serve` until it ends, or everything parks: whether it ended. async fn drive(serve: &mut RequestServe) -> bool { - moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| serve.poll(waiter))) + kio::clock::timeout(Duration::from_millis(1), kio::wait(|waiter| serve.poll(waiter))) .await .is_ok() } @@ -8075,7 +8075,7 @@ mod tests { drop(serve); if let Some(track) = track { let mut demand = track.demand(); - let unused = moq_clock::timeout( + let unused = kio::clock::timeout( Duration::from_millis(1), kio::wait(|waiter| crate::util::poll_unwanted(&mut demand, waiter)), ); @@ -8097,7 +8097,7 @@ mod tests { /// transaction (moq-lite: closing the send direction ends the stream), however the /// answer is waiting. The lookup ends then, rather than pinning an upstream request /// nobody will read. - #[moq_clock::test] + #[kio::test] async fn a_request_ends_when_the_requester_leaves() { let broadcast = crate::Path::from_static("room"); for version in [Version::Lite05, Version::Lite06, Version::Lite07] { @@ -8140,7 +8140,7 @@ mod tests { /// A broadcast that overflows `Path::MAX_BYTES` under a deep root is refused on its own /// stream, never by closing the session. - #[moq_clock::test] + #[kio::test] async fn a_broadcast_too_long_under_the_root_is_refused_per_request() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -8192,7 +8192,7 @@ mod tests { reader: crate::coding::Reader::new(crate::transport::boxed::RecvStream::new(recv), version), }; let mut serve = RequestServe::::new(publisher.shared.clone(), stream); - let served = moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| serve.poll(waiter))) + let served = kio::clock::timeout(Duration::from_millis(1), kio::wait(|waiter| serve.poll(waiter))) .await .expect("the request was left waiting"); assert!(served.is_ok(), "{version:?}: the session closed: {served:?}"); @@ -8206,7 +8206,7 @@ mod tests { /// An answered TRACK stream holds its track until the requester closes its side, by /// FIN or reset, and the hold owes nothing a draining close would wait for. A requester /// that leaves while the reply is still blocked on flow control lets the track go too. - #[moq_clock::test] + #[kio::test] async fn an_answered_track_stream_holds_the_track_until_the_requester_closes() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for close in [Close::Fin, Close::Reset] { @@ -8282,7 +8282,7 @@ mod tests { session.close(close); assert!(drive(&mut serve).await, "{case}: still holding"); let mut demand = track.demand(); - moq_clock::timeout( + kio::clock::timeout( Duration::from_millis(1), kio::wait(|waiter| crate::util::poll_unwanted(&mut demand, waiter)), ) @@ -8304,7 +8304,7 @@ mod tests { /// resolves keeps it waiting, and the latest applies once it starts. Its wanted group /// is state each update restates: past the largest it joins, and once that group /// exists the same value asks for nothing more. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_update_is_not_a_close() { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let broadcast = origin.create_broadcast("room").unwrap(); @@ -8506,7 +8506,7 @@ mod tests { /// sibling (the transport's driver, say) runs between its polls. Without it, one poll /// served every group the producer kept appending and starved the rest of the runtime /// (a go publisher's 2.5 ms audio groups timed its session out). - #[moq_clock::test] + #[kio::test] async fn a_busy_subscription_yields_to_its_siblings() { /// `RequestServe`'s passes per poll; each serves at most one group. const BUDGET: u64 = 32; @@ -8586,7 +8586,7 @@ mod tests { /// A requester streaming SUBSCRIBE_UPDATEs gets at most a budget of them applied per /// poll, so its siblings run between them, yet every update still applies in order. - #[moq_clock::test] + #[kio::test] async fn a_flood_of_updates_yields_to_its_siblings() { /// `RequestServe`'s passes per poll; each applies at most one update. const BUDGET: usize = 32; @@ -8632,7 +8632,7 @@ mod tests { } /// An update that restates the subscription wakes none of its groups. - #[moq_clock::test] + #[kio::test] async fn a_repeated_update_wakes_no_group() { #[derive(Default)] struct Count(std::sync::atomic::AtomicUsize); @@ -8675,7 +8675,7 @@ mod tests { /// A cold relay fills a bounded request from the group's head, so its cache does not /// store an undecodable tail merely because that was the downstream reader's floor. - #[moq_clock::test] + #[kio::test] async fn a_cold_bounded_fetch_requests_the_prefix() { let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); let broadcast = origin.create_broadcast("room").unwrap(); @@ -8720,7 +8720,7 @@ mod tests { /// A FETCH whose own budget gives up on its group partway resets as too old: a FIN /// would tell the requester the prefix it got is the whole group. - #[moq_clock::test] + #[kio::test] async fn an_expired_fetch_resets_rather_than_finishing() { const VERSION: Version = Version::Lite07; let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); @@ -8785,7 +8785,7 @@ mod tests { assert_eq!(session.log.resets(), vec![crate::StreamError::Old.to_code()]); } - #[moq_clock::test] + #[kio::test] async fn report_consumes_probe_targets_until_fin() { for version in [ Version::Lite03, @@ -8829,7 +8829,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn draining_probe_targets_yields() { const TARGETS: usize = 100; let version = Version::Lite07; @@ -8862,7 +8862,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn malformed_subscribe_update_closes_after_request_setup() { use kio::Task; for version in [Version::Lite05, Version::Lite06, Version::Lite07] { @@ -8920,7 +8920,7 @@ mod tests { /// A second listing of a broadcast on one session replaces the first, so a peer cannot /// multiply the listed set's memory and fanout by listing it again. - #[moq_clock::test] + #[kio::test] async fn a_newer_listing_of_a_broadcast_replaces_the_older() { use kio::Task; let version = Version::Lite07; @@ -8958,7 +8958,7 @@ mod tests { // Whether the control is still serving after the runtime settles. async fn serving(control: &mut Control) -> bool { - moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))) + kio::clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))) .await .is_err() } @@ -8973,7 +8973,7 @@ mod tests { assert!(serving(&mut newer).await, "the newer listing ended"); } - #[moq_clock::test] + #[kio::test] async fn a_producer_decode_error_stays_on_its_request() { use kio::Task; for version in [Version::Lite05, Version::Lite06, Version::Lite07] { @@ -9011,7 +9011,7 @@ mod tests { runtime: crate::time::sim(), state: ControlState::Subscribe(RequestServe::new(shared, probe.stream.unwrap())), }; - let pending = moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))).await; + let pending = kio::clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))).await; assert!(pending.is_err(), "{version}: request did not wait for its track"); // The local producer fails with the same error type a malformed peer message // would; it is still not the peer's fault. @@ -9021,7 +9021,7 @@ mod tests { .expect("track requested") .unwrap(); track.reject(Error::Decode(crate::DecodeError::InvalidValue)); - let ended = moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))).await; + let ended = kio::clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter))).await; assert!(ended.is_ok(), "{version}: the request did not end"); assert!( log.closes().is_empty(), @@ -9031,7 +9031,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn goaway_roles_limits_and_transport_termination() { use kio::Task; for version in [Version::Lite04, Version::Lite05, Version::Lite06, Version::Lite07] { @@ -9159,7 +9159,7 @@ mod tests { /// A subscription's send group ranks by the peer's subscriber priority first, and the /// publisher's track priority breaks a tie between two at one subscriber priority. - #[moq_clock::test] + #[kio::test] async fn send_group_ranks_by_the_subscriber_then_the_publisher() { let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); let broadcast = origin.create_broadcast("a").unwrap(); diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index e845ceb98c1..e95d8785253 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -879,7 +879,7 @@ mod tests { use crate::coding::Encode; use crate::lite::test_transport::ScriptedSession; - #[moq_clock::test] + #[kio::test] async fn malformed_auth_replies_close_the_session() { // Unknown reply, invalid code, truncated error, and trailing body bytes. for script in [ @@ -894,7 +894,7 @@ mod tests { /// A protocol error on a live connection must end partial receive reads before /// waiting for them, otherwise receive draining could wait for new peer data. - #[moq_clock::test] + #[kio::test] async fn malformed_auth_closes_before_draining_a_partial_group_header() { assert_session_closes( ScriptedSession::per_stream(vec![vec![99]]).with_incoming_unis(vec![vec![0]]), @@ -905,7 +905,7 @@ mod tests { /// After close, no stream can deliver the peer SETUP a GROUP stream waits on to read /// its header, whether the SETUP stream was truncated or never opened. - #[moq_clock::test] + #[kio::test] async fn drain_ends_when_groups_wait_on_an_undeliverable_setup() { let version = Version::Lite07; let mut group = Vec::new(); @@ -952,7 +952,7 @@ mod tests { .unwrap(); let mut driver = start.driver; - let res = moq_clock::timeout( + let res = kio::clock::timeout( std::time::Duration::from_secs(10), kio::wait(|waiter| driver.poll(waiter)), ) @@ -998,7 +998,7 @@ mod tests { let mut driver = start.driver; let token = handle.present(bytes::Bytes::from_static(b"token")).unwrap(); - let res = moq_clock::timeout( + let res = kio::clock::timeout( std::time::Duration::from_secs(5), kio::wait(|waiter| driver.poll(waiter)), ) @@ -1009,7 +1009,7 @@ mod tests { /// A granted token whose stream the peer resets is presented again on the same session, /// backing off while each attempt is lost before a reply: at 0s, 1s, and 3s. - #[moq_clock::test] + #[kio::test] async fn a_lost_stream_is_presented_again() { let grant = empty_grant(Version::Lite07); let transport = ScriptedSession::per_stream(vec![grant.clone(), grant]); @@ -1030,7 +1030,7 @@ mod tests { /// A retry's stream that ends before its reply is lost, not a peer without AUTH: the /// peer already answered the token, so it is presented again, backing off from the /// refusal's delay: at 0s, 1s, and 3s. - #[moq_clock::test] + #[kio::test] async fn a_lost_retry_is_presented_again() { let version = Version::Lite07; let mut busy = Vec::new(); @@ -1054,7 +1054,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn malformed_presenter_auth_closes_the_session() { for script in [vec![7, 1, 2], vec![7, 1, 0, 0]] { let transport = ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![script]); @@ -1084,7 +1084,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn malformed_auth_ok_closes_the_session() { for pattern in [ b"*/**".as_slice(), @@ -1116,7 +1116,7 @@ mod tests { /// A reply cut off inside its declared size fails to decode, unlike a peer that /// resets before answering. - #[moq_clock::test] + #[kio::test] async fn truncated_auth_reply_closes_the_session() { let mut script = Vec::new(); let mut w = crate::coding::Encoder::new(&mut script, Version::Lite07.into()); @@ -1126,7 +1126,7 @@ mod tests { assert_session_closes(ScriptedSession::per_stream_eof(vec![script]), Setup::default()).await; } - #[moq_clock::test] + #[kio::test] async fn malformed_auth_error_reasons_close_the_session() { for reason in [vec![0xff], vec![b'a'; 8193]] { let mut script = Vec::new(); @@ -1163,7 +1163,7 @@ mod tests { }) .unwrap(); let mut driver = start.driver; - let res = moq_clock::timeout( + let res = kio::clock::timeout( std::time::Duration::from_secs(10), kio::wait(|waiter| driver.poll(waiter)), ) @@ -1173,7 +1173,7 @@ mod tests { assert_eq!(log.closes()[0].0, SessionError::ProtocolViolation.to_code()); } - #[moq_clock::test] + #[kio::test] async fn accept_setup_does_not_wait_on_an_early_stream_header() { let version = Version::Lite05; let mut setup = Vec::new(); @@ -1191,7 +1191,7 @@ mod tests { assert_eq!(accepted.early.len(), 1); } - #[moq_clock::test] + #[kio::test] async fn accept_setup_refuses_two_incomplete_setup_streams() { use futures::FutureExt; let session = @@ -1202,7 +1202,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] async fn duplicate_setup_closes_the_session() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for complete in [false, true] { @@ -1247,7 +1247,7 @@ mod tests { /// A SETUP that fails to decode leaves nothing to wait on, since the Setup Stream is /// already claimed. - #[moq_clock::test] + #[kio::test] async fn malformed_setup_closes_the_session() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut truncated = Vec::new(); @@ -1324,7 +1324,7 @@ mod tests { .unwrap() } - #[moq_clock::test] + #[kio::test] async fn server_setup_client_parameters_close_the_session() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for body in [vec![1, 2, 0], vec![1, 3, 1, 0], vec![1, 3, 1, 1], vec![1, 3, 1, 3]] { @@ -1344,7 +1344,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn unknown_client_role_remains_bidirectional() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let transport = ScriptedSession::new(Vec::new()).with_incoming_unis(vec![vec![1, 4, 1, 3, 1, 3]]); @@ -1359,7 +1359,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn malformed_probe_reports_close_the_session() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let transport = if version.has_auth() { @@ -1393,7 +1393,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn malformed_group_headers_remain_per_stream() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let transport = ScriptedSession::new(Vec::new()).with_incoming_unis(vec![vec![0, 0]]); @@ -1407,7 +1407,7 @@ mod tests { // GOAWAY is not a request: refusing it without credit would leave the peer // unaware that we are draining. - #[moq_clock::test] + #[kio::test] async fn goaway_waits_for_stream_credit() { let transport = ScriptedSession::new(Vec::new()).without_credit(); let log = transport.log.clone(); @@ -1421,7 +1421,7 @@ mod tests { assert!(log.closes().is_empty()); } - #[moq_clock::test] + #[kio::test] async fn clients_never_emit_a_goaway_redirect() { for version in [Version::Lite04, Version::Lite05, Version::Lite06, Version::Lite07] { let client = raw_session(ScriptedSession::new(Vec::new()), version, true, None); diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index d57c5bf54c5..2db11a46e0d 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -2167,7 +2167,7 @@ mod tests { /// A fetch held for a pre-lite-05 feed is released once its caller gives up, rather /// than waiting, track handle and all, for a group the feed may never reach. - #[moq_clock::test] + #[kio::test] async fn an_abandoned_feed_fetch_is_released() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2187,7 +2187,7 @@ mod tests { /// A lite-07 publisher that FINs with no SUBSCRIBE_START served nothing, which covers the /// ranges the SUBSCRIBE asked for but not ones an update it may not have read changed. - #[moq_clock::test] + #[kio::test] async fn a_startless_fin_covers_only_the_subscribed_ranges() { let tail = kio::Producer::new(Tail::default()); let Sub::Active(mut active) = feed_sub(&tail).await else { @@ -2205,7 +2205,7 @@ mod tests { /// A covered FIN owes a relative range only from its own SUBSCRIBE_START, not from the /// lowest start of a disjoint range below it. - #[moq_clock::test] + #[kio::test] async fn a_covered_fin_owes_each_range_from_its_own_start() { let tail = kio::Producer::new(Tail::default()); let Sub::Active(mut active) = feed_sub(&tail).await else { @@ -2243,7 +2243,7 @@ mod tests { /// QUIC does not order streams, so group 2's header can reach the relay before group 1's. /// A fetch held for group 1 keeps waiting through the grace and is served when it lands. - #[moq_clock::test] + #[kio::test] async fn a_feed_fetch_waits_out_a_reordered_group() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2271,7 +2271,7 @@ mod tests { } /// A group still missing a grace after a later one arrived is a miss, not a hold. - #[moq_clock::test] + #[kio::test] async fn a_feed_fetch_misses_once_the_ledger_gives_up() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2291,7 +2291,7 @@ mod tests { /// A floor lowered by an update, or a fresh SUBSCRIBE starting below earlier arrivals, /// asks for groups only now, so a fetch held for one waits out a fresh grace rather than /// the age of the gap below those arrivals. - #[moq_clock::test] + #[kio::test] async fn a_lowered_floor_restarts_a_held_fetch_gap() { for update in [true, false] { let h = Harness::new(Version::Lite04); @@ -2301,7 +2301,7 @@ mod tests { group.write_frame(None, &b"x"[..]).unwrap(); group.finish().unwrap(); } - moq_clock::sleep(crate::tail::GRACE * 2).await; + kio::clock::sleep(crate::tail::GRACE * 2).await; let lowered = Some(Subscription::default().with_range(2..)); // The SUBSCRIBE in force, already answered. @@ -2377,7 +2377,7 @@ mod tests { (track, callers, requests) } - #[moq_clock::test] + #[kio::test] async fn an_abandoned_feed_fetch_wakes_its_owner_without_an_arrival() { #[derive(Default)] struct Wakes(std::sync::atomic::AtomicUsize); @@ -2423,7 +2423,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn a_feed_arrival_polls_only_its_group() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2444,7 +2444,7 @@ mod tests { assert_eq!(fetches.fold.deadline(), Some(start + crate::tail::GRACE)); } - #[moq_clock::test] + #[kio::test] async fn a_feed_fold_polls_only_its_expired_gap() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2457,7 +2457,7 @@ mod tests { } arrive(&track, &tail, 0, start); arrive(&track, &tail, 2, start); - moq_clock::sleep(crate::tail::GRACE / 2).await; + kio::clock::sleep(crate::tail::GRACE / 2).await; arrive(&track, &tail, 4, start + crate::tail::GRACE / 2); let waiter = kio::Waiter::noop(); fetches.poll(&sub, start, &waiter); @@ -2472,7 +2472,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn feed_boundaries_poll_only_the_groups_they_exclude() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2501,7 +2501,7 @@ mod tests { assert!(fetches.held.is_empty(), "closure releases all remaining held groups"); } - #[moq_clock::test] + #[kio::test] async fn a_feed_drop_polls_only_the_groups_it_excludes() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2530,7 +2530,7 @@ mod tests { /// A peer that starts its feed far past a reader's floor makes the reader's miss wide. /// Holding it settles what the feed gave up by run, in one poll, rather than holding or /// refusing its groups one at a time. - #[moq_clock::test] + #[kio::test] async fn a_wide_feed_fill_settles_by_run() { const WIDE: u64 = 1 << 40; let start = crate::time::Instant::now(); @@ -2566,7 +2566,7 @@ mod tests { } /// A held fill costs one entry, shared by every reader that joins it, until the last leaves. - #[moq_clock::test] + #[kio::test] async fn held_feed_fills_follow_shared_demand() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2603,7 +2603,7 @@ mod tests { assert!(dynamic.requested_fill().now_or_never().is_none()); } - #[moq_clock::test] + #[kio::test] async fn a_feed_fetch_can_replace_an_abandoned_attempt_before_polling() { let start = crate::time::Instant::now(); let clock = crate::time::Deadlines::new(start); @@ -2630,7 +2630,7 @@ mod tests { } /// Sweep held fetches, unrelated tracks, and live arrival runs independently. - #[moq_clock::test] + #[kio::test] #[ignore = "release benchmark, run by nightly"] async fn benchmark_feed_fetch_wakes() { struct ScanFetches { @@ -2707,7 +2707,7 @@ mod tests { for _ in 0..tracks { // The sim counts ready polls per task poll to catch spinning loops, so // give each track's setup, and the timed loop below, a poll of its own. - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let (track, callers, requests) = feed_batch(1_000_000..1_000_000 + held); let tail = kio::Producer::new(Tail::default()); let sub = feed_sub(&tail).await; @@ -2731,7 +2731,7 @@ mod tests { fixtures.push((track, callers, tail, sub, scan, fetches)); } let (track, _callers, tail, sub, scan, fetches) = &mut fixtures[0]; - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; #[expect( clippy::disallowed_methods, clippy::disallowed_types, @@ -2759,7 +2759,7 @@ mod tests { /// The owed groups start at the floor the demand last asked for, which an update can move /// either way after SUBSCRIBE_START answered the SUBSCRIBE. - #[moq_clock::test] + #[kio::test] async fn the_owed_floor_follows_the_demand() { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); let stream = Stream::open(&mut crate::driver::Transport::new(session.clone()), VERSION) @@ -2868,7 +2868,7 @@ mod tests { /// A peer keeping datagrams ready gets a budget of them routed per poll, leaving the /// rest for later so the session's other tasks run in between. - #[moq_clock::test] + #[kio::test] async fn a_flood_of_datagrams_yields() { use crate::transport::poll::Session as _; @@ -2901,7 +2901,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn padding_is_discarded_only_on_lite07() { for version in [ Version::Lite01, @@ -2921,7 +2921,7 @@ mod tests { } /// Both runtimes receive the other's encoded padding and keep the session live. - #[moq_clock::test] + #[kio::test] #[ignore = "requires Bun; run by just test interop"] async fn lite_padding_interop() { for (version, alpn) in [ @@ -2945,7 +2945,7 @@ mod tests { /// A GROUP needs no negotiated extension, so it proceeds before SETUP, or after a /// server's gated accept held it. - #[moq_clock::test] + #[kio::test] async fn early_group_is_delivered() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for pre_read in [false, true] { @@ -3038,7 +3038,7 @@ mod tests { /// A group at or past the end the publisher declared contradicts that end, which no later /// stream can repair, so the whole track fails rather than ending clean without it. lite-05 /// specified an inclusive end, so there it costs only that group's stream. - #[moq_clock::test] + #[kio::test] async fn a_group_past_the_declared_end_aborts_the_track() { use crate::transport::poll::Session as _; @@ -3197,7 +3197,7 @@ mod tests { } /// Object records: `(Skip << 1) | END`, the properties block's length, then the frame. - #[moq_clock::test] + #[kio::test] async fn ietf_records_frame_a_group() { // A plain group: Group State 0, then frame 0 with an empty record. let (res, track, _) = receive_ietf(draft18(None), &[0, 0, 0, 1, u64::from(b'x')]).await; @@ -3217,7 +3217,7 @@ mod tests { } /// A record the Group State does not allow, or bytes past END_OF_GROUP, are refused. - #[moq_clock::test] + #[kio::test] async fn ietf_records_refuse_what_their_group_cannot_hold() { for (body, reason) in [ (&[0x20][..], "an unknown Group State bit"), @@ -3235,7 +3235,7 @@ mod tests { /// A track published over moq-lite has no moq-transport state, so a relayed group on /// one is refused, though its plain groups cross. - #[moq_clock::test] + #[kio::test] async fn ietf_records_need_a_moq_transport_track() { let plain = [0, 0, 0, 1, u64::from(b'x')]; let relayed = [0x1, 0, 0, 1, u64::from(b'x')]; @@ -3249,7 +3249,7 @@ mod tests { /// A relayed group's records carry properties only when its Group State sets EXTENSIONS, /// as the moq-transport subgroup it mirrors could hold none otherwise. - #[moq_clock::test] + #[kio::test] async fn ietf_records_need_extensions_for_properties() { // Object 0 with a draft-18 block holding 0x20 = 1, or an untimed Timestamp. for record in [&[2, 0x20, 1][..], &[2, 0x10, 7]] { @@ -3266,7 +3266,7 @@ mod tests { /// On a timed track, the frame holds an object's time, so a record cannot carry a second, /// mutable Timestamp that could disagree with it. Records that say nothing of time, or /// seal a Timestamp moq-transport egress cannot rewrite, cross beside the frame's. - #[moq_clock::test] + #[kio::test] async fn ietf_records_leave_time_to_their_frame() { let frame = crate::coding::varint::zigzag(500); // Each record after its Object code: Object 0 unless it says otherwise. @@ -3292,7 +3292,7 @@ mod tests { /// A record's properties stay the bytes they arrived as, which the cache charges, rather /// than a decoded list costing many times as much. - #[moq_clock::test] + #[kio::test] async fn ietf_records_hold_properties_at_their_wire_size() { const COUNT: u64 = 1000; // A relayed group's Object 0, whose draft-18 block holds COUNT two-byte properties @@ -3387,7 +3387,7 @@ mod tests { /// Lite-05/06 timestamps may be send times, so a received frame is read past its /// timestamp and lands untimed: nothing rewinds, and the track stays open. - #[moq_clock::test] + #[kio::test] async fn lite06_timestamps_are_dropped() { for version in [Version::Lite05, Version::Lite06] { // Frame 0 at 500ms, before group 4's 1000ms. @@ -3405,7 +3405,7 @@ mod tests { /// Lite-07 timestamps are media time, so a received group is checked like a local /// write and one that rewinds is refused. - #[moq_clock::test] + #[kio::test] async fn a_lite07_rewind_is_refused() { let (res, _track) = receive_group(Version::Lite07, &[500]).await; assert!(matches!(res, Err(Error::TimestampMismatch)), "{res:?}"); @@ -3415,7 +3415,7 @@ mod tests { /// holds one that lite-05/06 could not carry as a group's first frame. lite-06 reaches /// it with a second delta, lite-07 with a first frame its 64-bit varint can encode. /// lite-05/06 drop the timestamp, but a stream carrying one past the bound is still malformed. - #[moq_clock::test] + #[kio::test] async fn a_received_timestamp_past_2_61_is_refused() { let max: i64 = (1 << 61) - 1; for version in [Version::Lite05, Version::Lite06, Version::Lite07] { @@ -3489,7 +3489,7 @@ mod tests { /// An idle copy that resubscribes gets its newest cached group again. That stream only /// duplicates the cache, but lite-07's SUBSCRIBE_END still counts it, so the tail must /// too, or the subscription waits out the grace before it ends. - #[moq_clock::test] + #[kio::test] async fn a_duplicate_group_stream_still_counts_toward_the_end() { use crate::transport::poll::Session as _; @@ -3558,7 +3558,7 @@ mod tests { /// A SUBSCRIBE_END below a group already received contradicts that group. lite-05 /// specified an inclusive end, and `@moq/net` 0.1.3 to 0.1.9 sent one, so there it only /// costs the early boundary; later drafts abort the track. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_end_below_a_received_group() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut responses = Vec::new(); @@ -3702,7 +3702,7 @@ mod tests { /// An answer read only after another instance took the path may be that instance's, /// so the replacement refuses the subscription instead, as does a withdrawal followed /// by a new announcement. - #[moq_clock::test] + #[kio::test] async fn an_answer_read_after_a_replacement_is_refused() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let res = answer_after(version, |selection| selection.replace()).await; @@ -3718,7 +3718,7 @@ mod tests { /// A withdrawal alone leaves the SUBSCRIBE to its answer: the publisher concludes a /// subscription in flight, so a track that finished as its broadcast ended arrives whole. - #[moq_clock::test] + #[kio::test] async fn an_answer_read_after_a_withdrawal_is_kept() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let res = answer_after(version, |selection| selection.withdraw()).await; @@ -3729,7 +3729,7 @@ mod tests { /// Lite-07's SUBSCRIBE_START says where the track is, so a reader knows its largest /// frame before any group arrives. The FIN with no SUBSCRIBE_END then aborts the track, /// and the stream ends with it. - #[moq_clock::test] + #[kio::test] async fn subscribe_start_reports_the_largest() { let version = Version::Lite07; let largest = track::Position { group: 4, frame: 2 }; @@ -3790,7 +3790,7 @@ mod tests { /// A SUBSCRIBE_DROP ends a group still arriving now, with its Error Code on lite-07. /// Earlier versions carry an application code there, so the same bytes read as /// OLD. - #[moq_clock::test] + #[kio::test] async fn a_subscribe_drop_ends_an_arriving_group_with_its_code() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut responses = Vec::new(); @@ -3957,7 +3957,7 @@ mod tests { responses } - #[moq_clock::test] + #[kio::test] async fn bare_fin_requires_subscribe_end() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for (started, clean) in [(false, false), (true, false), (false, true)] { @@ -3966,7 +3966,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] #[ignore = "requires Bun; run by just test bare-fin in interop CI"] async fn bare_fin_interop() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { @@ -3982,7 +3982,7 @@ mod tests { /// Removing a subscription both stops delivery and releases the session's handle /// on the producer, so the track (its cached groups, its stats subscription) ends /// rather than outliving the subscription it belonged to. - #[moq_clock::test] + #[kio::test] async fn unsubscribe_drops_the_datagram_and_releases_the_producer() { let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { @@ -4070,7 +4070,7 @@ mod tests { /// A lite-05 subscribe still waiting on TRACK_INFO is not in the subscribe map. /// Dropping that machine must reject the origin request with the session's error. - #[moq_clock::test] + #[kio::test] async fn session_death_rejects_a_track_waiting_for_info() { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -4117,7 +4117,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn announce_interest_without_credit_keeps_the_session_alive() { use std::sync::atomic::Ordering; for version in [Version::Lite04, Version::Lite07] { @@ -4140,7 +4140,7 @@ mod tests { let mut driver = SubscriberDriver::new(subscriber, Vec::new(), false); assert!(driver.poll(&kio::Waiter::noop()).is_pending()); assert_eq!(log.request_attempts.load(Ordering::Relaxed), 1, "{version}"); - moq_clock::sleep(std::time::Duration::from_secs(20)).await; + kio::clock::sleep(std::time::Duration::from_secs(20)).await; assert!(driver.poll(&kio::Waiter::noop()).is_pending()); assert_eq!( log.request_attempts.load(Ordering::Relaxed), @@ -4152,7 +4152,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn a_claimed_fetch_waits_only_while_wanted() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { for end in ["credit", "unused", "retired"] { @@ -4209,7 +4209,7 @@ mod tests { /// send, or its peer never answers. /// Otherwise every request a relay's front abandons (a failover, a reader leaving) /// holds a task, a stream, and the track until the peer answers, which may be never. - #[moq_clock::test] + #[kio::test] async fn an_unused_track_stops_waiting_for_info() { // A closed gate holds the TRACK request in its send; an open one sends it to a // peer that never answers. @@ -4305,7 +4305,7 @@ mod tests { /// A listing is a subscribe: it waits for a token that may cover the broadcast before /// syncing its readers or asking the peer, which would refuse it until then. - #[moq_clock::test] + #[kio::test] async fn a_listing_waits_for_its_token() { let auth = crate::auth::Link::new(true); let token = auth.present(bytes::Bytes::from_static(b"new"), false).unwrap(); @@ -4332,7 +4332,7 @@ mod tests { /// An instance retired while its listing waits for a token lists nothing: a TRACKS /// request without an epoch would list its replacement. The source ends with it. - #[moq_clock::test] + #[kio::test] async fn a_listing_of_a_retired_instance_never_reaches_the_wire() { let auth = crate::auth::Link::new(true); let token = auth.present(bytes::Bytes::from_static(b"new"), false).unwrap(); @@ -4353,7 +4353,7 @@ mod tests { /// A listing on the wire but unanswered when another instance takes the path lists /// nothing: the peer may list that instance. - #[moq_clock::test] + #[kio::test] async fn an_unanswered_listing_of_a_replaced_instance_is_refused() { let open = kio::Producer::new(true); let session = SinkSession::gated_bi(open.consume()); @@ -4376,7 +4376,7 @@ mod tests { } /// A listing outside the session's scope is refused before it reaches the wire. - #[moq_clock::test] + #[kio::test] async fn a_listing_outside_the_scope_is_refused() { let auth = crate::auth::Link::new(false); auth.handle().authorize(&crate::auth::Grant::default()); @@ -4392,7 +4392,7 @@ mod tests { /// A narrower scope resets a live listing with UNAUTHORIZED rather than keep listing /// what the session no longer allows, and leaves the session up. - #[moq_clock::test] + #[kio::test] async fn a_narrower_limit_resets_a_listing() { let auth = crate::auth::Link::new(false); let open = kio::Producer::new(true); @@ -4416,7 +4416,7 @@ mod tests { /// A track waiting on an unanswered token ends once nobody wants it, rather than /// holding its task and track until a token that may never be answered. - #[moq_clock::test] + #[kio::test] async fn an_unused_track_stops_waiting_for_auth() { let auth = crate::auth::Link::new(true); let _token = auth.present(bytes::Bytes::from_static(b"new"), false).unwrap(); @@ -4471,7 +4471,7 @@ mod tests { /// free to serve twice, and a late insert loses the race with a publisher that /// serves its first group the instant it reads the request (`recv_group` drops a /// group whose id isn't in the map yet). - #[moq_clock::test] + #[kio::test] async fn establish_sends_one_registered_subscribe() { // Writes park until this opens, so the assertions below run at the exact moment // the request would hit the wire. @@ -4538,7 +4538,7 @@ mod tests { /// A narrower limit landing while the SUBSCRIBE is still opening resets it with /// UNAUTHORIZED, like a live one, and releases its id. - #[moq_clock::test] + #[kio::test] async fn a_narrower_limit_resets_a_subscribe_still_opening() { // Writes park, so the SUBSCRIBE is on an open stream but not yet flushed. let gate = kio::Producer::new(false); @@ -4649,13 +4649,13 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn internal_cancel_without_a_recorded_session_end_is_cancel() { let h = Harness::new(VERSION); assert!(matches!(h.serve.subscriber.end_reason(), Error::Cancel)); } - #[moq_clock::test] + #[kio::test] async fn internal_serve_preserves_an_abort_from_a_live_clone() { for dynamic_first in [true, false] { let h = Harness::new(VERSION); @@ -4677,7 +4677,7 @@ mod tests { /// A session that dies hands a live track back with the session's error, but finishes one /// whose subscription the publisher already ended, as the driver's cleanup does. - #[moq_clock::test] + #[kio::test] async fn internal_session_end_gives_back_live_and_finishes_ended() { use crate::transport::poll::Session as _; for ended in [false, true] { @@ -4731,7 +4731,7 @@ mod tests { /// A publisher that finishes the track stops reading its subscribe stream, so a /// SUBSCRIBE_UPDATE written then fails. The track still ends with the publisher's /// finish; a reset still hands it back with the reset's error. - #[moq_clock::test] + #[kio::test] async fn an_update_the_publisher_stopped_reading_defers_to_its_end() { use crate::transport::poll::{RecvStream as _, SendStream as _, Session as _}; for reset in [false, true] { @@ -4799,7 +4799,7 @@ mod tests { /// A PROBE stream the peer ends, by FIN or reset, leaves no estimate behind: the /// session gives up probing, so a held consumer must not keep its last rate. - #[moq_clock::test] + #[kio::test] async fn an_ended_probe_clears_the_estimate() { use crate::transport::poll::{SendStream as _, Session as _}; for reset in [false, true] { @@ -4910,7 +4910,7 @@ mod tests { /// An end of group 0 is the empty range: nothing sorts below it. The wire cannot /// say that, and the nearest thing it can say is "through group 0", which would /// deliver the single group the caller excluded. - #[moq_clock::test] + #[kio::test] async fn an_empty_range_opens_no_subscription() { let mut h = Harness::new(Version::Lite06); let mut sub = Sub::None; @@ -4927,7 +4927,7 @@ mod tests { /// Demand collapsing to nothing cancels the upstream rather than sending a bound /// that means the opposite. - #[moq_clock::test] + #[kio::test] async fn an_empty_range_cancels_a_live_subscription() { let mut h = Harness::new(Version::Lite06); let mut sub = Sub::None; @@ -4955,7 +4955,7 @@ mod tests { /// The wire has no encoding for either: an exclusive end at a group head floors to /// the group below it, so group 5 through group 5 would go out as `start_group = 5`, /// `end_group = 4`, an inverted range the publisher happily parks on. - #[moq_clock::test] + #[kio::test] async fn a_nonzero_empty_range_opens_no_subscription() { let mut h = Harness::new(Version::Lite06); let mut sub = Sub::None; @@ -4972,7 +4972,7 @@ mod tests { /// Demand collapsing to an empty range mid-track cancels the upstream, the same way /// it does at the first position. - #[moq_clock::test] + #[kio::test] async fn a_nonzero_empty_range_cancels_a_live_subscription() { let mut h = Harness::new(Version::Lite06); let mut sub = Sub::None; @@ -4998,7 +4998,7 @@ mod tests { /// sent, such as a lost datagram, never arrived: subscribing again would replay the rest /// and repeat for as long as it stays undeliverable. Ranges an update changed are asked /// again, since the FIN may predate the update. - #[moq_clock::test] + #[kio::test] async fn a_covered_fin_short_of_a_lost_group_resubscribes_only_after_an_update() { for updated in [false, true] { let h = Harness::new(Version::Lite07); @@ -5030,7 +5030,7 @@ mod tests { "{updated}: waits out the grace" ); - moq_clock::sleep(Duration::from_secs(120)).await; + kio::clock::sleep(Duration::from_secs(120)).await; let _ = serving.poll(&h.serve, &kio::Waiter::noop()); assert_eq!(serving.covered.is_some(), !updated, "{updated}"); assert_eq!( @@ -5043,7 +5043,7 @@ mod tests { /// Concurrent joins over the refresh ratio send one SUBSCRIBE_UPDATE upstream, a new /// group past the largest sends the next, and every update restates the latest. - #[moq_clock::test] + #[kio::test] async fn refresh_joins_coalesce_upstream() { let h = Harness::new(Version::Lite07); let request = h._broadcast.reserve_track("refresh").unwrap(); @@ -5100,7 +5100,7 @@ mod tests { /// publisher no longer serves, or clamp one it still does), and an update /// that moves back restores it (the publisher declared that range gone and /// sends no replacement START). - #[moq_clock::test] + #[kio::test] async fn buffered_start_applies_iff_demand_matches() { let mut h = Harness::new(Version::Lite05); let mut sub = Sub::None; @@ -5147,7 +5147,7 @@ mod tests { /// that moves the start forward retires the skipped range (the publisher /// stops serving it and no fresh START says so), one that moves it backward /// reopens it, and dropping to the live edge clears it entirely. - #[moq_clock::test] + #[kio::test] async fn updates_move_the_declared_floor_both_ways() { let mut h = Harness::new(Version::Lite05); let mut sub = Sub::None; @@ -5189,7 +5189,7 @@ mod tests { /// an announce id to it: dropping it silently leaves that id pointing at a path /// owned by the earlier announce, and the `ANNOUNCE_END` that follows retires the /// wrong route. - #[moq_clock::test] + #[kio::test] async fn a_double_announce_is_an_error_even_when_reflected() { let assigned = crate::Hop::new(777).unwrap(); let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -5245,7 +5245,7 @@ mod tests { /// A serve pass polls only the routes whose request queue woke. The driver runs a /// pass on every wake, which is once per group the session carries, so polling /// every announced route there made each group cost the whole announce set. - #[moq_clock::test] + #[kio::test] async fn a_request_readies_only_its_route() { let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { @@ -5284,7 +5284,7 @@ mod tests { assert!(announced.ready.is_empty()); let consumer = origin.consume(); - let request = moq_clock::sim::spawn(async move { consumer.request("room/7", None).await }); + let request = kio::clock::sim::spawn(async move { consumer.request("room/7", None).await }); let ready = kio::wait(|waiter| announced.ready.poll_pop(waiter)).await.unwrap(); assert_eq!(ready.as_str(), "room/7"); @@ -5299,7 +5299,7 @@ mod tests { /// A source minted under a claim goes once nothing holds it: the front that read it /// ended, so the session keeps nothing for the path, and a later request asks the /// route afresh. Withdrawing the claim still closes a source in use at once. - #[moq_clock::test] + #[kio::test] async fn an_unheld_source_is_retired() { let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { @@ -5336,7 +5336,7 @@ mod tests { announced: &mut Announced, ) -> (crate::broadcast::Consumer, SourceServe) { let consumer = origin.consume(); - let request = moq_clock::sim::spawn(async move { consumer.request("pool/p", None).await }); + let request = kio::clock::sim::spawn(async move { consumer.request("pool/p", None).await }); let ready = kio::wait(|waiter| announced.ready.poll_pop(waiter)).await.unwrap(); announced.ready.try_push(ready).unwrap(); announced.poll_serve(subscriber, &kio::Waiter::noop()); @@ -5351,7 +5351,7 @@ mod tests { // The requester leaves without reading: its front ends, and the source with it. drop(resolved); - moq_clock::timeout( + kio::clock::timeout( std::time::Duration::from_secs(1), kio::wait(|waiter| kio::Task::poll(&mut serve, waiter)), ) @@ -5368,7 +5368,7 @@ mod tests { /// A track read before the minted source's serve machine first runs queues for that /// machine, rather than the front finding no handler and ending the track `NotFound`. - #[moq_clock::test] + #[kio::test] async fn a_track_read_before_its_source_is_served_queues() { let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { @@ -5398,7 +5398,7 @@ mod tests { announced.poll_serve(&subscriber, &kio::Waiter::noop()); let consumer = origin.consume(); - let request = moq_clock::sim::spawn(async move { consumer.request("pool/p", None).await }); + let request = kio::clock::sim::spawn(async move { consumer.request("pool/p", None).await }); let ready = kio::wait(|waiter| announced.ready.poll_pop(waiter)).await.unwrap(); announced.ready.try_push(ready).unwrap(); announced.poll_serve(&subscriber, &kio::Waiter::noop()); @@ -5407,7 +5407,7 @@ mod tests { // The front asks the source for the track while its serve machine is still queued. let track = resolved.track("video").unwrap(); let _subscribing = track.subscribe(None); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; let minted = subscriber.sources.try_pop().unwrap().expect("a source was minted"); let mut serve = SourceServe::new(subscriber.clone(), minted); @@ -5423,7 +5423,7 @@ mod tests { /// the path reads as free, a later announce takes it, and the declined one's /// `ANNOUNCE_END` retires that route instead. This walks a reflection: the chain /// already names this session. - #[moq_clock::test] + #[kio::test] async fn every_declined_announce_is_recorded() { let assigned = crate::Hop::new(777).unwrap(); let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -5481,7 +5481,7 @@ mod tests { } /// A dropped announce still holds its path until the peer retracts it. - #[moq_clock::test] + #[kio::test] async fn a_dropped_announce_still_holds_its_path() { let assigned = crate::Hop::new(777).unwrap(); let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -5539,7 +5539,7 @@ mod tests { /// Appending it again would name one identity twice, which is tolerated in a lite /// chain but is a PROTOCOL_VIOLATION for an IETF peer the route is later forwarded /// to, so the route must never enter the model carrying it. - #[moq_clock::test] + #[kio::test] async fn an_announce_reflected_by_its_sender_is_dropped() { let assigned = crate::Hop::new(777).unwrap(); @@ -5576,7 +5576,7 @@ mod tests { .unwrap(); assert!(!accepted, "a chain naming its own sender must not become a route"); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_none()); } @@ -5584,7 +5584,7 @@ mod tests { /// origin's hop in the chain is a reflection, not a new path. The announce /// is dropped, the local front keeps serving, and the peer's own /// subscription (split-horizon excluded) still reads from it. - #[moq_clock::test] + #[kio::test] async fn a_reflected_announce_does_not_displace_the_local_front() { let relay = crate::Hop::new(1).unwrap(); let origin = origin::Config::new(relay).produce(); @@ -5665,7 +5665,7 @@ mod tests { /// A peer that declares no identity is marked anonymous (hop 0). The assigned /// identity stays on `via` for split-horizon and is never written into the chain. - #[moq_clock::test] + #[kio::test] async fn assigned_peer_hop_attributes_announces() { let session = SinkSession::new(Default::default()); let assigned = crate::Hop::new(777).unwrap(); @@ -5714,7 +5714,7 @@ mod tests { /// Lite03 hop-count placeholders stay 0 and count as anonymous; they are not /// rewritten with the assigned identity. - #[moq_clock::test] + #[kio::test] async fn lite03_placeholders_stay_anonymous() { let assigned = crate::Hop::new(777).unwrap(); let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); @@ -5758,7 +5758,7 @@ mod tests { /// A publisher that names nobody keeps the anonymous mark, and nothing in front of it: /// identity is the epoch's job, so the relay never names the publisher itself. A /// reprice on the same connection keeps it and updates in place. - #[moq_clock::test] + #[kio::test] async fn an_unnamed_publisher_stays_anonymous() { let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default())); @@ -5776,7 +5776,7 @@ mod tests { .unwrap(); let mut cursor = consumer.announced(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let route = cursor.expect_next_active("room/host").await; let hops: Vec<_> = route.hops.iter().copied().collect(); assert_eq!(hops, vec![crate::Hop::UNKNOWN]); @@ -5792,7 +5792,7 @@ mod tests { &mut announced, ) .unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let route = cursor.expect_next_active("room/host").await; let hops: Vec<_> = route.hops.iter().copied().collect(); assert_eq!(hops, vec![crate::Hop::UNKNOWN]); @@ -5818,7 +5818,7 @@ mod tests { /// A takeover in place keeps the sources the predecessor minted open: they serve the /// instance it continues. A restart in place closes them. - #[moq_clock::test] + #[kio::test] async fn a_takeover_in_place_keeps_the_predecessors_sources() { for takeover in [true, false] { let (mut subscriber, _consumer) = restart_subscriber(SinkSession::new(Default::default())); @@ -5865,7 +5865,7 @@ mod tests { /// A restart re-prices the announced route in place: consumers observe another /// active update with the new metadata rather than a retract-and-announce. - #[moq_clock::test] + #[kio::test] async fn restart_updates_the_route_in_place() { let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default())); @@ -5884,7 +5884,7 @@ mod tests { .unwrap(); let mut cursor = consumer.announced(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; cursor.expect_next_active("room/host").await; subscriber @@ -5898,14 +5898,14 @@ mod tests { ) .unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let route = cursor.expect_next_active("room/host").await; assert_eq!(route.cost, crate::origin::Cost::new(5).charged(0)); } /// A restart is held to the subscribe limit like a start: one the limit no longer /// covers is withheld, ending the old instance rather than attaching the new one. - #[moq_clock::test] + #[kio::test] async fn a_restart_outside_the_limit_is_withheld() { let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default())); let auth = subscriber.auth.clone(); @@ -5953,7 +5953,7 @@ mod tests { /// This falls out of `Announced` being a local whose announcements drop, /// which is exactly what makes it worth pinning: a refactor that hoisted the map /// to the session (outliving the stream) would leak the announcement instead. - #[moq_clock::test] + #[kio::test] async fn a_lost_announce_stream_retracts_the_route() { let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); let consumer = origin.consume(); @@ -6014,7 +6014,7 @@ mod tests { /// An unknown announce type between two starts is skipped without ending the /// stream. - #[moq_clock::test] + #[kio::test] async fn an_unknown_announce_type_keeps_the_stream() { const VERSION: Version = Version::Lite06; let start = |suffix| lite::AnnounceBroadcast::Active { @@ -6133,7 +6133,7 @@ mod tests { /// A peer streaming announces gets a budget of them read per poll, so the session's /// other tasks run between them, and the announce behind the flood still arrives. - #[moq_clock::test] + #[kio::test] async fn a_flood_of_announces_yields() { const VERSION: Version = Version::Lite06; /// `AnnouncePrefix`'s announces per poll. @@ -6163,7 +6163,7 @@ mod tests { } /// The origin's consumers sync once the counted starts are in and read, never before. - #[moq_clock::test] + #[kio::test] async fn a_counted_initial_set_catches_up() { const VERSION: Version = Version::Lite06; let script = announce_script( @@ -6193,7 +6193,7 @@ mod tests { } /// Part of a counted set is not synced, however much of it was read. - #[moq_clock::test] + #[kio::test] async fn a_partial_initial_set_holds() { const VERSION: Version = Version::Lite06; let script = announce_script(VERSION, &[&announce_ok(VERSION, 2), &announce_start(VERSION, "a")]); @@ -6207,7 +6207,7 @@ mod tests { } /// An empty lite-07 set waits for the ordered SYNCED event. - #[moq_clock::test] + #[kio::test] async fn an_empty_initial_set_catches_up_at_once() { const VERSION: Version = Version::Lite07; let synced = |w: &mut crate::coding::Encoder<'_>| lite::AnnounceBroadcast::Synced.encode(w, VERSION).unwrap(); @@ -6221,7 +6221,7 @@ mod tests { /// A complete body cannot be repaired by bytes from the next announcement. /// Keep the peer stream open: FIN must not be what discovers the malformed body. - #[moq_clock::test] + #[kio::test] async fn malformed_complete_announce_closes_before_more_bytes() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut script = announce_script(version, &[&announce_ok(version, 1)]); @@ -6242,7 +6242,7 @@ mod tests { } /// Only an incomplete outer frame waits, then resumes on its missing byte. - #[moq_clock::test] + #[kio::test] async fn an_incomplete_announce_waits_for_its_body() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { let mut script = announce_script(version, &[&announce_ok(version, 1), &announce_start(version, "room")]); @@ -6260,7 +6260,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn a_duplicate_synced_is_refused() { const VERSION: Version = Version::Lite07; let synced = |w: &mut crate::coding::Encoder<'_>| lite::AnnounceBroadcast::Synced.encode(w, VERSION).unwrap(); @@ -6271,7 +6271,7 @@ mod tests { } /// Anything but a start inside the counted set cuts it short: a protocol violation. - #[moq_clock::test] + #[kio::test] async fn an_end_inside_the_initial_set_is_refused() { const VERSION: Version = Version::Lite06; let end = @@ -6286,7 +6286,7 @@ mod tests { } /// The stream ending inside the counted set cuts it short too. - #[moq_clock::test] + #[kio::test] async fn a_fin_inside_the_initial_set_is_refused() { const VERSION: Version = Version::Lite06; let script = announce_script(VERSION, &[&announce_ok(VERSION, 2), &announce_start(VERSION, "a")]); @@ -6298,7 +6298,7 @@ mod tests { } /// Lite03/04 mark no initial set: synced, best effort, once the request is sent. - #[moq_clock::test] + #[kio::test] async fn an_unmarked_version_catches_up_on_the_request() { const VERSION: Version = Version::Lite04; let (mut prefix, consumer) = @@ -6311,7 +6311,7 @@ mod tests { } /// Lite01/02 mark the initial set with ANNOUNCE_INIT. - #[moq_clock::test] + #[kio::test] async fn announce_init_is_the_initial_set() { const VERSION: Version = Version::Lite02; let init = |w: &mut crate::coding::Encoder<'_>| { @@ -6335,7 +6335,7 @@ mod tests { /// An announce past the session's cap fails the session with TOO_MANY_REQUESTS, and /// the stream gives its slots back once the session drops it. - #[moq_clock::test] + #[kio::test] async fn announces_past_the_cap_close_the_session() { const VERSION: Version = Version::Lite06; let start = |suffix| lite::AnnounceBroadcast::Active { @@ -6391,7 +6391,7 @@ mod tests { } /// Distinct live GROUP starts are copies of the same group, including while /// readers retain every earlier tail. Exercise the real header/ingest path. - #[moq_clock::test] + #[kio::test] async fn live_group_tails_share_content_held_by_earlier_readers() { use crate::transport::poll::Session as _; let version = Version::Lite07; diff --git a/rs/moq-net/src/model/bandwidth.rs b/rs/moq-net/src/model/bandwidth.rs index 7c718debe14..7e6e3383fa9 100644 --- a/rs/moq-net/src/model/bandwidth.rs +++ b/rs/moq-net/src/model/bandwidth.rs @@ -936,7 +936,7 @@ mod tests { /// The headline case: two encoders on one connection must not each target the /// whole estimate. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn concurrent_tracks_split_the_estimate() { let estimate = Producer::new(); @@ -989,7 +989,7 @@ mod tests { /// Demand transitions have to wake a parked share, not just change what a later /// `peek` would see; the encoder is sitting in a `select!` on `changed`. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_share_wakes_when_a_sibling_goes_idle() { let estimate = Producer::new(); @@ -1050,7 +1050,7 @@ mod tests { /// waker armed. Reservations cap the slice, so most estimate changes don't reach /// it, and a poll that returned the value without arming anything would park the /// encoder with nothing left to wake it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_unchanged_slice_keeps_watching_the_estimate() { let estimate = Producer::new(); @@ -1077,7 +1077,7 @@ mod tests { } /// The same, for the other input: a sibling's demand. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_parked_share_is_woken_by_sibling_demand() { let estimate = Producer::new(); @@ -1103,7 +1103,7 @@ mod tests { /// A share follows the estimate's own lifecycle: unavailable while disconnected /// (hold the current rate), terminal once the session is gone for good. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_share_follows_the_estimate_lifecycle() { let estimate = Producer::new(); @@ -1147,7 +1147,7 @@ mod tests { /// Dropping the reservation hands the room back. The registry only ever prunes /// tracks that have *closed*, so a claim left behind by a track that is still /// publishing would stand for the rest of the connection. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_a_reservation_releases_it() { let estimate = Producer::new(); @@ -1249,7 +1249,7 @@ mod tests { /// A reader parked on `changed` has to be woken by its own reservation moving, not /// just by the estimate or a sibling: the encoder is sitting in a `select!` on it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn update_wakes_a_parked_reader() { let estimate = Producer::new(); @@ -1272,7 +1272,7 @@ mod tests { /// The registry is the allocator's, not a share's: a share that outlives every /// allocator reports the estimate as gone rather than keeping the channel open. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_share_outliving_the_allocator_reports_closed() { let estimate = Producer::new(); @@ -1292,7 +1292,7 @@ mod tests { /// holds its rate for the former and stops watching for the latter. /// Reporting closure as `Ok(None)` would spin any `select!` over `changed()`, /// because a closed channel is always immediately ready. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn closed_is_distinct_from_unavailable() { let producer = Producer::new(); diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index c5448c264f5..d4b2d6ff4f4 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -1704,7 +1704,7 @@ mod test { }}; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn insert() { let mut producer = Info::new().produce(); @@ -1730,7 +1730,7 @@ mod test { track2_consumer.assert_group(); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn closed() { let mut producer = Info::new().produce(); @@ -1759,7 +1759,7 @@ mod test { } /// `close()` ends the broadcast for every clone at once, and a second close is a no-op. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_ends_every_clone() { let producer = Info::new().produce(); @@ -1776,7 +1776,7 @@ mod test { } /// Dropping the last producer ends the broadcast exactly like `close()`. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn drop_ends_like_close() { let producer = Info::new().produce(); @@ -1786,7 +1786,7 @@ mod test { assert!(matches!(consumer.track("video"), Err(Error::Unroutable))); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn requests() { let mut producer = Info::new().produce().requests(); @@ -1827,7 +1827,7 @@ mod test { assert!(track5.is_err(), "should have errored"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn stale_producer() { let mut broadcast = Info::new().produce().requests(); @@ -1916,7 +1916,7 @@ mod test { assert!(state.tracks.len() < 16, "{} names retained", state.tracks.len()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn requested_unused() { let mut broadcast = Info::new().produce().requests(); @@ -1970,7 +1970,7 @@ mod test { /// ever sees the (now-taken) name. Without this the requester is stranded: /// the name exists the moment the track does, so the queue entry could /// never be served under it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn create_track_fulfills_queued_request() { let producer = Info::new().produce(); @@ -2044,7 +2044,7 @@ mod test { /// end. Ending the broadcast is where it does: `Consumer::track` answers /// `Unroutable` for a name asked about after this point, so whoever asked earlier gets /// the same answer instead of waiting on info that can never arrive. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_resolves_a_reserved_name() { let producer = Info::new().produce(); @@ -2059,7 +2059,7 @@ mod test { /// A request still queued for a handler is the same parking case reached from the /// consumer side, so it ends the same way. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_resolves_a_queued_request() { let producer = Info::new().produce(); @@ -2075,7 +2075,7 @@ mod test { /// A queued request answers the same when the broadcast ends by its last handle /// dropping, even when that handle is the `Requests` that would have served it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_the_last_handle_resolves_a_queued_request() { let dynamic = Info::new().produce().requests(); @@ -2090,7 +2090,7 @@ mod test { /// A source that no longer names the instance that minted it takes no new track, even /// from a handler that checks nothing: its request stream ends and every later request /// answers `Unroutable`, while the track it accepted earlier runs on. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_lapsed_source_refuses_new_tracks() { let route = kio::Producer::new(()); @@ -2116,7 +2116,7 @@ mod test { /// With a producer still alive, losing the last handler is not the broadcast ending: /// the queued request fails as `Dropped`. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_the_last_handler_resolves_a_queued_request_dropped() { let producer = Info::new().produce(); @@ -2133,7 +2133,7 @@ mod test { /// A request a handler already took is the handler's to answer: it may be in flight /// to a peer, and a retraction does not disturb subscriptions already in flight. /// Whatever the handler decides still reaches the consumer. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_leaves_a_claimed_request_to_its_handler() { let producer = Info::new().produce(); @@ -2166,7 +2166,7 @@ mod test { /// accepted, but it does not create a live publisher. Closing the broadcast /// must still reject that name so an arrival-order subscriber does not park on /// backfill that is deliberately absent from its queue. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_resolves_an_unaccepted_track_with_fetched_info() { let producer = Info::new().produce(); @@ -2191,7 +2191,7 @@ mod test { /// A staged track resolves no subscriber until it commits, and then with what was /// written meanwhile. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_staged_track_resolves_subscribers_at_commit() { let producer = Info::new().produce(); @@ -2202,7 +2202,7 @@ mod test { let mut staged = request.stage(crate::track::Info::timed()); staged.write_frame(crate::Timestamp::ZERO, b"x".as_slice()).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; assert!(futures::poll!(subscribing.as_mut()).is_pending(), "still staged"); let _track = staged.commit(); @@ -2212,7 +2212,7 @@ mod test { /// Dropping a staged track uncommitted rejects the request, so its subscribers fail /// rather than wait on a track nobody will publish. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_a_staged_track_rejects_the_request() { let producer = Info::new().produce(); @@ -2228,7 +2228,7 @@ mod test { /// Dropping a staged track uncommitted aborts a group still being written through it, so /// its writer fails rather than fill a track nobody will read. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_a_staged_track_aborts_its_open_groups() { let producer = Info::new().produce(); @@ -2242,7 +2242,7 @@ mod test { /// Ending the broadcast doesn't cascade into a track someone is publishing: it keeps /// its cache and its publisher decides when it ends. Only a new lookup is refused. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_spares_a_served_track() { let producer = Info::new().produce(); @@ -2262,7 +2262,7 @@ mod test { /// The publisher may still be holding the `track::Request` for a name the broadcast /// just gave up on. Accepting it afterwards must not resurrect the track, or a /// subscriber that was told `Unroutable` could be contradicted by a later one. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn close_leaves_a_stale_reservation_inert() { let producer = Info::new().produce(); @@ -2284,7 +2284,7 @@ mod test { /// Dropping a `track::Request` is not a verdict about the name, so it resolves as /// `Dropped` (a handler lost to a crashed publisher or a dead transport), never as /// `NotFound`. Only an explicit rejection may claim the track is absent. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_a_reserved_request_resolves_dropped() { let producer = Info::new().produce(); @@ -2300,7 +2300,7 @@ mod test { /// `track::Request::reject` carries its reason the same way, which is what lets a /// subscriber tell "no such track" from "the publisher went away". - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn rejecting_a_reserved_request_carries_the_reason() { let producer = Info::new().produce(); @@ -2319,7 +2319,7 @@ mod test { /// teardown commits. The returning viewer keeps the track alive, and once it /// really does commit the cached handle is reclaimed rather than handed out /// cancelled. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_idle_teardown_yields_to_a_returning_viewer() { let producer = Info::new().produce(); diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index ceb63b1aa50..4ba981694f1 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -1421,17 +1421,17 @@ mod test { /// Wall time can lead a lagging driver's sample, while another driver can supply /// future time. Neither a new driver nor a backward sample may rewind expiration. - #[moq_clock::test] + #[kio::test] async fn wall_deadlines_use_the_later_of_ambient_and_driven_time() { let pool = Pool::unbounded(); - let now = moq_clock::now(); + let now = kio::clock::now(); let waiter = kio::Waiter::noop(); pool.poll(now, &waiter); let track = Track::new(pool.clone(), Default::default(), kio::Weak::new()); let (read, reading) = flag(); let at = now + Duration::from_secs(1); track.watch_wall(at, &reading); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(pool.poll(now, &waiter), None); assert!(read.0.swap(false, Ordering::SeqCst), "ambient time was ignored"); diff --git a/rs/moq-net/src/model/clock.rs b/rs/moq-net/src/model/clock.rs index 711cc475444..3b2276f10a5 100644 --- a/rs/moq-net/src/model/clock.rs +++ b/rs/moq-net/src/model/clock.rs @@ -15,7 +15,7 @@ use rand::RngExt; /// The current instant on the model's clock. pub(super) fn now() -> crate::time::Instant { - moq_clock::now() + kio::clock::now() } /// The instant a cache judges wall-clock staleness by, before the time its drivers @@ -25,16 +25,16 @@ pub(super) fn now() -> crate::time::Instant { /// staleness along with the drivers it supplies time to. #[cfg(not(test))] pub(super) fn wall() -> crate::time::Instant { - moq_clock::now() + kio::clock::now() } /// Unit tests freeze the wall clock, so only time a test supplies moves it: the -/// simulated clock inside `moq_clock::sim`, or a pool stepped by hand outside it. +/// simulated clock inside `kio::clock::sim`, or a pool stepped by hand outside it. #[cfg(test)] pub(super) fn wall() -> crate::time::Instant { - static FROZEN: LazyLock = LazyLock::new(moq_clock::now); - match moq_clock::sim::is_running() { - true => moq_clock::now(), + static FROZEN: LazyLock = LazyLock::new(kio::clock::now); + match kio::clock::sim::is_running() { + true => kio::clock::now(), false => *FROZEN, } } @@ -47,9 +47,9 @@ pub(super) fn wall() -> crate::time::Instant { /// deters using it as a wall clock and catches implementations that assume /// unrelated broadcasts are synchronized. pub(super) fn anchor() -> (crate::time::Instant, Duration) { - static ANCHORS: LazyLock>> = + static ANCHORS: LazyLock>> = LazyLock::new(Default::default); - let (instant, wall) = moq_clock::origin(); + let (instant, wall) = kio::clock::origin(); let mut anchors = ANCHORS.lock().unwrap(); let offset = *anchors.entry((instant, wall)).or_insert_with(|| { let jitter = Duration::from_millis(rand::rng().random_range(1..69_420)); @@ -63,9 +63,9 @@ pub(super) fn anchor() -> (crate::time::Instant, Duration) { /// Counting from 50 years after the Unix epoch keeps the value ~1.5e12 ms smaller, /// trimming a byte or two off the first frame's varint. Saturates to zero on a wall /// clock set before 2020 (an unsynced clock), since only a non-negative start matters. -fn offset(wall: moq_clock::Wall, jitter: Duration) -> Duration { +fn offset(wall: kio::clock::Wall, jitter: Duration) -> Duration { const EPOCH: Duration = Duration::from_secs(1_577_836_800); - wall.saturating_duration_since(moq_clock::Wall::UNIX_EPOCH) + wall.saturating_duration_since(kio::clock::Wall::UNIX_EPOCH) .saturating_sub(EPOCH) .saturating_sub(jitter) } @@ -79,7 +79,7 @@ mod tests { #[test] fn unit_tests_freeze_the_cache_clock() { let frozen = wall(); - while moq_clock::now() <= frozen { + while kio::clock::now() <= frozen { std::hint::spin_loop(); } assert_eq!(wall(), frozen); @@ -87,11 +87,11 @@ mod tests { #[test] fn each_ambient_clock_owns_its_wall_anchor() { - let first = moq_clock::sim::run(async { anchor() }); - let second = moq_clock::sim::run(async { - moq_clock::sim::step_wall(moq_clock::Manual::WALL_START + Duration::from_secs(86_400)); + let first = kio::clock::sim::run(async { anchor() }); + let second = kio::clock::sim::run(async { + kio::clock::sim::step_wall(kio::clock::Manual::WALL_START + Duration::from_secs(86_400)); let before = anchor(); - moq_clock::sim::step_wall(moq_clock::Manual::WALL_START - Duration::from_secs(86_400)); + kio::clock::sim::step_wall(kio::clock::Manual::WALL_START - Duration::from_secs(86_400)); assert_eq!( anchor(), before, diff --git a/rs/moq-net/src/model/follow.rs b/rs/moq-net/src/model/follow.rs index 687e5f7c6fa..cb9eb33396d 100644 --- a/rs/moq-net/src/model/follow.rs +++ b/rs/moq-net/src/model/follow.rs @@ -312,7 +312,7 @@ mod tests { /// The follower's next event, which must arrive within the origin's update hold. async fn followed(follow: &mut Follow) -> (&'static str, String) { - let event = moq_clock::timeout(Duration::from_secs(1), follow.next()) + let event = kio::clock::timeout(Duration::from_secs(1), follow.next()) .await .expect("no event") .expect("the origin closed"); @@ -327,7 +327,7 @@ mod tests { /// The follower stays quiet past the origin's update hold. async fn quiet(follow: &mut Follow) { - if let Ok(event) = moq_clock::timeout(Duration::from_secs(1), follow.next()).await { + if let Ok(event) = kio::clock::timeout(Duration::from_secs(1), follow.next()).await { panic!("expected nothing, got {event:?}"); } } @@ -336,7 +336,7 @@ mod tests { Route::default().with_epoch(epoch.clone()) } - #[moq_clock::test] + #[kio::test] async fn follow_reports_the_route_serving_the_path() { let origin = Hop::new(1).unwrap().produce(); let mut follow = origin.consume().routes("pool/job").unwrap(); @@ -375,7 +375,7 @@ mod tests { /// A follower that joins late starts on the route serving the path, not on whichever /// covering route the replay happened to reach first. - #[moq_clock::test] + #[kio::test] async fn follow_starts_on_the_serving_route_when_joining_late() { let origin = Hop::new(1).unwrap().produce(); let _pool = origin.requests_route("pool", Route::default(), None).unwrap(); @@ -388,7 +388,7 @@ mod tests { /// A gap with nothing serving the path ends any request on it, so a covering route that /// arrives after it is a start of its own, even under the same epoch. - #[moq_clock::test] + #[kio::test] async fn follow_keeps_a_gap_between_routes_of_one_epoch() { let origin = Hop::new(1).unwrap().produce(); let epoch = Epoch::mint(); @@ -412,7 +412,7 @@ mod tests { /// A prefix that started before the serving route's last change stood before the route's /// end, so it takes over in place even when the cursor never ran dry in between. - #[moq_clock::test] + #[kio::test] async fn follow_hands_over_to_a_prefix_that_started_before_the_last_change() { let origin = Hop::new(1).unwrap().produce(); let exact = origin.publish("pool/job", route(&Epoch::mint())).unwrap(); @@ -429,7 +429,7 @@ mod tests { } /// Without an epoch nothing says two routes serve the same bytes. - #[moq_clock::test] + #[kio::test] async fn follow_restarts_onto_a_more_specific_route_without_an_epoch() { let origin = Hop::new(1).unwrap().produce(); let mut follow = origin.consume().routes("pool/job").unwrap(); @@ -443,7 +443,7 @@ mod tests { /// A route whose claim covers only paths beneath the followed one never serves it, so it /// cannot mask the route that does, even when it would win the prefix on cost. - #[moq_clock::test] + #[kio::test] async fn follow_ignores_a_route_scoped_beneath_the_path() { let origin = Hop::new(1).unwrap().produce(); let chat = Patterns::from("room/*/chat".parse::().unwrap()); @@ -455,7 +455,7 @@ mod tests { let mut follow = origin.consume().routes("room/alice").unwrap(); let first = origin.publish("room/alice", Route::default().with_cost(5)).unwrap(); - let event = moq_clock::timeout(Duration::from_secs(1), follow.next()) + let event = kio::clock::timeout(Duration::from_secs(1), follow.next()) .await .unwrap() .unwrap(); @@ -467,7 +467,7 @@ mod tests { // A republish is another instance of the route that serves the path. let _second = origin.publish("room/alice", Route::default().with_cost(5)).unwrap(); drop(first); - let event = moq_clock::timeout(Duration::from_secs(1), follow.next()) + let event = kio::clock::timeout(Duration::from_secs(1), follow.next()) .await .unwrap() .unwrap(); @@ -479,7 +479,7 @@ mod tests { /// The next instance handed out, which must arrive within the origin's update hold. async fn available(announced: &mut Following) -> broadcast::Consumer { - moq_clock::timeout(Duration::from_secs(1), announced.available()) + kio::clock::timeout(Duration::from_secs(1), announced.available()) .await .expect("no instance") .expect("the wait failed") @@ -488,7 +488,7 @@ mod tests { /// Nothing more is handed out past the origin's update hold. async fn none(announced: &mut Following) { let hold = super::super::origin_impl::DEFAULT_UPDATE_HOLD * 2; - if let Ok(result) = moq_clock::timeout(hold, announced.available()).await { + if let Ok(result) = kio::clock::timeout(hold, announced.available()).await { panic!( "expected nothing, got {:?}", result.map(|broadcast| broadcast.info().epoch.clone()) @@ -498,7 +498,7 @@ mod tests { /// The next request a dynamic route receives for its path. async fn requested(dynamic: &crate::origin::Requests) -> crate::origin::Request { - moq_clock::timeout(Duration::from_secs(1), dynamic.requested_broadcast()) + kio::clock::timeout(Duration::from_secs(1), dynamic.requested_broadcast()) .await .expect("never asked") .expect("the route closed") @@ -506,7 +506,7 @@ mod tests { /// Another instance taking over while a wait resolves is the one it hands out, so the /// restart the origin holds for it must not hand it out again while the caller holds it. - #[moq_clock::test] + #[kio::test] async fn announced_hands_out_a_held_takeover_once() { let origin = Hop::new(1).unwrap().produce(); let dynamic = origin.requests("live").unwrap(); @@ -522,7 +522,7 @@ mod tests { /// The follower holds what it handed out weakly: a takeover the caller let go of retires, /// and the restart the origin held for it hands out a fresh front. - #[moq_clock::test] + #[kio::test] async fn announced_hands_out_a_dropped_takeover_again() { let origin = Hop::new(1).unwrap().produce(); let dynamic = origin.requests("live").unwrap(); @@ -542,7 +542,7 @@ mod tests { /// The route a wait resolves through leaving, and another instance arriving before it /// resolves, reach the follower as an end and a start alongside the answer. That start must /// not hand the newcomer out again. - #[moq_clock::test] + #[kio::test] async fn announced_hands_out_a_gap_while_resolving_once() { let origin = Hop::new(1).unwrap().produce(); let dynamic = origin.requests("").unwrap(); @@ -551,7 +551,7 @@ mod tests { let (_arrival, _publish) = futures::join!(available(&mut announced), async { let _unanswered = requested(&dynamic).await; drop(dynamic); - moq_clock::sleep(super::super::origin_impl::DEFAULT_UPDATE_HOLD * 2).await; + kio::clock::sleep(super::super::origin_impl::DEFAULT_UPDATE_HOLD * 2).await; origin.publish("live", Route::default()).unwrap() }); none(&mut announced).await; @@ -560,7 +560,7 @@ mod tests { /// An end is a gap that ended every request on the old route, even when a route above the /// path with the same epoch carries the instance on. So the instance serving the path /// afterwards is handed out again, though it is the one the caller still holds. - #[moq_clock::test] + #[kio::test] async fn announced_hands_out_the_instance_again_after_an_end() { let origin = Hop::new(1).unwrap().produce(); let epoch = Epoch::mint(); @@ -579,7 +579,7 @@ mod tests { /// An announced request that pins an epoch refuses another instance taking over instead of /// following it. - #[moq_clock::test] + #[kio::test] async fn announced_pinned_refuses_another_instance() { let origin = Hop::new(1).unwrap().produce(); let epoch = Epoch::mint(); @@ -597,7 +597,7 @@ mod tests { assert_ne!(current.info().epoch.as_ref(), Some(&epoch)); } - #[moq_clock::test] + #[kio::test] async fn announced_pinned_hands_out_its_instance_after_a_gap() { let origin = Hop::new(1).unwrap().produce(); let epoch = Epoch::mint(); @@ -610,13 +610,13 @@ mod tests { assert_eq!(available(&mut announced).await.info().epoch.as_ref(), Some(&epoch)); } - #[moq_clock::test] + #[kio::test] async fn announced_reports_a_dropped_prepared_answer() { let origin = Hop::new(1).unwrap().produce(); let claim = origin.requests("live").unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (result, ()) = futures::join!( - moq_clock::timeout(Duration::from_secs(1), announced.available()), + kio::clock::timeout(Duration::from_secs(1), announced.available()), async { let prepared = requested(&claim).await.prepare(Epoch::mint()).unwrap(); drop(prepared); diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 4c78092c333..7e34950a582 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -5412,7 +5412,7 @@ mod test { /// a write guard was mutably accessed, so `frame_notify` must mark the guard /// modified; a guard dropped untouched wakes nobody and the reader would /// stall until the frame completed. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn chunk_write_wakes_parked_reader() { let producer = Info { sequence: 0 }.produce(); @@ -5424,11 +5424,11 @@ mod test { }) .unwrap(); let mut f = consumer.next_frame().await.unwrap().unwrap(); - let handle = moq_clock::sim::spawn(async move { f.read_chunk().await }); + let handle = kio::clock::sim::spawn(async move { f.read_chunk().await }); // Let the reader park on the empty partial before the chunk lands. - moq_clock::sleep(std::time::Duration::from_millis(50)).await; + kio::clock::sleep(std::time::Duration::from_millis(50)).await; frame.write(Bytes::from_static(b"foo")).unwrap(); - let chunk = moq_clock::timeout(std::time::Duration::from_secs(2), handle) + let chunk = kio::clock::timeout(std::time::Duration::from_secs(2), handle) .await .expect("parked chunk reader was never woken by the chunk write") .unwrap() @@ -5438,16 +5438,16 @@ mod test { /// Each frame is stamped when its last byte lands, whichever way it is written, and /// readers see that stamp however late they read. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn frames_carry_when_they_landed() { use std::time::Duration; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut producer = Info { sequence: 0 }.produce(); producer.write_frame(Timestamp::ZERO, Bytes::from_static(b"a")).unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; let mut chunked = producer .create_frame(frame::Info { size: 2, @@ -5455,23 +5455,23 @@ mod test { }) .unwrap(); chunked.write(Bytes::from_static(b"b")).unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; chunked.write(Bytes::from_static(b"c")).unwrap(); producer = chunked.finish().unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; let mut batch = frame::Buffer::<2>::new(); batch .push(Frame::new(Timestamp::ZERO, Bytes::from_static(b"d"))) .unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; batch .push(Frame::new(Timestamp::ZERO, Bytes::from_static(b"e"))) .unwrap(); producer.write_frames(&mut batch).unwrap(); producer.finish().unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let mut consumer = producer.consume(); let mut arrived = Vec::new(); while let Some(frame) = consumer.read_frame().await.unwrap() { @@ -5482,10 +5482,10 @@ mod test { /// A group is stamped when it is created here, and a reader pulling it late from its track /// still sees that stamp. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn groups_carry_when_they_landed() { - let start = moq_clock::now(); + let start = kio::clock::now(); let mut alone = Info { sequence: 0 }.produce(); let track = crate::broadcast::Info::new() .produce() @@ -5494,7 +5494,7 @@ mod test { let mut subscriber = track.subscribe(None); let mut live = track.create_group(Info { sequence: 0 }).unwrap(); - moq_clock::sleep(std::time::Duration::from_secs(1)).await; + kio::clock::sleep(std::time::Duration::from_secs(1)).await; assert_eq!(alone.consume().arrived(), start); let group = subscriber.recv_group().await.unwrap().expect("the live group"); assert_eq!(group.arrived(), start); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index ce60949c0e9..4309f83df8e 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -7753,8 +7753,8 @@ impl ProduceTest for Config { let self_ = self; let (producer, driver) = Producer::new(self_); #[cfg(feature = "async")] - if moq_clock::sim::is_running() { - moq_clock::sim::spawn(crate::time::run(driver)); + if kio::clock::sim::is_running() { + kio::clock::sim::spawn(crate::time::run(driver)); return producer; } { @@ -7870,7 +7870,7 @@ mod tests { /// Ending a logical track must finish its metadata producer as well as its routes, /// without losing the source's final group or warning about an unfinished writer. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_finished_logical_track_does_not_warn() { let warns = count_drop_warnings("track::Producer dropped without finish", || { @@ -7912,7 +7912,7 @@ mod tests { assert_eq!(warns, 0, "a clean logical end must not drop an unfinished producer"); } - #[moq_clock::test] + #[kio::test] async fn default_config_mints_a_real_hop() { let config = Config::default(); assert_ne!(config.hop, Hop::UNKNOWN); @@ -7921,7 +7921,7 @@ mod tests { assert_eq!(producer.consume().hop(), config.hop); } - #[moq_clock::test] + #[kio::test] async fn random_hops_fit_legacy_lite_clients() { for _ in 0..32 { assert!(Hop::random().id() < 1u64 << 53); @@ -7936,7 +7936,7 @@ mod tests { if check() { return; } - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } panic!("condition never settled"); } @@ -7971,7 +7971,7 @@ mod tests { next.unwrap() } - #[moq_clock::test] + #[kio::test] async fn announce_and_retract() { let producer = origin(1).produce(); let consumer = producer.consume(); @@ -8201,7 +8201,7 @@ mod tests { /// A `.`-prefixed segment below the requested prefix hides a route from /// discovery unless the reader opts in; one inside the prefix does not. - #[moq_clock::test] + #[kio::test] async fn hidden_routes_need_an_opt_in() { let producer = origin(1).produce(); let consumer = producer.consume(); @@ -8236,7 +8236,7 @@ mod tests { } /// Hiding narrows discovery only: an exact request resolves without an opt-in. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn hidden_broadcast_resolves_by_path() { let producer = origin(1).produce(); @@ -8251,7 +8251,7 @@ mod tests { /// An excluded subtree is neither discovered nor resolved, even under a route /// covering it, while its hidden siblings and the covering route still show. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn exclude_hides_and_refuses_the_subtree() { let producer = origin(1).produce(); @@ -8289,7 +8289,7 @@ mod tests { /// An exclusion inside a mount carves the target, and one over the mount point /// drops the mount. - #[moq_clock::test] + #[kio::test] async fn exclude_reaches_into_a_mount() { let producer = origin(1).produce(); let _foo = producer.publish(".svc/p1/foo", Route::default()).unwrap(); @@ -8330,7 +8330,7 @@ mod tests { /// A request through a mount is a request for the target path: it joins the /// one front there, so the fleet-wide claim is asked once for both readers. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn mount_resolves_on_the_target_front() { let producer = origin(1).produce(); @@ -8355,7 +8355,7 @@ mod tests { /// Routes under the target, and the claim covering it, present under the /// mount; what the origin holds at the mounted path itself does not. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn mount_presents_target_routes_under_the_mount() { let producer = origin(1).produce(); @@ -8399,7 +8399,7 @@ mod tests { /// The handle's own patterns authorize a path through the mount, named as the /// handle names it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn mount_authorizes_the_named_path() { let producer = origin(1).produce(); @@ -8434,7 +8434,7 @@ mod tests { /// A wildcard spanning the mount point captures the path as the handle names /// it, so capture-keyed consumers key a mounted route like any other. - #[moq_clock::test] + #[kio::test] async fn mount_captures_the_named_path() { let producer = origin(1).produce(); let _foo = producer.publish(".svc/p1/foo", Route::default()).unwrap(); @@ -8456,7 +8456,7 @@ mod tests { /// A target at the maximum depth still presents its exact path: the `**` a /// wildcard scope carries past it can only match nothing there. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn mount_keeps_a_max_depth_target() { let producer = origin(1).produce(); @@ -8483,7 +8483,7 @@ mod tests { /// A mount point deeper than its target never presents a route whose name /// through the mount is past the depth limit, and a mount point past it is refused. - #[moq_clock::test] + #[kio::test] async fn mount_bounds_the_named_path() { let producer = origin(1).produce(); let _near = producer.publish("t/x", Route::default()).unwrap(); @@ -8508,7 +8508,7 @@ mod tests { } /// Nothing is published at or beneath a mount. - #[moq_clock::test] + #[kio::test] async fn mount_is_read_only() { let producer = origin(1).produce(); let project = producer @@ -8529,7 +8529,7 @@ mod tests { } /// A mount reaches only what the handle already reaches, and mounts never nest. - #[moq_clock::test] + #[kio::test] async fn mount_never_widens_a_scope() { let (producer, _driver) = Producer::new(Config::new(origin(1))); let project = producer.scope("", &scopes(&["p1"])).unwrap(); @@ -8557,7 +8557,7 @@ mod tests { } /// A mount point no pattern can spell could never be announced or authorized. - #[moq_clock::test] + #[kio::test] async fn mount_refuses_a_wildcard_mount_point() { let (producer, _driver) = Producer::new(Config::new(origin(1))); for at in ["*", "p1/*", "p1/**", "p1/a*"] { @@ -8570,7 +8570,7 @@ mod tests { /// Egress through a mount counts under the path the reader named, so it /// attributes to the reader's root rather than the fleet-wide target. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn mount_egress_counts_under_the_named_path() { let registry = stats::Registry::new(stats::Config::new()); @@ -8599,7 +8599,7 @@ mod tests { } /// A route that turns up later is filtered the same way as the replay. - #[moq_clock::test] + #[kio::test] async fn hidden_route_announced_later_stays_hidden() { let producer = origin(1).produce(); let consumer = producer.consume(); @@ -8615,7 +8615,7 @@ mod tests { opted.expect_next_ended(".stats/node").await; } - #[moq_clock::test] + #[kio::test] async fn a_replayed_route_retracted_before_delivery_cancels() { let producer = origin(1).produce(); let alice = producer.announce("alice", Route::default()).unwrap(); @@ -8624,7 +8624,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn broadcast_announces_its_own_path() { let producer = origin(1).produce(); @@ -8666,7 +8666,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn broadcast_announcement_retracts_with_the_last_producer() { let producer = origin(1).produce(); let consumer = producer.consume(); @@ -8684,7 +8684,7 @@ mod tests { announced.expect_next_ended("room/alice").await; } - #[moq_clock::test] + #[kio::test] async fn publish_creates_and_announces_together() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -8692,7 +8692,7 @@ mod tests { announced.expect_next_active("room/alice").await; } - #[moq_clock::test] + #[kio::test] async fn standalone_broadcast_cannot_announce() { let broadcast = broadcast::Info::new().produce(); assert!(matches!(broadcast.announce(Route::default()), Err(Error::Closed))); @@ -8700,7 +8700,7 @@ mod tests { broadcast.unannounce(); } - #[moq_clock::test] + #[kio::test] async fn announce_replays_to_late_cursor() { let producer = origin(1).produce(); let _a = producer.announce("room/alice", Route::default()).unwrap(); @@ -8713,7 +8713,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn announce_keeps_its_prefix_under_a_producer_scope() { let producer = origin(1).produce(); let scoped = producer.scope("", &scopes(&["room"])).unwrap(); @@ -8730,7 +8730,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] async fn cursor_keeps_an_overlapping_prefix_above_its_scope() { let producer = origin(1).produce(); let _a = producer.announce("", Route::default()).unwrap(); @@ -8741,7 +8741,7 @@ mod tests { consumer.announced().assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn cursor_root_strips_prefix() { let producer = origin(1).produce(); let _a = producer.announce("room/alice", Route::default()).unwrap(); @@ -8754,7 +8754,7 @@ mod tests { announced.expect_next_active("alice").await; } - #[moq_clock::test] + #[kio::test] async fn best_route_wins_and_fails_over() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -8783,7 +8783,7 @@ mod tests { } /// Pinned so `spreadHash` in `js/net` picks the same pool member for a path. - #[moq_clock::test] + #[kio::test] async fn spread_hash_matches_js() { assert_eq!(fnv_key("pool/job-0", [origin(10)]), 0xefb5e20a66101c32); assert_eq!(fnv_key("pool/job-0", [origin(11)]), 0x0eb0a91370ff6653); @@ -8793,7 +8793,7 @@ mod tests { /// paths spreads across the pool, and one path always resolves to the same /// advertiser, whatever order the routes arrived in. The split is a rendezvous /// hash, so losing an advertiser moves only the paths it won. - #[moq_clock::test] + #[kio::test] async fn equal_cost_pool_spreads_paths() { const WORKERS: [u64; 4] = [10, 11, 12, 13]; const PATHS: usize = 64; @@ -8846,7 +8846,7 @@ mod tests { /// an epoch nothing says it serves the same bytes, so consumers restart; with the /// same epoch it is the same instance, and nothing is delivered. Retracting the stale /// twin is quiet either way. - #[moq_clock::test] + #[kio::test] async fn identical_reannounce_restarts_without_an_epoch() { for epoch in [None, Some(epoch())] { let producer = origin(1).produce(); @@ -8870,7 +8870,7 @@ mod tests { } /// A re-price of the winning route is an update in place, never a restart. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_reprice_is_an_update() { let producer = origin(1).produce(); @@ -8889,7 +8889,7 @@ mod tests { /// Swapping a route's auth is an update in place carrying the new auth, so the session /// advertising it can renew its request. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_auth_swap_is_an_update() { let handle = crate::auth::Link::ietf(false); @@ -8913,7 +8913,7 @@ mod tests { /// chain whose hash loses, competes with the lingering old route: nothing restarts and /// requests stay on the old route until it is withdrawn, then consumers restart and a /// re-request lands on the replacement. Every node ranks peer routes alike. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_equal_cost_peer_replacement_waits_for_the_old_route() { // Pinned in `spread_hash_matches_js`: hop 11 hashes below hop 10 for this path. @@ -8957,7 +8957,7 @@ mod tests { /// A publisher that restarts while its old session lingers announces its own path under /// a new first hop. The restart takes over at once whichever chain hashes lower, so new /// requests never wait on the old session. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_equal_cost_local_replacement_takes_over_at_once() { for (old_hop, new_hop) in [(11, 10), (10, 11)] { @@ -9021,7 +9021,7 @@ mod tests { #[cfg(feature = "async")] async fn quiet(announced: &mut AnnounceConsumer) { for _ in 0..20 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } announced.assert_next_wait(); } @@ -9030,7 +9030,7 @@ mod tests { #[cfg(feature = "async")] async fn restarted(announced: &mut AnnounceConsumer, prefix: &str) -> Route { for _ in 0..20 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } announced.expect_next_restarted(prefix).await } @@ -9038,7 +9038,7 @@ mod tests { /// A held path moving restarts a scoped cursor whose own winner stayed, even /// though the route the cursor cannot see left and so changed the prefix's /// overall winner. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_moved_path_restarts_a_scoped_cursor() { let (producer, claim) = scoped_pool(); @@ -9063,7 +9063,7 @@ mod tests { /// A requester joining the front after its cursor restarted is not covered by /// that restart: the path moving afterwards restarts the prefix again. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_moved_path_restarts_a_requester_that_joined_after_a_restart() { let (producer, claim) = scoped_pool(); @@ -9088,7 +9088,7 @@ mod tests { /// A path that moved with the prefix's own restart is settled: the prefix's winner /// moving back to a route the front saw restarts it once, and the front adds none. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_moved_path_settled_by_a_restart_stays_settled() { let (producer, claim) = scoped_pool(); @@ -9113,7 +9113,7 @@ mod tests { /// A route from before the request repricing to win both the prefix and the held /// path restarts the prefix once: the cursor's own switch covers the move. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_repriced_route_taking_a_held_path_restarts_once() { let (producer, claim) = scoped_pool(); @@ -9130,7 +9130,7 @@ mod tests { quiet(&mut announced).await; } - #[moq_clock::test] + #[kio::test] async fn exclude_hides_routes_through_the_peer() { let producer = origin(1).produce(); let _a = producer @@ -9144,7 +9144,7 @@ mod tests { visible.expect_next_active("room").await; } - #[moq_clock::test] + #[kio::test] async fn exclude_matches_via_when_the_chain_is_anonymous() { let producer = origin(1).produce(); let assigned = origin(777); @@ -9160,7 +9160,7 @@ mod tests { hidden.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn anonymous_route_loses_to_identified_at_any_cost() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9180,7 +9180,7 @@ mod tests { assert_eq!(route.cost, Cost::new(5)); } - #[moq_clock::test] + #[kio::test] async fn anonymous_routes_order_by_cost() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9202,7 +9202,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn anonymous_chain_from_identified_peer_still_ranks_last() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9226,7 +9226,7 @@ mod tests { assert_eq!(route.cost, Cost::new(5)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn request_prefers_identified_over_cheaper_anonymous() { let producer = origin(1).produce(); @@ -9248,7 +9248,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn request_avoids_a_demoted_link_even_when_cheaper() { let producer = origin(1).produce(); @@ -9272,7 +9272,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn update_reprices_in_place() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9286,7 +9286,7 @@ mod tests { } /// Re-pricing from the current route keeps the epoch, so it stays one broadcast. - #[moq_clock::test] + #[kio::test] async fn reprice_from_the_current_route_keeps_the_epoch() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9313,7 +9313,7 @@ mod tests { assert!(broadcast.route().is_none(), "withdrawn"); } - #[moq_clock::test] + #[kio::test] async fn retract_after_undelivered_reprice_still_delivered() { let producer = origin(1).produce(); let mut announced = producer.consume().announced(); @@ -9330,7 +9330,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn scoped_cursor_advertises_most_specific_covering_route() { let producer = origin(1).produce(); // Broad and cheap; narrow and expensive. Both present relative to a cursor @@ -9348,7 +9348,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn capture_change_retracts_before_reannouncing_a_presented_prefix() { let producer = origin(1).produce(); @@ -9390,7 +9390,7 @@ mod tests { assert_eq!(heads(r"a\/b/*"), [Path::from_static(r"a\/b")]); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn follow_resolves_once_announced() { let producer = origin(1).produce(); @@ -9404,7 +9404,7 @@ mod tests { // Creating is not announcing: still parked. let broadcast = producer.create_broadcast("room/alice").unwrap(); for _ in 0..20 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!((&mut resolving).now_or_never().is_none()); @@ -9416,7 +9416,7 @@ mod tests { /// A local broadcast competes on its announced cost: a cheaper route at the /// same path wins, for cursors and requests alike. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn cheaper_remote_route_beats_a_local_broadcast() { let producer = origin(1).produce(); @@ -9449,7 +9449,7 @@ mod tests { /// A resolved broadcast names the epoch of the route it came through, and none /// when that route has none. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_resolved_broadcast_carries_its_route_epoch() { let producer = origin(1).produce(); @@ -9468,7 +9468,7 @@ mod tests { /// A cheaper route that appears after a front was minted takes the front over: it /// carries the same epoch, so a newcomer joins the front. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn cheaper_route_after_a_front_takes_it_over() { let producer = origin(1).produce(); @@ -9507,7 +9507,7 @@ mod tests { } /// A front lists what its serving source lists, as it changes. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_lists_its_source() { let producer = origin(1).produce(); @@ -9531,7 +9531,7 @@ mod tests { /// A source closing right after its tracks finished, held or not, ends the front's /// listing after those finishes, never ahead of them. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_forwards_the_finishes_before_its_source_closed() { let producer = origin(1).produce(); @@ -9558,7 +9558,7 @@ mod tests { /// A source's handler ending its listing while the source stays, as a session does on /// its peer's FIN before any retraction, ends the front's listing too. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_ends_its_listing_with_its_sources() { let producer = origin(1).produce(); @@ -9580,7 +9580,7 @@ mod tests { /// A same-instance route taking the front over lists the same tracks: readers see /// only what differs, once the new source's listing synced. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_reconciles_a_takeover() { let producer = origin(1).produce(); @@ -9615,7 +9615,7 @@ mod tests { /// A takeover without an epoch, in place, continues the front too: it serves from /// the successor once the predecessor retires rather than ending with no route. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_follows_an_epochless_takeover_in_place() { let producer = origin(1).produce(); @@ -9635,13 +9635,13 @@ mod tests { let second = producer .requests_route("room/alice", Route::default().with_hops(hops(&[10])), Some(&first)) .unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; drop(first); let successor = broadcast::Info::new().produce(); let _a = successor.create_track("a", None).unwrap(); let _b = successor.create_track("b", None).unwrap(); - moq_clock::timeout(Duration::from_secs(1), queued(&second)) + kio::clock::timeout(Duration::from_secs(1), queued(&second)) .await .expect("the front asked the successor") .accept(&successor); @@ -9651,7 +9651,7 @@ mod tests { /// A chain of takeovers in place that all land before the front's task looks again /// carries the front to the last one, though each names only the one before it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_follows_a_chain_of_takeovers() { for epochs in [false, true] { @@ -9692,7 +9692,7 @@ mod tests { let successor = broadcast::Info::new().produce(); let _a = successor.create_track("a", None).unwrap(); let _b = successor.create_track("b", None).unwrap(); - moq_clock::timeout(Duration::from_secs(1), queued(&last)) + kio::clock::timeout(Duration::from_secs(1), queued(&last)) .await .expect("the front asked the chain's last route") .accept(&successor); @@ -9705,7 +9705,7 @@ mod tests { /// A successor renewed to another epoch continues nothing its predecessor served, even /// before the front resolved through the predecessor looks at the table again. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_renewed_successor_continues_nothing() { let route = |link: u64| { @@ -9724,11 +9724,11 @@ mod tests { // Taken over, then renewed, with no yield between. let second = producer.requests_route("room/alice", route(1), Some(&first)).unwrap(); second.update_route(route(2)).unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let pending = consumer.request("room/alice", None); let renewed = broadcast::Info::new().produce(); - moq_clock::timeout(Duration::from_secs(1), queued(&second)) + kio::clock::timeout(Duration::from_secs(1), queued(&second)) .await .expect("a fresh front asked the renewed route") .accept(&renewed); @@ -9742,7 +9742,7 @@ mod tests { /// A path served on request through a covering prefix is not a broadcast anyone /// announced, so it has nothing to list. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_through_a_covering_prefix_lists_nothing() { let producer = origin(1).produce(); @@ -9761,7 +9761,7 @@ mod tests { /// At equal cost the local broadcast wins even over a route with no hops of its /// own, such as a later claim on this origin: locality is the tie-break after /// cost, not the newest entry. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn local_broadcast_wins_a_tie_with_a_hopless_route() { let producer = origin(1).produce(); @@ -9771,7 +9771,7 @@ mod tests { let server = producer.requests_route("room/alice", Route::default(), None).unwrap(); // Were the claim to win, the request would park on its handler forever. - let resolved = moq_clock::timeout(Duration::from_secs(1), consumer.request("room/alice", None)) + let resolved = kio::clock::timeout(Duration::from_secs(1), consumer.request("room/alice", None)) .await .expect("the newer hopless route won the tie") .expect("resolves"); @@ -9781,7 +9781,7 @@ mod tests { /// Ingress announce stats count advertised intervals, not the broadcast's /// lifetime: nothing while hidden, one per announce, none for a re-price. - #[moq_clock::test] + #[kio::test] async fn announce_stats_follow_the_advertisement() { let registry = stats::Registry::new(stats::Config::new()); let producer = origin(1).produce().with_stats( @@ -9817,7 +9817,7 @@ mod tests { } /// At equal cost the local broadcast wins. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn local_broadcast_wins_a_cost_tie() { let producer = origin(1).produce(); @@ -9840,14 +9840,14 @@ mod tests { let resolved = consumer.request("room/alice", None).await.expect("resolves"); assert_eq!(resolved.info().path.as_str(), "room/alice"); for _ in 0..20 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!(server.poll_requested_broadcast(&kio::Waiter::noop()).is_pending()); } /// Unannouncing ends the front the origin served from the broadcast and /// refuses new requests at once, even before the front acts on it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn unannounce_ends_the_front() { let producer = origin(1).produce(); @@ -9871,7 +9871,7 @@ mod tests { /// A subscriber still waiting on the source's track info is in flight too: /// unannouncing leaves it on the copy it asked for, which the source can /// still answer and finish. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn unannounce_keeps_a_track_awaiting_its_info() { let producer = origin(1).produce(); @@ -9881,8 +9881,8 @@ mod tests { let mut dynamic = broadcast.requests(); let resolved = consumer.request("room/alice", None).await.expect("resolves"); let track = resolved.track("video").unwrap(); - let subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); - let request = moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); + let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("the front asked the source") .expect("request"); @@ -9922,14 +9922,14 @@ mod tests { /// A finished track stays readable from the front while it is read and for the /// linger after, then leaves the broadcast so it stops pinning its cache: the next /// reader asks the source afresh. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn finished_track_is_forgotten_after_the_linger() { let (_server, _upstream, mut dynamic, resolved) = served_front().await; let track = resolved.track("catalog").unwrap(); - let subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); - let request = moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); + let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("the front asked the source") .expect("request"); @@ -9964,18 +9964,18 @@ mod tests { assert!(next_group(&mut subscription).await.unwrap().is_none()); drop(subscription); assert!( - moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .is_err(), "a finished track within the linger asked the source again" ); // Paused time runs the front's earlier deadline before this sleep returns. - moq_clock::sleep(track::IDLE_LINGER).await; + kio::clock::sleep(track::IDLE_LINGER).await; let track = resolved.track("catalog").unwrap(); - let _subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); - moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + let _subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); + kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("the finished track outlived the linger") .expect("request"); @@ -9984,7 +9984,7 @@ mod tests { /// Every viewer session excludes a hop of its own that no route chain names, so /// they all share the plain front instead of each minting one that outlives them /// for as long as the route stands (#4799). Its tracks still go with the linger. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn viewer_sessions_share_the_plain_front() { let producer = origin(1).produce(); @@ -10030,14 +10030,14 @@ mod tests { // The front outlives its viewers while the route stands, but not their track. let front = front.unwrap(); assert_eq!(front.open_tracks(), 1, "the unread track lingers"); - moq_clock::sleep(track::IDLE_LINGER).await; + kio::clock::sleep(track::IDLE_LINGER).await; settle(|| front.open_tracks() == 0).await; } /// A requester excluding a peer that a covering route passes through gets a front /// of its own. Decided per request: a peer whose hop joins a chain after it joined /// the plain front gets the filtered one on its next request. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_hop_in_a_chain_gets_its_own_front() { let producer = origin(1).produce(); @@ -10063,7 +10063,7 @@ mod tests { /// A front ends once nothing reads it for the linger and nothing holds its /// broadcast, rather than for as long as its route stands, and lets go of its source. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_unread_front_ends_after_the_linger() { let producer = origin(1).produce(); @@ -10087,11 +10087,11 @@ mod tests { drop(resolved); // Within the linger the unread track keeps its front for a returning reader. - moq_clock::sleep(track::IDLE_LINGER / 2).await; + kio::clock::sleep(track::IDLE_LINGER / 2).await; assert_eq!(fronts(), 1); assert!(upstream.is_held(), "the front let go of its source early"); - moq_clock::sleep(track::IDLE_LINGER).await; + kio::clock::sleep(track::IDLE_LINGER).await; settle(|| fronts() == 0).await; assert!(front.is_closed()); assert!(!upstream.is_held(), "an ended front still holds its source"); @@ -10099,7 +10099,7 @@ mod tests { /// A request racing a front's retirement never joins it as it ends: one that holds /// the front before its driver looks keeps it, and one after mints a fresh front. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_racing_a_front_retiring_never_joins_it_ending() { let producer = origin(1).produce(); @@ -10124,7 +10124,7 @@ mod tests { /// A track that ends while read is unread from then on, even with its reader still /// holding it: the front sees it go unread once and lets it linger, rather than /// keeping it read forever or spinning on it while it lingers ended and unread. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_track_ending_while_read_lets_its_front_retire() { let producer = origin(1).produce(); @@ -10146,7 +10146,7 @@ mod tests { source.abort(Error::NotFound).unwrap(); drop(resolved); - moq_clock::sleep(track::IDLE_LINGER).await; + kio::clock::sleep(track::IDLE_LINGER).await; settle(|| fronts() == 0).await; drop(reader); } @@ -10154,7 +10154,7 @@ mod tests { /// A front whose broadcast closes under it ends, rather than polling a holder edge /// that a closed broadcast answers at once. Nothing but the front closes it today, so /// the test does; a regression spins inside one poll and hangs the test. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_front_whose_broadcast_closes_ends() { let producer = origin(1).produce(); @@ -10185,7 +10185,7 @@ mod tests { assert!(front.as_mut().now_or_never().is_none(), "the front ended early"); broadcast.close(); - let in_flight = moq_clock::timeout(Duration::from_secs(1), front) + let in_flight = kio::clock::timeout(Duration::from_secs(1), front) .await .expect("the front outlived its broadcast"); assert!(in_flight.is_empty()); @@ -10194,7 +10194,7 @@ mod tests { /// The filtered front a peer session gets for a chain through it goes once the peer /// stops reading it, leaving the plain front its viewers share. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_peers_filtered_front_ends_once_unread() { let producer = origin(1).produce(); @@ -10225,14 +10225,14 @@ mod tests { drop(subscription); drop(peered); drop(peer); - moq_clock::sleep(track::IDLE_LINGER).await; + kio::clock::sleep(track::IDLE_LINGER).await; settle(|| fronts() == 1).await; } /// The hairpin the per-request choice accepts ends on its own. A peer still on the /// plain front when the only route left runs through it gets that route, but its own /// view withdraws the path, so it stops serving the path back to us. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_hairpin_through_the_plain_front_is_withdrawn() { let producer = origin(1).produce(); @@ -10275,7 +10275,7 @@ mod tests { /// whether the old route dies before the new one takes over (a reconnect) or after /// (a cheaper route preempting it). A reader joining mid-outage gets it too, and the /// reader already mid-group is not handed it a second time. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_takeover_serves_the_open_group_head_to_later_readers() { for dies_first in [true, false] { @@ -10301,7 +10301,7 @@ mod tests { #[cfg(feature = "async")] async fn read(group: &mut crate::group::Consumer) -> Vec { - let frame = moq_clock::timeout(Duration::from_secs(1), group.read_frame()) + let frame = kio::clock::timeout(Duration::from_secs(1), group.read_frame()) .await .expect("frame") .unwrap() @@ -10311,7 +10311,7 @@ mod tests { // A reader is mid-way through the open group when the route changes. let track = resolved.track("log").unwrap(); - let subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); + let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); let source = dynamic .requested_track() .await @@ -10335,7 +10335,7 @@ mod tests { // the front give up on a path with no route left before the replacement lands. assert!(futures::FutureExt::now_or_never(subscription.recv_group()).is_none()); let track = resolved.track("log").unwrap(); - joining = Some(moq_clock::sim::spawn(async move { + joining = Some(kio::clock::sim::spawn(async move { let mut joined = track.subscribe(None).await.unwrap(); let group = joined.recv_group().await.unwrap().expect("track ended"); (joined, group) @@ -10355,7 +10355,7 @@ mod tests { let replacement = broadcast::Info::new().produce(); let mut replacement_dynamic = replacement.requests(); queued(&replacement_server).await.accept(&replacement); - let request = moq_clock::timeout(Duration::from_secs(1), replacement_dynamic.requested_track()) + let request = kio::clock::timeout(Duration::from_secs(1), replacement_dynamic.requested_track()) .await .expect("the front asked the replacement") .unwrap(); @@ -10363,7 +10363,7 @@ mod tests { let fetches = request.requests(); let fetched = Arc::new(std::sync::Mutex::new(Vec::::new())); let serving = fetched.clone(); - let _fetching = moq_clock::sim::spawn(async move { + let _fetching = kio::clock::sim::spawn(async move { while let Ok(request) = fetches.requested_fill_group().await { let mut group = request.accept(crate::track::Info::timed()).unwrap(); for frame in [b"a", b"b", b"c"] { @@ -10391,11 +10391,11 @@ mod tests { drop(first); let track = resolved.track("log").unwrap(); - let mut later = moq_clock::timeout(Duration::from_secs(1), track.subscribe(None)) + let mut later = kio::clock::timeout(Duration::from_secs(1), track.subscribe(None)) .await .expect("subscribe") .unwrap(); - let mut late = moq_clock::timeout(Duration::from_secs(1), later.recv_group()) + let mut late = kio::clock::timeout(Duration::from_secs(1), later.recv_group()) .await .unwrap_or_else(|_| panic!("dies_first={dies_first}: the later reader never got the group")) .unwrap() @@ -10406,7 +10406,7 @@ mod tests { } let mut joined = None; if let Some(joining) = joining { - let (subscription, mut group) = moq_clock::timeout(Duration::from_secs(1), joining) + let (subscription, mut group) = kio::clock::timeout(Duration::from_secs(1), joining) .await .expect("the reader joining mid-outage never got the group") .unwrap(); @@ -10419,7 +10419,7 @@ mod tests { // The reader that was mid-group already has it. assert!( - moq_clock::timeout(Duration::from_secs(1), subscription.recv_group()) + kio::clock::timeout(Duration::from_secs(1), subscription.recv_group()) .await .is_err(), "dies_first={dies_first}: the group was handed out twice" @@ -10451,7 +10451,7 @@ mod tests { /// The same holds for a reader returning to a parked track: its warm cache /// does not stand in for the copy it is waiting on. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn unannounce_keeps_a_returning_reader_awaiting_its_info() { let producer = origin(1).produce(); @@ -10461,8 +10461,8 @@ mod tests { let mut dynamic = broadcast.requests(); let resolved = consumer.request("room/alice", None).await.expect("resolves"); let track = resolved.track("video").unwrap(); - let subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); - let request = moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); + let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("the front asked the source") .expect("request"); @@ -10476,14 +10476,14 @@ mod tests { // Parked: the source copy goes, the delivered group stays warm. The source // then tears its idle track down, so a returning reader asks it afresh. - moq_clock::timeout(Duration::from_secs(1), source.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), source.demand().until(|wanted| wanted.is_none())) .await .expect("parked") .expect("source open"); drop(source); let track = resolved.track("video").unwrap(); - let subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await }); - let request = moq_clock::timeout(Duration::from_secs(1), dynamic.requested_track()) + let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await }); + let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("the front asked the source again") .expect("request"); @@ -10508,7 +10508,7 @@ mod tests { /// A re-announce that lands before the front acts on the retraction reuses /// the same route entry, so the front carries on. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn reannounce_before_the_front_acts_keeps_it() { let producer = origin(1).produce(); @@ -10520,14 +10520,14 @@ mod tests { broadcast.unannounce(); broadcast.announce(Route::default()).unwrap(); for _ in 0..20 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!(!resolved.is_closed(), "the front ended across a reannouncement"); let again = consumer.request("room/alice", None).await.expect("resolves"); assert!(again.is_clone(&resolved)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn local_broadcast_resolves_once_announced() { let producer = origin(1).produce(); @@ -10558,7 +10558,7 @@ mod tests { assert!(matches!(err, Error::Unroutable)); } - #[moq_clock::test] + #[kio::test] async fn create_broadcast_accepts_a_path_at_the_wire_limits() { let producer = origin(1).produce(); let path = vec!["a"; Path::MAX_PARTS].join("/"); @@ -10582,7 +10582,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn duplicate_routes_aggregate_until_the_last_leaves() { let producer = origin(1).produce(); @@ -10610,7 +10610,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn dynamic_may_cover_a_scope_but_disjoint_prefixes_are_refused() { let producer = origin(1).produce(); let scoped = producer.scope("", &scopes(&["room"])).unwrap(); @@ -10627,7 +10627,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn requests_route_keeps_its_producer_scope() { let producer = origin(1).produce(); @@ -10663,7 +10663,7 @@ mod tests { assert_eq!(request.path().as_str(), "room/chat"); } - #[moq_clock::test] + #[kio::test] async fn scoped_cursor_selects_among_the_routes_it_can_see() { let producer = origin(1).produce(); let scoped = |pattern: &str| { @@ -10687,7 +10687,7 @@ mod tests { assert_eq!(video.expect_next_active("").await.cost, Cost::new(5)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn route_changes_preserve_each_cursors_visible_winner() { let producer = origin(1).produce(); @@ -10739,7 +10739,7 @@ mod tests { video.expect_next_ended("room/live").await; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn root_cursor_keeps_the_more_specific_covering_route() { let producer = origin(1).produce(); @@ -10765,7 +10765,7 @@ mod tests { assert_eq!(announced.expect_next_active("").await.cost, Cost::new(0)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dynamic_accepts_a_max_depth_prefix() { let producer = origin(1).produce(); @@ -10785,7 +10785,7 @@ mod tests { assert_eq!(request.path().as_str(), path); } - #[moq_clock::test] + #[kio::test] async fn dynamic_exclusion_skips_routes_through_the_subscriber() { let producer = origin(1).produce(); let _server = producer @@ -10800,7 +10800,7 @@ mod tests { } /// The consumer is a `Stream` of the same updates as `next`. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn announce_consumer_is_a_stream() { use futures::StreamExt; @@ -10817,7 +10817,7 @@ mod tests { assert!(matches!(next(), Some(Some(AnnounceEvent::End(_))))); } - #[moq_clock::test] + #[kio::test] async fn dynamic_retracts() { let producer = origin(1).produce(); let server = producer.requests_route("live", Route::default(), None).unwrap(); @@ -10828,7 +10828,7 @@ mod tests { announced.expect_next_ended("live").await; } - #[moq_clock::test] + #[kio::test] async fn local_broadcast_is_invisible_until_announced() { let producer = origin(1).produce(); let mut local = producer.consume().announced(); @@ -10846,7 +10846,7 @@ mod tests { peer.expect_next_ended("room/alice").await; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn served_route_materializes_on_demand() { let producer = origin(1).produce(); @@ -10870,7 +10870,7 @@ mod tests { assert!(again.is_clone(&resolved)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn served_requests_coalesce() { let producer = origin(1).produce(); @@ -10892,7 +10892,7 @@ mod tests { assert!(first.is_clone(&second)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn retract_rejects_pending_requests() { let producer = origin(1).produce(); @@ -10915,7 +10915,7 @@ mod tests { assert!(matches!(err, Error::Unroutable)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn follow_survives_serving_route_retraction() { let producer = origin(1).produce(); @@ -10949,7 +10949,7 @@ mod tests { assert_eq!(resolved.info().path.as_str(), "room/alice"); } - #[moq_clock::test] + #[kio::test] async fn split_horizon_skips_routes_through_the_requester() { let producer = origin(1).produce(); let _server = producer @@ -10972,7 +10972,7 @@ mod tests { assert!(pending.now_or_never().is_none()); } - #[moq_clock::test] + #[kio::test] async fn routes_report_where_they_entered() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); @@ -11015,15 +11015,15 @@ mod tests { /// A caller that only polls with `try_next` still gets a held update once its /// hold passes. Nothing else wakes the idle driver, so the hold's own timer /// must, or the origin's clock never reaches the deadline. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn try_next_delivers_a_held_update() { // Let paused time pass and every task woken by it run. #[cfg(feature = "async")] async fn step(by: Duration) { - moq_clock::sim::advance(by).await; + kio::clock::sim::advance(by).await; for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } } @@ -11113,14 +11113,14 @@ mod tests { /// A new route and a removal are delivered at once. A change of the best route /// within one instance waits out the update hold, and a newer change during the /// wait replaces it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_changed_route_waits_out_the_hold() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); let mut announced = producer.consume().announced(); // Holds count on the driver's clock, which starts at its first poll. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; // One epoch, so the winner moving between routes is an update, not a restart. let route = |chain: &[u64], via| { @@ -11135,14 +11135,14 @@ mod tests { // The best route changes twice; the consumer sees only the last, once. let far = peer.requests_route("room", route(&[9, 3, 4], 4), None).unwrap(); let farther = peer.requests_route("room", route(&[9, 5, 6, 7], 7), None).unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); drop(near); drop(far); match announced.next().await.unwrap() { AnnounceEvent::Update(update) => assert_eq!(update.route.hops, hops(&[9, 5, 6, 7])), other => panic!("should be an update: got {other:?}"), } - assert_eq!(moq_clock::now() - start, DEFAULT_UPDATE_HOLD); + assert_eq!(kio::clock::now() - start, DEFAULT_UPDATE_HOLD); announced.assert_next_wait(); // The last route goes: retracted at once. @@ -11152,13 +11152,13 @@ mod tests { /// After a retraction, a worse path to the same publisher waits out the /// quarantine. An anonymous route names no publisher, so one after it is not held. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_retraction_quarantines_a_named_publisher() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); let mut announced = producer.consume().announced(); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; let route = |chain: &[u64], via| Route::default().with_hops(hops(chain)).with_via(origin(via)); @@ -11166,13 +11166,13 @@ mod tests { announced.expect_next_active("named").await; drop(near); announced.expect_next_ended("named").await; - let start = moq_clock::now(); + let start = kio::clock::now(); let _stale = peer.requests_route("named", route(&[9, 3, 4], 4), None).unwrap(); match announced.next().await.unwrap() { AnnounceEvent::Start(announce) => assert_eq!(announce.route.hops, hops(&[9, 3, 4])), other => panic!("should be a start: got {other:?}"), } - assert!(moq_clock::now() - start >= RETRACT_QUARANTINE); + assert!(kio::clock::now() - start >= RETRACT_QUARANTINE); let near = peer.requests_route("anonymous", route(&[0, 2], 2), None).unwrap(); announced.expect_next_active("anonymous").await; @@ -11201,7 +11201,7 @@ mod tests { assert!(!announced.retracted.is_empty()); for _ in 0..2 { announced.assert_next_wait(); - moq_clock::sleep(RETRACT_QUARANTINE).await; + kio::clock::sleep(RETRACT_QUARANTINE).await; } announced.assert_next_wait(); assert!(announced.retracted.is_empty(), "the ended quarantine is still held"); @@ -11210,7 +11210,7 @@ mod tests { /// A peer withdrawing a prefix hides the routes there through it, so the next /// best is never a path derived from the one withdrawn. Announcing again /// revives them, and nothing is remembered once no route passes through it. - #[moq_clock::test] + #[kio::test] async fn withdrawn_peer_hides_routes_through_it() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); @@ -11248,7 +11248,7 @@ mod tests { /// Overlapping sessions are independent claims, regardless of announcement order. /// The fallback to the older session is another source, so it restarts. - #[moq_clock::test] + #[kio::test] async fn old_session_withdrawal_keeps_newer_route() { for restart in [false, true] { let producer = origin(1).produce(); @@ -11277,7 +11277,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn withdrawn_route_no_longer_covers_requests() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); @@ -11304,7 +11304,7 @@ mod tests { /// A change of source alone is delivered: the same chain and cost arriving /// from a peer instead of a client is a different fact for the consumer. Under one /// epoch it is an update. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn source_change_is_an_update() { let producer = origin(1).produce(); @@ -11335,7 +11335,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] async fn local_view_hides_peer_routes() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); @@ -11390,7 +11390,7 @@ mod tests { /// An upstream link is offered what entered here and what other peers /// forwarded, but never a route learned on another upstream link, and the /// best route it sees skips a better upstream one. - #[moq_clock::test] + #[kio::test] async fn upstream_view_hides_upstream_routes() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); @@ -11450,7 +11450,7 @@ mod tests { /// A handler that rejects a path with `Unroutable` while its route stands /// gives the requester that answer; the front must not re-ask the same route /// forever, which would spin the origin driver. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn handler_rejection_is_final() { let producer = origin(1).produce(); @@ -11460,7 +11460,7 @@ mod tests { let pending = consumer.request("room/alice", None); let request = queued(&server).await; request.reject(Error::Unroutable); - let err = moq_clock::timeout(Duration::from_secs(5), pending) + let err = kio::clock::timeout(Duration::from_secs(5), pending) .await .expect("the front must give up, not spin") .err() @@ -11476,7 +11476,7 @@ mod tests { pending.await.expect("resolves"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn claim_answer_is_hidden_until_published_with_its_epoch() { let producer = origin(1).produce(); @@ -11500,7 +11500,7 @@ mod tests { } /// Only `publish` announces a prepared answer, under its epoch and after admission. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_prepared_answer_cannot_announce_itself() { let producer = origin(1).produce(); @@ -11523,7 +11523,7 @@ mod tests { } /// Announcement control follows the origin role while fill clones retain publication lifetime. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn publication_clones_share_control_and_fill_retention() { let producer = origin(1).produce(); @@ -11548,7 +11548,7 @@ mod tests { } /// A withdrawn stale publication cannot remove a replacement instance's route. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn stale_publication_control_cannot_withdraw_a_replacement() { let producer = origin(1).produce(); @@ -11568,7 +11568,7 @@ mod tests { } /// A refused answer keeps its announcer withheld, so a clone cannot announce it later. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_refused_prepared_answer_cannot_announce_later() { let producer = origin(1).produce(); @@ -11582,7 +11582,7 @@ mod tests { assert!(matches!(answer.announce(Route::default()), Err(Error::Closed))); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn dropping_a_prepared_claim_answer_refuses_the_request() { let producer = origin(1).produce(); @@ -11595,7 +11595,7 @@ mod tests { } /// An answer prepared for a claim that went away is refused, never announced. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_prepared_answer_for_an_abandoned_claim_is_never_announced() { let producer = origin(1).produce(); @@ -11612,7 +11612,7 @@ mod tests { } /// An answer prepared before the claim changed instance is refused, never announced. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_prepared_answer_for_a_released_request_is_never_announced() { let producer = origin(1).produce(); @@ -11633,7 +11633,7 @@ mod tests { /// A takeover withdrawn before the cursor delivers it may have continued what its /// reader resolved through the claim, so the claim continues nothing more for that /// reader: the next answer is a start. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_withdrawn_takeover_ends_the_claims_continuity() { let producer = origin(1).produce(); @@ -11674,7 +11674,7 @@ mod tests { /// A request pinned to an epoch resolves only through the answer published under it, /// never by asking the claim, which has no epoch of its own. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_pinned_request_resolves_only_through_the_published_epoch() { let producer = origin(1).produce(); @@ -11696,7 +11696,7 @@ mod tests { /// A refusal from the longest prefix is the answer: neither a costlier advertiser of /// that prefix nor a catch-all is asked instead. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn refusal_never_falls_through() { let producer = origin(1).produce(); @@ -11726,7 +11726,7 @@ mod tests { /// A refusal from a route a local broadcast superseded while it was pending is moot: /// the request resolves to the local broadcast instead of ending. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn superseded_refusal_does_not_end_the_request() { let producer = origin(1).produce(); @@ -11753,7 +11753,7 @@ mod tests { /// The same holds for a more specific remote route: the beaten route's refusal is /// moot, and the new winner is asked instead. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn refusal_from_a_beaten_route_asks_the_new_winner() { let producer = origin(1).produce(); @@ -11779,7 +11779,7 @@ mod tests { } /// Teardown rejects the parked request with the origin's own terminal cause. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn follow_reports_teardown_as_closed() { let (producer, driver) = Producer::new(Config::new(origin(1))); @@ -11793,7 +11793,7 @@ mod tests { drop(driver); - let err = moq_clock::timeout(Duration::from_secs(5), resolving) + let err = kio::clock::timeout(Duration::from_secs(5), resolving) .await .expect("teardown resolves the wait") .err() @@ -11803,7 +11803,7 @@ mod tests { /// A track first subscribed after the front is already serving another still /// replays what its source holds, like the first track did. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn late_track_on_a_served_front_replays() { let producer = origin(1).produce(); @@ -11832,7 +11832,7 @@ mod tests { .subscribe(budget.clone()) .await .expect("subscribe"); - let mut group = moq_clock::timeout(Duration::from_secs(5), subscription.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(5), subscription.recv_group()) .await .expect("the late track must replay, not park") .expect("recv group") @@ -11842,7 +11842,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn most_specific_prefix_shadows() { let producer = origin(1).produce(); @@ -11867,7 +11867,7 @@ mod tests { assert_eq!(request.path().as_str(), "room/alice"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn root_dynamic_serves_any_path() { let producer = origin(1).produce(); @@ -11903,7 +11903,7 @@ mod tests { /// `scope` is authoritative, so an out-of-scope path is unauthorized before /// routing can send a request to the handler. A `Request` carries only a path, /// so the handler cannot tell who asked. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn out_of_scope_request_never_reaches_the_dynamic_handler() { let producer = origin(1).produce(); @@ -11934,7 +11934,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn routes_wait_for_coverage() { let producer = origin(1).produce(); @@ -11954,7 +11954,7 @@ mod tests { started(routes.next().now_or_never().expect("covered")); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn routes_ignore_deeper_routes() { let producer = origin(1).produce(); @@ -11970,7 +11970,7 @@ mod tests { started(fut.now_or_never().expect("covered")); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn routes_accept_a_max_depth_path() { let producer = origin(1).produce(); @@ -11992,7 +11992,7 @@ mod tests { started(fut.now_or_never().expect("covered")); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn teardown_ends_everything() { let (producer, driver) = Producer::new(Config::new(origin(1))); @@ -12228,7 +12228,7 @@ mod tests { /// Without an epoch nothing says another route serves the same bytes: a better /// route does not move the subscription, and when its own route goes it ends /// rather than resuming elsewhere. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_route_without_an_epoch_never_resumes_elsewhere() { let producer = origin(1).produce(); @@ -12265,7 +12265,7 @@ mod tests { /// A newer publisher at the path wins new requests even when it costs more, while /// the subscriptions on the old one stay with it until its route goes. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_newer_epoch_leaves_the_broadcast_in_flight() { let producer = origin(1).produce(); @@ -12309,7 +12309,7 @@ mod tests { /// A request in the same tick as a newer epoch's announcement is never handed /// the old front: its watcher has not noticed the replacement yet, but the /// request mints a front on the new epoch instead of joining the replaced one. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_racing_a_newer_epoch_skips_the_old_front() { let producer = origin(1).produce(); @@ -12353,7 +12353,7 @@ mod tests { /// A newer epoch winning while the front's first request is in flight beats that /// route: its late answer is not what requesters resolve to. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_answer_racing_a_newer_epoch_resolves_the_winner() { let producer = origin(1).produce(); @@ -12425,13 +12425,13 @@ mod tests { deliver(&fresh_track, &mut subscription, b"new").await; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_held_across_an_epoch_change_is_asked_again() { held_request_across_an_epoch_change(false).await; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_answer_before_an_epoch_change_is_asked_again() { held_request_across_an_epoch_change(true).await; @@ -12439,7 +12439,7 @@ mod tests { /// A refusal that lands just before an epoch change, before the front takes it, /// was the old instance's answer: the request is asked again, not ended. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_refusal_before_an_epoch_change_is_asked_again() { let producer = origin(1).produce(); @@ -12463,7 +12463,7 @@ mod tests { /// A release is not undone by the epoch coming back before the front looks: a /// request held across A to B to A is asked again, not refused. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_held_across_an_epoch_round_trip_is_asked_again() { let producer = origin(1).produce(); @@ -12495,7 +12495,7 @@ mod tests { /// A route that gains an epoch and then drops it serves a third instance, not the /// first: a request after the round trip is asked again rather than joining the /// front still serving the first instance's subscribers. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn losing_an_epoch_is_another_instance() { let producer = origin(1).produce(); @@ -12524,7 +12524,7 @@ mod tests { /// Announce cursors follow the newest epoch over a cheaper one, and deliver a /// change of epoch as a restart: a different broadcast. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn the_newest_epoch_is_announced_as_a_new_broadcast() { let producer = origin(1).produce(); @@ -12560,7 +12560,7 @@ mod tests { } /// A peer naming one publisher instance is never handed another. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_for_another_epoch_is_refused() { let producer = origin(1).produce(); @@ -12580,7 +12580,7 @@ mod tests { } /// A route without an epoch resolves a handle without one. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_route_without_an_epoch_resolves_without_one() { let producer = origin(1).produce(); @@ -12591,14 +12591,14 @@ mod tests { /// The driver's completion contract: it resolves once every producer handle /// drops, however many read handles remain. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn driver_resolves_with_live_consumers() { let (producer, driver) = Producer::new(Config::new(origin(1))); let consumer = producer.consume(); let run = crate::time::run(driver); drop(producer); - moq_clock::timeout(Duration::from_secs(5), run) + kio::clock::timeout(Duration::from_secs(5), run) .await .expect("driver must finish once the producers are gone"); drop(consumer); @@ -12607,7 +12607,7 @@ mod tests { /// A source claiming the same content cannot change immutable track metadata: /// the successor is refused instead of the subscriber's samples being read on /// a different grid, and the verdict outlives the aborted logical track. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn incompatible_successor_is_refused() { for replacement in [ @@ -12647,7 +12647,7 @@ mod tests { /// Routes with one epoch serve one broadcast: when the serving route dies, the /// subscription resumes through another with that epoch, whatever its first hop, /// or with none at all. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn any_route_at_the_path_resumes_the_subscription() { let cases = [ @@ -12668,7 +12668,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_replacement_query_carries_the_readers_resume_floor() { let (mut rig, incumbent, source) = ResumeRig::new(&[10]).await; @@ -12698,7 +12698,7 @@ mod tests { /// A route updated in place to a new first hop still serves the same broadcast: /// the subscription carries on through it, and a new request joins the front. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_first_hop_update_keeps_serving() { for first in [&[][..], &[0][..], &[10][..]] { @@ -12728,7 +12728,7 @@ mod tests { /// A session never subscribes to itself: when the route serving a peer dies, its /// front never resumes onto a route through that peer, even one from the same /// publisher. A reader that can see the route resumes there. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn resume_never_routes_through_the_requester() { for peer in [Some(origin(7)), None] { @@ -12806,7 +12806,7 @@ mod tests { /// /// The front closes with its last source, so the newcomer attaches a fresh /// one and the subscriber resolves it without parking. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn anonymous_handoff_serves_the_newcomer_immediately() { let producer = origin(1).produce(); @@ -12903,7 +12903,7 @@ mod tests { ); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn reprice_is_invisible_to_the_subscription() { let (rig, incumbent, source) = ResumeRig::new(&[10]).await; @@ -12935,7 +12935,7 @@ mod tests { assert_eq!(&frame.payload[..], b"steady"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn drain_reprice_migrates_before_the_session_dies() { let (mut rig, incumbent, source) = ResumeRig::new(&[10]).await; @@ -12962,7 +12962,7 @@ mod tests { /// A second broadcast at the path without an epoch is another instance: new /// requests resolve it on a fresh front, rather than join the first one's. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_newer_local_source_gets_a_fresh_front() { let producer = origin(1).produce(); @@ -12989,7 +12989,7 @@ mod tests { /// A front still resolving an instance that another has since beaten takes no new /// requester: it may already hold the beaten instance's source, and would hand it to a /// request that saw it lose, which no later announcement corrects. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_skips_a_front_resolving_a_beaten_instance() { let producer = origin(1).produce(); @@ -13011,7 +13011,7 @@ mod tests { /// A front that moved to the new winner before resolving takes requesters for it, so /// they share it rather than each minting a front on the winner. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_request_joins_a_front_resolving_the_winner() { let producer = origin(1).produce(); @@ -13046,7 +13046,7 @@ mod tests { /// /// The runtime is single-threaded and the publisher's whole ending has no await in /// it, so the outcome does not depend on timing. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_finished_broadcast_concludes_in_flight_subscriptions() { let producer = origin(1).produce(); @@ -13089,7 +13089,7 @@ mod tests { /// must still conclude normally. moq-lite, ANNOUNCE_END: "Retraction does not /// disturb subscriptions already in flight, which conclude normally with /// SUBSCRIBE_END." - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_retracted_route_concludes_in_flight_subscriptions() { let producer = origin(1).produce(); @@ -13138,7 +13138,7 @@ mod tests { /// A standing route outlives the source it produced: the front ends instead of /// asking that route for the broadcast that just closed. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_closed_source_is_not_requested_again_from_its_standing_route() { let producer = origin(1).produce(); @@ -13162,7 +13162,7 @@ mod tests { /// so the publisher's demand goes unwanted far below `track::IDLE_LINGER`. /// Cached groups stay on the front for the linger; a returning reader /// replays them and asks the source again for groups past that edge. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn origin_front_drops_the_source_when_unused() { let producer = origin(1).produce(); @@ -13186,7 +13186,7 @@ mod tests { drop(group); drop(subscription); - moq_clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_none())) .await .expect("source unused should resolve far below track::IDLE_LINGER") .expect("source closed"); @@ -13199,14 +13199,14 @@ mod tests { .subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(3600))) .await .expect("resubscribe"); - let mut group = moq_clock::timeout(Duration::from_secs(1), again.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(1), again.recv_group()) .await .expect("cached group is still on the front") .expect("recv group") .expect("track ended early"); assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached"); - moq_clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_some())) + kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_some())) .await .expect("returning reader re-splices the source") .expect("source closed"); @@ -13214,7 +13214,7 @@ mod tests { let mut group = track.append_group().unwrap(); group.write_frame(crate::Timestamp::ZERO, b"live".as_ref()).unwrap(); group.finish().unwrap(); - let mut group = moq_clock::timeout(Duration::from_secs(1), again.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(1), again.recv_group()) .await .expect("groups past the cached edge come from the re-splice") .expect("recv group") @@ -13225,7 +13225,7 @@ mod tests { /// A reader still holding an open group after its track goes unread gets the rest /// of the group: parking the track reads no new group, but the upstream stays /// subscribed until the held one ends. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_held_group_continues_after_its_track_goes_unread() { let producer = origin(1).produce(); @@ -13245,19 +13245,19 @@ mod tests { assert_eq!(&reading.read_frame().await.unwrap().unwrap().payload[..], b"head"); drop(subscription); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; writing.write_frame(crate::Timestamp::ZERO, b"tail".as_ref()).unwrap(); writing.finish().unwrap(); - let tail = moq_clock::timeout(Duration::from_secs(1), reading.read_frame()) + let tail = kio::clock::timeout(Duration::from_secs(1), reading.read_frame()) .await .expect("the held group lost its source") .unwrap() .expect("the group ended early"); assert_eq!(&tail.payload[..], b"tail"); - let end = moq_clock::timeout(Duration::from_secs(1), reading.read_frame()).await; + let end = kio::clock::timeout(Duration::from_secs(1), reading.read_frame()).await; assert!(matches!(end, Ok(Ok(None))), "the group should finish: {end:?}"); - moq_clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_none())) .await .expect("the front lets the source go once the held group ends") .expect("source closed"); @@ -13266,7 +13266,7 @@ mod tests { /// A source that aborts one group while its track carries on ends that group for /// the reader too, rather than leaving it waiting for a route change that never /// comes. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_group_the_source_aborts_ends_while_the_track_lives() { let producer = origin(1).produce(); @@ -13281,14 +13281,14 @@ mod tests { assert_eq!(&reading.read_frame().await.unwrap().unwrap().payload[..], b"head"); aborted.abort(Error::Cancel).unwrap(); - let end = moq_clock::timeout(Duration::from_secs(1), reading.read_frame()).await; + let end = kio::clock::timeout(Duration::from_secs(1), reading.read_frame()).await; assert!(matches!(end, Ok(Err(_))), "the group should fail: {end:?}"); // The track carries on. let mut next = track.append_group().unwrap(); next.write_frame(crate::Timestamp::ZERO, b"next".as_ref()).unwrap(); next.finish().unwrap(); - let mut group = moq_clock::timeout(Duration::from_secs(1), subscription.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(1), subscription.recv_group()) .await .expect("the next group") .unwrap() @@ -13299,7 +13299,7 @@ mod tests { /// A front serving from another front still drops upstream on the unused edge, /// so the publisher's demand goes unwanted far below `track::IDLE_LINGER` through /// the whole chain, and a returning reader reaches the publisher's cache afresh. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn chained_front_drops_the_source_when_unused() { let leaf = origin(1).produce(); @@ -13341,7 +13341,7 @@ mod tests { drop(group); drop(subscription); - moq_clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) .await .expect("chained unused should resolve far below track::IDLE_LINGER") .expect("source closed"); @@ -13353,7 +13353,7 @@ mod tests { .subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(3600))) .await .expect("resubscribe"); - moq_clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_some())) + kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_some())) .await .expect("resubscribe should reach the leaf") .expect("source open"); @@ -13368,7 +13368,7 @@ mod tests { drop(group); drop(subscription); - moq_clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) .await .expect("second chained unused should resolve far below track::IDLE_LINGER") .expect("source closed"); @@ -13381,11 +13381,11 @@ mod tests { let fetch = edge_resolved.track("video").unwrap().fetch_group(2, None); let mut fetch = std::pin::pin!(fetch); assert!(futures::poll!(fetch.as_mut()).is_pending(), "fetch should re-splice"); - moq_clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_some())) + kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_some())) .await .expect("fetch should reach the leaf") .expect("source open"); - let mut group = moq_clock::timeout(Duration::from_secs(5), fetch) + let mut group = kio::clock::timeout(Duration::from_secs(5), fetch) .await .expect("re-spliced source should answer the fetch") .expect("fetch succeeds"); @@ -13395,7 +13395,7 @@ mod tests { /// A newer local source wins dispatch the moment it attaches, but one whose copy /// of the track carries different metadata is refused: the incumbent keeps /// serving, and the refusal is never retried once the incumbent leaves. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn incompatible_local_source_keeps_the_incumbent() { let producer = origin(1).produce(); @@ -13426,7 +13426,7 @@ mod tests { .create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO)) .unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } // Still spliced to the incumbent, still delivering. @@ -13477,7 +13477,7 @@ mod tests { /// A local newcomer takes over while its answer for "video" is pending, so the track /// drains the incumbent. The reader leaves: the incumbent's copy is dropped at once, /// like any unread track's, not held until the linger. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_unread_draining_track_releases_the_old_source() { let (producer, _server, _upstream, old, subscription) = remote_front().await; @@ -13485,13 +13485,13 @@ mod tests { let newcomer = producer.create_broadcast("room/alice").unwrap(); let mut handler = newcomer.requests(); newcomer.announce(Route::default().with_epoch(epoch())).unwrap(); - let _unanswered = moq_clock::timeout(Duration::from_secs(1), handler.requested_track()) + let _unanswered = kio::clock::timeout(Duration::from_secs(1), handler.requested_track()) .await .expect("the front asked the newcomer") .expect("request"); drop(subscription); - moq_clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) .await .expect("the draining source stays subscribed with nobody reading") .expect("open"); @@ -13501,7 +13501,7 @@ mod tests { /// (the park drops the incumbent's copy), a third source that also lacks the track /// takes over, and the reader returns: it gets an outcome rather than waiting on the /// dropped copy. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_returning_reader_is_not_stranded_on_a_dropped_copy() { let (producer, _server, upstream, old, mut subscription) = remote_front().await; @@ -13512,7 +13512,7 @@ mod tests { .publish("room/alice", Route::default().with_epoch(epoch())) .unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } let mut group = old.append_group().unwrap(); group.write_frame(crate::Timestamp::ZERO, b"draining".as_ref()).unwrap(); @@ -13522,7 +13522,7 @@ mod tests { drop(group); drop(subscription); - moq_clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) .await .expect("parked") .expect("open"); @@ -13531,14 +13531,14 @@ mod tests { .publish("room/alice", Route::default().with_epoch(epoch())) .unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } let mut again = resolved.track("video").unwrap().subscribe(None).await.unwrap(); let mut group = old.append_group().unwrap(); group.write_frame(crate::Timestamp::ZERO, b"after".as_ref()).unwrap(); group.finish().unwrap(); - let outcome = moq_clock::timeout(Duration::from_secs(5), async { + let outcome = kio::clock::timeout(Duration::from_secs(5), async { loop { match again.recv_group().await { Ok(Some(mut group)) => { @@ -13559,7 +13559,7 @@ mod tests { /// The reader leaves, parking the track. A fetch of a whole group the parked copy /// caches answers at once, without the front serving the copy again; an open group /// still waits on the front, and is served once the copy is back. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_parked_track_serves_whole_groups_from_its_copy() { let (producer, _server, _upstream, old, subscription) = remote_front().await; @@ -13567,7 +13567,7 @@ mod tests { let mut open = old.append_group().unwrap(); open.write_frame(crate::Timestamp::ZERO, b"open".as_ref()).unwrap(); drop(subscription); - moq_clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) .await .expect("parked") .expect("open"); @@ -13592,13 +13592,13 @@ mod tests { /// A new source takes over a parked track: a whole group its old copy caches is no /// longer served from that copy, but asked of the new route, which lacks it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_new_source_unparks_the_old_copy() { let (producer, _server, _upstream, old, subscription) = remote_front().await; let resolved = producer.consume().request("room/alice", None).await.unwrap(); drop(subscription); - moq_clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| wanted.is_none())) .await .expect("parked") .expect("open"); @@ -13608,7 +13608,7 @@ mod tests { .unwrap(); let _video = newcomer.create_track("video", crate::track::Info::timed()).unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } let mut fetching = resolved.track("video").unwrap().fetch_group(0, None); @@ -13621,7 +13621,7 @@ mod tests { /// A newer local source's copy of "video" is refused for its metadata while the /// incumbent keeps serving: the refused copy is let go, not kept subscribed. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_refused_copy_is_not_kept_subscribed() { let producer = origin(1).produce(); @@ -13645,7 +13645,7 @@ mod tests { .create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO)) .unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } assert!( !incompatible.demand().is_wanted(), @@ -13661,7 +13661,7 @@ mod tests { /// As above, the newer source's copy was refused and the incumbent keeps serving. /// Then both withdraw and the front ends: the track in flight carries on with the /// incumbent, never the refused copy. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn the_end_never_feeds_a_refused_copy() { let producer = origin(1).produce(); @@ -13686,7 +13686,7 @@ mod tests { .create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO)) .unwrap(); for _ in 0..10 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; } first.unannounce(); @@ -13717,7 +13717,7 @@ mod tests { /// The track drains the incumbent while a newer source's answer is pending, then both /// withdraw and the front ends: the track carries on with the incumbent's copy rather /// than the unanswered one. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn the_end_keeps_the_copy_still_serving() { let producer = origin(1).produce(); @@ -13738,7 +13738,7 @@ mod tests { let second = producer.create_broadcast("room/alice").unwrap(); let mut handler = second.requests(); second.announce(Route::default().with_epoch(epoch())).unwrap(); - let request = moq_clock::timeout(Duration::from_secs(1), handler.requested_track()) + let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track()) .await .expect("the front asked the newcomer") .expect("request"); @@ -13759,7 +13759,7 @@ mod tests { assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"still"); } - #[moq_clock::test] + #[kio::test] async fn multiple_scopes_present_one_broad_prefix() { let producer = origin(1).produce(); let _a = producer.announce("", Route::default()).unwrap(); @@ -13774,7 +13774,7 @@ mod tests { announced.assert_next_wait(); } - #[moq_clock::test] + #[kio::test] async fn scope_accepts_every_pattern_union() { let producer = origin(1).produce(); @@ -13810,7 +13810,7 @@ mod tests { assert_eq!(producer.scope("", &mixed).unwrap().allowed(), mixed); } - #[moq_clock::test] + #[kio::test] async fn route_table_prunes_to_empty() { let producer = origin(1).produce(); let consumer = producer.consume(); @@ -13851,7 +13851,7 @@ mod tests { /// A session handed an `origin::Producer` drops it once it has its own /// handles, so the driver must keep running while a published broadcast /// lives, and finish once the last one is gone. - #[moq_clock::test] + #[kio::test] async fn a_published_broadcast_keeps_the_driver_running() { let (producer, mut driver) = Producer::new(Config::new(origin(1))); let waiter = kio::Waiter::noop(); @@ -13867,11 +13867,11 @@ mod tests { /// A handler holding only its `Requests` keeps serving once every producer /// handle drops, and the driver finishes once the handler is gone too. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_dynamic_keeps_the_driver_running() { let (producer, driver) = Producer::new(Config::new(origin(1))); - let run = moq_clock::sim::spawn(crate::time::run(driver)); + let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let server = producer.requests_route("room", Route::default(), None).unwrap(); drop(producer); @@ -13885,7 +13885,7 @@ mod tests { drop(resolved); drop(source); drop(server); - moq_clock::timeout(Duration::from_secs(5), run) + kio::clock::timeout(Duration::from_secs(5), run) .await .expect("driver must finish once the dynamic is gone") .unwrap(); @@ -13894,11 +13894,11 @@ mod tests { /// A reader still on a retracted broadcast's track keeps its front draining, but /// never keeps the driver from finishing once nothing owns the origin. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_retracted_reader_never_holds_the_driver() { let (producer, driver) = Producer::new(Config::new(origin(1))); - let run = moq_clock::sim::spawn(crate::time::run(driver)); + let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let broadcast = producer.publish("room/alice", Route::default()).unwrap(); let track = broadcast.create_track("video", crate::track::Info::timed()).unwrap(); @@ -13909,7 +13909,7 @@ mod tests { settle(|| resolved.is_closed()).await; drop(broadcast); drop(producer); - moq_clock::timeout(Duration::from_secs(5), run) + kio::clock::timeout(Duration::from_secs(5), run) .await .expect("driver must finish once the producers are gone") .unwrap(); @@ -13919,11 +13919,11 @@ mod tests { /// A subscriber that asked before the retraction but was not polled yet still finds /// the copy after the origin is orphaned and its driver finishes. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_orphaned_front_keeps_the_copy_for_a_pending_subscriber() { let (producer, driver) = Producer::new(Config::new(origin(1))); - let run = moq_clock::sim::spawn(crate::time::run(driver)); + let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let broadcast = producer.publish("room/alice", Route::default()).unwrap(); let mut track = broadcast.create_track("video", crate::track::Info::timed()).unwrap(); @@ -13935,7 +13935,7 @@ mod tests { settle(|| resolved.is_closed()).await; drop(broadcast); drop(producer); - moq_clock::timeout(Duration::from_secs(5), run) + kio::clock::timeout(Duration::from_secs(5), run) .await .expect("driver must finish once the producers are gone") .unwrap(); @@ -13948,7 +13948,7 @@ mod tests { /// A track whose last reader leaves as its broadcast ends, before the front parks it, /// lets go of its copy: the source is not kept subscribed for nobody. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_track_unread_as_its_broadcast_ends_releases_its_source() { let producer = origin(1).produce(); @@ -13957,7 +13957,7 @@ mod tests { let track = broadcast.create_track("video", crate::track::Info::timed()).unwrap(); let resolved = consumer.request("room/alice", None).await.expect("resolves"); let sub = resolved.track("video").unwrap().subscribe(None).await.unwrap(); - moq_clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_some())) + kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted.is_some())) .await .expect("the front subscribed the source") .unwrap(); @@ -13968,13 +13968,13 @@ mod tests { drop(broadcast); settle(|| resolved.is_closed()).await; - moq_clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) + kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted.is_none())) .await .expect("the ended copy must not keep the source subscribed") .unwrap(); } - #[moq_clock::test] + #[kio::test] async fn source_selection_leases_survive_reprices_but_never_revive_pending_work() { let producer = origin(1).produce(); let broad = producer @@ -14008,7 +14008,7 @@ mod tests { /// The answering lease outlives a withdrawal, since the peer still answers for the /// instance it retracted, and ends once another instance takes the path. - #[moq_clock::test] + #[kio::test] async fn source_selection_answering_ends_only_on_a_replacement() { let producer = origin(1).produce(); let path = Path::from_static("room/a"); @@ -14047,7 +14047,7 @@ mod tests { assert!(answering.is_closed()); } - #[moq_clock::test] + #[kio::test] async fn source_selection_unregisters_without_retaining_the_source() { let producer = origin(1).produce(); let route = producer @@ -14062,7 +14062,7 @@ mod tests { assert_eq!(table.routes.root.watches_below, 0); } - #[moq_clock::test] + #[kio::test] async fn watch_wakes_only_for_covering_changes() { let producer = origin(1).produce(); let waiter = kio::Waiter::noop(); @@ -14103,7 +14103,7 @@ mod tests { assert_eq!(table.routes.root.watches_below, 0); } - #[moq_clock::test] + #[kio::test] async fn a_discarded_front_task_unregisters_its_watch() { let (producer, _driver) = Producer::new(Config { hop: origin(1), @@ -14119,7 +14119,7 @@ mod tests { let _pending = consumer.request("room/a", None); } - #[moq_clock::test] + #[kio::test] async fn published_names_refuse_navigation_segments() { let producer = origin(1).produce(); for path in ["room/./cam", "room/../cam", ".", ".."] { @@ -14135,7 +14135,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn create_broadcast_refuses_a_path_no_pattern_can_spell() { let producer = origin(1).produce(); @@ -14152,7 +14152,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] async fn scope_empty_union_grants_nothing() { let producer = origin(1).produce(); @@ -14164,7 +14164,7 @@ mod tests { )); } - #[moq_clock::test] + #[kio::test] async fn scope_nests_and_rebases_roots() { let producer = origin(1).produce(); @@ -14189,7 +14189,7 @@ mod tests { broadcast.close(); } - #[moq_clock::test] + #[kio::test] async fn scope_intersects_and_rebases_arbitrary_grants() { let producer = origin(1).produce(); let rooms = producer @@ -14219,7 +14219,7 @@ mod tests { drop(broadcast); } - #[moq_clock::test] + #[kio::test] async fn wildcard_scope_filters_announcements_and_reports_captures() { let producer = origin(1).produce(); let consumer = producer @@ -14255,7 +14255,7 @@ mod tests { drop(alice); } - #[moq_clock::test] + #[kio::test] async fn announced_lists_full_names_in_replay_and_live_changes() { let producer = origin(1).produce(); let patterns: Patterns = ["*.hang", "**/*.chat"] @@ -14286,7 +14286,7 @@ mod tests { drop(chat); } - #[moq_clock::test] + #[kio::test] async fn announced_keeps_lifecycle_and_filters_before_rerooting() { let producer = origin(1).produce(); let consumer = producer @@ -14323,7 +14323,7 @@ mod tests { assert!(table.routes.interests_from(&Path::empty()).is_empty()); } - #[moq_clock::test] + #[kio::test] async fn announced_matches_mounted_names_and_keeps_exclusions() { let producer = origin(1).produce(); let _broad = producer.announce(".svc", Route::default()).unwrap(); @@ -14355,7 +14355,7 @@ mod tests { inside.expect_next_ended("lobby.chat").await; } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn announced_requests_covering_routes_and_preserves_shared_fronts_and_stats() { let registry = stats::Registry::new(stats::Config::new()); @@ -14416,7 +14416,7 @@ mod tests { pending.await.unwrap(); } - #[moq_clock::test] + #[kio::test] async fn local_broadcast_wins_announcement_ties() { let producer = origin(1).produce(); let remote = producer.announce("room/alice", Route::default().with_cost(9)).unwrap(); @@ -14439,7 +14439,7 @@ mod tests { /// so a bogus peer sorts last, not first. The ceiling is the largest cost a /// varint can carry, so whatever a peer advertises, the sum we forward still /// encodes. - #[moq_clock::test] + #[kio::test] async fn cost_charge_saturates() { assert_eq!(Cost::new(4).charged(5), Cost::new(9)); assert_eq!(Cost::new(u64::MAX).charged(10), Cost::new(MAX_COST)); @@ -14461,7 +14461,7 @@ mod tests { /// A publisher that stalls with a group still open runs no write path, so the /// track's own write-driven expiry never fires and a reader parked in that group /// is never told. The driver's wall-clock sweep is the bound. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn stalled_publisher_open_group_is_reclaimed() { let expiry = Duration::from_secs(1); @@ -14482,7 +14482,7 @@ mod tests { // Production goes quiet: nothing writes to this track again. Bounded so a // regression fails rather than parking forever, which is the bug itself. Time // is simulated, so the wait costs nothing. - let reclaimed = moq_clock::timeout(Duration::from_secs(60), reading.read_frame()).await; + let reclaimed = kio::clock::timeout(Duration::from_secs(60), reading.read_frame()).await; assert!( matches!(reclaimed, Ok(Err(Error::Old))), "the sweep must reclaim an idle open group and surface the gap, got {reclaimed:?}" @@ -14491,7 +14491,7 @@ mod tests { /// Reclamation is the pool's policy, not the origin's: a pool with no expiry /// window keeps idle content until byte pressure takes it, sweep or no sweep. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn sweep_respects_a_disabled_expiry() { let origin = Config { @@ -14509,7 +14509,7 @@ mod tests { let mut reading = stalled.consume(); assert!(reading.read_frame().await.unwrap().is_some()); - moq_clock::sim::advance(Duration::from_secs(3600)).await; + kio::clock::sim::advance(Duration::from_secs(3600)).await; assert!( reading.read_frame().now_or_never().is_none(), @@ -14519,7 +14519,7 @@ mod tests { /// A draining cost still has to fit the wire, since the route keeps being /// announced downstream while it drains. - #[moq_clock::test] + #[kio::test] async fn drain_cost_is_encodable() { use crate::coding::Encode; diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index 4d212c4858f..3e59b5a04b7 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -2351,7 +2351,7 @@ mod test { } /// A later stream header is not a verdict on the group held from a failed route. - #[moq_clock::test] + #[kio::test] async fn a_failed_route_waits_for_a_reordered_group_header() { let waiter = kio::Waiter::noop(); for arrives in [true, false] { @@ -2393,7 +2393,7 @@ mod test { assert_eq!(read(&mut held), Some(b"continued".to_vec())); assert_eq!(read(&mut held), None); } else { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(matches!( held.poll_read_frame(&waiter), Poll::Ready(Err(Error::NotFound)) @@ -2406,7 +2406,7 @@ mod test { /// an hour-budget one, whichever recovers first: each reader subscribes to the new route /// before judging, so the copy's combined budget always covers its own. Nor does the /// hour-budget reader keep the short one waiting past its own budget. - #[moq_clock::test] + #[kio::test] async fn a_refused_group_waits_for_its_own_readers_grace() { let waiter = kio::Waiter::noop(); let short = Duration::from_millis(100); @@ -2449,7 +2449,7 @@ mod test { } assert!(refused > 0, "short_first={short_first}: the recovery fetch arrives"); - moq_clock::sleep(short).await; + kio::clock::sleep(short).await; let res = quick_held.poll_read_frame(&waiter); assert!( matches!(res, Poll::Ready(Err(Error::Old | Error::NotFound))), @@ -2489,7 +2489,7 @@ mod test { ); } - #[moq_clock::test] + #[kio::test] async fn a_declared_end_survives_a_swap_before_it_is_polled() { let routes = Producer::new(); let logical = logical(&routes); @@ -2515,7 +2515,7 @@ mod test { /// A route switch keeps the error the logical end was declared with, even when the copy /// serving at the end declares that end cleanly. - #[moq_clock::test] + #[kio::test] async fn an_errored_end_survives_a_route_switch() { let routes = Producer::new(); let logical = logical(&routes); @@ -2541,7 +2541,7 @@ mod test { } /// A routed reader that reads only datagrams ends with the end's error, as a direct one does. - #[moq_clock::test] + #[kio::test] async fn a_routed_datagram_reader_ends_with_the_end_error() { let routes = Producer::new(); let logical = logical(&routes); @@ -2561,7 +2561,7 @@ mod test { )); } - #[moq_clock::test] + #[kio::test] async fn copies_must_agree_on_the_declared_end() { for next in [Position::group(5), Position { group: 4, frame: 3 }, Position::group(6)] { let routes = Producer::new(); @@ -2591,7 +2591,7 @@ mod test { } /// A copy that delivers past an end another copy declared contradicts it. - #[moq_clock::test] + #[kio::test] async fn content_past_the_declared_end_refuses_the_track() { for datagram in [false, true] { let routes = Producer::new(); @@ -2627,7 +2627,7 @@ mod test { /// A mid-group end another copy declared caps the group it falls in, even for frames /// that arrive after the group was handed out. - #[moq_clock::test] + #[kio::test] async fn a_mid_group_end_caps_another_copys_group() { let routes = Producer::new(); let logical = logical(&routes); @@ -2656,7 +2656,7 @@ mod test { } /// An end below a group a copy handed out or holds claims other content. - #[moq_clock::test] + #[kio::test] async fn an_end_below_a_seen_group_refuses_the_track() { for handed_out in [false, true] { let routes = Producer::new(); @@ -2680,7 +2680,7 @@ mod test { /// A mid-group end learned late, below a frame or datagram object already seen, claims /// other content. - #[moq_clock::test] + #[kio::test] async fn a_late_mid_group_end_below_a_seen_object_refuses_the_track() { for datagram in [false, true] { let routes = Producer::new(); @@ -2732,7 +2732,7 @@ mod test { } /// The newest datagram handed out bounds a late end after the budget forgets its identity. - #[moq_clock::test] + #[kio::test] async fn an_end_below_an_expired_datagram_refuses_the_track() { let routes = Producer::new(); let logical = logical(&routes); @@ -2745,7 +2745,7 @@ mod test { routes.serve(b.consume()); b.insert_datagram(1, ts(1), b"d".as_ref()).unwrap(); assert!(sub.poll_recv_datagram(&kio::Waiter::noop()).is_ready()); - moq_clock::sleep(Duration::from_secs(2)).await; + kio::clock::sleep(Duration::from_secs(2)).await; assert!(sub.poll_recv_datagram(&kio::Waiter::noop()).is_pending()); assert_eq!(copies(&routes), 1); b.finish_at(Position::group(5), None).unwrap(); @@ -2757,7 +2757,7 @@ mod test { /// A gap that stays open across route flaps keeps one backfill per distinct route: a /// later resume point widens the route's backfill rather than asking again. - #[moq_clock::test] + #[kio::test] async fn route_flaps_keep_one_backfill_per_distinct_route() { let routes = Producer::new(); let logical = logical(&routes); @@ -2780,7 +2780,7 @@ mod test { assert_eq!(drain(&mut sub, false), [1]); } - #[moq_clock::test] + #[kio::test] async fn route_flaps_keep_one_copy_per_distinct_route() { let routes = Producer::new(); let logical = logical(&routes); @@ -2810,7 +2810,7 @@ mod test { /// A returning route resumes where a fresh copy would, and what it buffered while /// replaced below what another route already handed out comes through the backfill: /// the late group once, and nothing handed out again. - #[moq_clock::test] + #[kio::test] async fn a_returning_route_backfills_below_the_readers_newest() { let routes = Producer::new(); let logical = logical(&routes); @@ -2833,7 +2833,7 @@ mod test { drop(held); } - #[moq_clock::test] + #[kio::test] async fn a_replaced_copy_is_not_kept_for_a_gap_outside_the_window() { let routes = Producer::new(); let logical = logical(&routes); @@ -2939,7 +2939,7 @@ mod test { /// Routes that close without concluding read like a conclusion: a reader stalled /// mid-group parks on the copy it is reading rather than polling the closed routes /// forever, and finishes the group from that copy. - #[moq_clock::test] + #[kio::test] async fn a_stalled_group_parks_when_the_routes_close() { let routes = Producer::new(); let logical = logical(&routes); @@ -3224,7 +3224,7 @@ mod test { /// A run the serving copy gave up waits while a copy it replaced may still deliver it /// under its bound, and goes out once that copy is past the reader's budget. - #[moq_clock::test] + #[kio::test] async fn a_drop_waits_while_a_replaced_copy_may_still_deliver_it() { let routes = Producer::new(); let logical = logical(&routes); @@ -3247,7 +3247,7 @@ mod test { assert_eq!(drain(&mut sub, false), [3]); assert_eq!(dropped(&mut sub), []); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(dropped(&mut sub), [(2..3, StreamError::NotFound)]); write(&a, 2); assert_eq!(drain(&mut sub, false), Vec::::new()); @@ -3945,7 +3945,7 @@ mod test { /// A group the old route was still sending when the new route took over arrives after the /// new copy's first group, once polled: the old copy stays while it may still land, and /// goes once its publisher drops it or the reader's budget passes. - #[moq_clock::test] + #[kio::test] async fn an_arrival_reader_gets_a_group_still_in_flight_on_the_replaced_route() { for outcome in ["lands", "dropped", "expired"] { let routes = Producer::new(); @@ -3966,7 +3966,7 @@ mod test { match outcome { "lands" => {} "dropped" => a.drop_groups(1..2, StreamError::NotFound), - _ => moq_clock::sleep(Duration::from_secs(1)).await, + _ => kio::clock::sleep(Duration::from_secs(1)).await, } if outcome != "lands" { assert_eq!(drain(&mut sub, false), Vec::::new()); @@ -4720,7 +4720,7 @@ mod test { /// A route's backfill widened by a later resume point asks for the wider span even once /// it answered for the narrower one: a range ending relative to the latest group keeps the /// reader's end, not the backfill's earlier cap. - #[moq_clock::test] + #[kio::test] async fn a_widened_backfill_reaches_past_its_earlier_cap() { let routes = Producer::new(); let logical = logical(&routes); @@ -4992,7 +4992,7 @@ mod test { /// arrives, so only the deadline wake can release the reader: against a cold route, and /// against one whose copy already caches groups past the held one, so a cursor that /// skips ahead cannot hide the stall. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_untimed_group_no_route_continues_is_given_up_by_wall_clock() { let untimed = || { @@ -5145,7 +5145,7 @@ mod test { assert_eq!(routes.subscription(demand, 1).start(), Some(10)); } - #[moq_clock::test] + #[kio::test] async fn a_replacement_delivers_unseen_datagrams_below_the_newest_sequence() { let routes = Producer::new(); let front = logical(&routes); diff --git a/rs/moq-net/src/model/resume_model.rs b/rs/moq-net/src/model/resume_model.rs index e4b65e7c409..dab72582ce5 100644 --- a/rs/moq-net/src/model/resume_model.rs +++ b/rs/moq-net/src/model/resume_model.rs @@ -197,7 +197,7 @@ fn case() -> impl Strategy { struct Copy { track: track::Producer, /// Answers the front's requests for the route until the route goes. - serving: moq_clock::sim::JoinHandle<()>, + serving: kio::clock::sim::JoinHandle<()>, _broadcast: broadcast::Producer, /// Fetches of groups the copy lacks, which the route forwards to the publisher. fills: track::Requests, @@ -338,7 +338,7 @@ impl Model { ..Default::default() }; let (origin, driver) = Producer::new(origin); - moq_clock::sim::spawn(crate::time::run(driver)); + kio::clock::sim::spawn(crate::time::run(driver)); Self { consumer: origin.consume(), origin, @@ -404,9 +404,9 @@ impl Model { instance.given_up.insert(group); } Op::End { epoch, slot } => self.end(epoch, slot), - Op::Advance { ms } => moq_clock::sim::advance(Duration::from_millis(ms)).await, + Op::Advance { ms } => kio::clock::sim::advance(Duration::from_millis(ms)).await, Op::Expire => { - moq_clock::sim::advance(Duration::from_secs(60)).await; + kio::clock::sim::advance(Duration::from_secs(60)).await; for reader in self.readers.iter_mut().flatten() { reader.floor = self.instances[reader.instance].newest(); } @@ -457,7 +457,7 @@ impl Model { let broadcast = broadcast::Info::new().produce(); let track = broadcast.create_track("video", track::Info::timed()).unwrap(); let upstream = broadcast.consume(); - let serving = moq_clock::sim::spawn(async move { + let serving = kio::clock::sim::spawn(async move { while let Ok(request) = kio::wait(|waiter| requests.poll_requested_broadcast(waiter)).await { request.accept(&upstream); } @@ -769,7 +769,7 @@ impl Model { async fn settle(&mut self) -> Result<(), TestCaseError> { let mut quiet = 0; for _ in 0..10_000 { - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; let mut woken = self.fill(); for index in 0..READERS { if self.readers[index] @@ -905,7 +905,7 @@ impl Model { } fn run(case: &Case) -> Result<(), TestCaseError> { - moq_clock::sim::run(async { + kio::clock::sim::run(async { let mut model = Model::new(); model.up(0, 0); for op in &case.ops { @@ -935,7 +935,7 @@ fn readers_match_the_logical_track() { /// An Up or Down that leaves the winning route serving still delivers a group only a standby route has. #[test] fn unchanged_routes_keep_groups_owed() { - moq_clock::sim::run(async { + kio::clock::sim::run(async { let mut model = Model::new(); model.up(0, 0); let ops = [ diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 97264338d27..cb5dabe683a 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -8639,7 +8639,7 @@ mod test { /// An empty group raises the largest at its head, so its first frame names nothing newer. #[cfg(feature = "async")] - #[moq_clock::test] + #[kio::test] async fn largest_streams_groups_and_frames_and_coalesces() { let producer = track_producer("test", Info::default()); let mut subscriber = producer.subscribe(replay()); @@ -8730,7 +8730,7 @@ mod test { /// A copy a transport bound cut short finishes only its own range, so the largest group /// may still grow and the stream stays open past the end. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_finished_bounded_copy_keeps_the_largest_open() { let mut producer = track_producer("test", Info::timed()); @@ -8855,7 +8855,7 @@ mod test { } #[cfg(feature = "async")] - #[moq_clock::test] + #[kio::test] async fn largest_starts_with_the_sources_report() { let producer = track_producer("test", Info::default()); let mut subscriber = producer.subscribe(replay()); @@ -9508,7 +9508,7 @@ mod test { } /// A cached observer must not keep an unfinished writer alive or serve its dead copy. - #[moq_clock::test] + #[kio::test] async fn dropped_group_writer_aborts_and_releases_its_cached_copy() { let pool = cache::Pool::unbounded(); let producer = track_producer_pooled("test", pool.clone()); @@ -9531,7 +9531,7 @@ mod test { assert_eq!(pool.used(), 0); } - #[moq_clock::test] + #[kio::test] async fn dropped_group_writer_is_absent_and_its_sequence_can_be_recreated() { let producer = track_producer("test", Info::timed()); let mut group = producer.create_group(group::Info { sequence: 3 }).unwrap(); @@ -9563,7 +9563,7 @@ mod test { )); } - #[moq_clock::test] + #[kio::test] async fn dropped_group_writer_preserves_the_committed_resume_position() { let producer = track_producer("test", Info::timed()); let consumer = producer.consume(); @@ -10047,7 +10047,7 @@ mod test { /// A group whose frames outlive `max_age` is aged out when the next group starts, but /// a subscriber that already drained it must still see the clean end of group. Otherwise a /// track with long groups (a per-minute rollup, say) fails its readers at every boundary. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn aging_out_a_finished_group_keeps_the_clean_end() { let producer = track_producer("test", Info::timed()); @@ -10070,7 +10070,7 @@ mod test { /// An actively-read group is not expired out from under its reader: every frame /// read restarts the retention clock. A group nobody reads still ages out on /// schedule, so reclamation stays intact. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn active_reader_survives_expiry() { let producer = track_producer("test", Info::timed()); @@ -10108,7 +10108,7 @@ mod test { /// alive: the batch is filled (and stamped) once per `Prefetch::CAP` frames, /// which bounds frames, not elapsed time, so a slow `read_frame` reader has to /// re-stamp on a time bound between refills. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn slow_prefetch_reader_survives_expiry() { let producer = track_producer("test", Info::timed()); @@ -10137,7 +10137,7 @@ mod test { /// Receiving a group is itself a cache access: a subscriber that takes /// delivery just before the group would age out still gets to read it a full /// window later. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn delivery_restarts_the_expiry_clock() { let producer = track_producer("test", Info::timed()); @@ -10233,7 +10233,7 @@ mod test { /// Re-offering a parked group (once the cap rises) is a delivery: it restarts /// the expiry clock so the subscriber gets to read what it was just handed. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn parked_reoffer_restarts_the_expiry_clock() { let producer = track_producer("test", Info::timed()); @@ -10594,7 +10594,7 @@ mod test { /// A read parked on a superseded group is released by the wall clock alone: nothing is /// written after its successor arrives, so no write could wake it. That holds whether a /// driver collected the pool before the read parked or only after. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_parked_read_wakes_at_its_wall_deadline() { for (info, primed) in [Info::default(), Info::timed()] @@ -10643,7 +10643,7 @@ mod test { /// A successor whose header landed but whose first frame never does still starts the /// wall clock, so a relay ages the group before it as the origin does. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_frameless_successor_ages_its_predecessor() { for info in [Info::default(), Info::timed()] { @@ -11356,7 +11356,7 @@ mod test { assert_eq!(drain(&mut subscriber), vec![1]); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_handed_out_group_expires_while_its_first_frame_is_stalled() { let mut producer = track_producer("test", Info::timed()); @@ -11364,8 +11364,8 @@ mod test { let _writer_1 = producer.append_group().unwrap(); let mut stalled = subscriber.recv_group().await.unwrap().expect("stalled group"); - let pending = moq_clock::sim::spawn(async move { stalled.read_frame().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { stalled.read_frame().await }); + kio::clock::sim::yield_now().await; assert!( !pending.is_finished(), "the empty live edge still waits for its first frame" @@ -11383,7 +11383,7 @@ mod test { /// to be woken by it. The conviction needs a group beyond the held one's successor: /// a group is bounded by where its successor begins, so the successor itself never /// proves it stale. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_handed_out_group_wakes_when_a_newer_group_gets_its_first_timestamp() { let mut producer = track_producer("test", Info::timed()); @@ -11399,8 +11399,8 @@ mod test { assert!(held.read_frame().await.unwrap().is_some()); let mut live = producer.append_group().unwrap(); - let pending = moq_clock::sim::spawn(async move { held.read_frame().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { held.read_frame().await }); + kio::clock::sim::yield_now().await; assert!(!pending.is_finished(), "the newer group has no timestamp yet"); // 2s edge against group 0's 1s reach: a full second past the budget. @@ -11409,7 +11409,7 @@ mod test { bytes::Bytes::from_static(b"live"), ) .unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; assert!(pending.is_finished(), "the new presentation edge wakes the held reader"); // Drained but never finished, so the budget fails the group. @@ -11900,7 +11900,7 @@ mod test { /// A frameless group whose stream ends with no frame, cleanly or reset, ends its readers /// with it, and the track's end follows. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_frameless_group_that_ends_empty_ends_its_readers() { for abort in [false, true] { @@ -11918,7 +11918,7 @@ mod test { true => group.abort(Error::Cancel).unwrap(), false => group.finish().unwrap(), } - moq_clock::timeout(Duration::from_secs(1), next) + kio::clock::timeout(Duration::from_secs(1), next) .await .expect("the end wakes the reader") }; @@ -11939,7 +11939,7 @@ mod test { /// and the next group's first frame are separate events and the wire does not order /// them. A zero budget gives up there, and the group fails with [`Error::Old`] since /// its producer never finished it, but only after the reader took every frame. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn real_time_reads_a_live_stream_without_truncating_it() { let producer = track_producer("test", Info::timed()); @@ -12006,7 +12006,7 @@ mod test { } /// Decode-order B-frames cannot rewind the presentation edge and re-admit an old group. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_reordered_tail_keeps_the_group_pts_drift_verdict() { for reordered in [false, true] { @@ -12048,7 +12048,7 @@ mod test { /// /// Measuring from the group's first frame instead makes the drift 2000ms, so a /// budget shorter than one GOP would drop the tail of every GOP. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_budget_is_measured_from_the_readers_position() { let producer = track_producer("test", Info::timed()); @@ -12094,7 +12094,7 @@ mod test { /// A drained group the budget gives up on fails with [`Error::Old`] on every probe, /// including [`group::Consumer::finished`]: the producer never finished it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_expired_group_stays_old_when_probed_again() { let mut producer = track_producer("test", Info::timed()); @@ -12106,13 +12106,13 @@ mod test { let mut group = subscriber.recv_group().await.unwrap().expect("group"); assert!(group.read_frame().await.unwrap().is_some()); - let probes = moq_clock::sim::spawn(async move { + let probes = kio::clock::sim::spawn(async move { let first = group.read_frame().await; let second = group.read_frame().await; let finished = group.finished().await; (first, second, finished) }); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; append_at(&mut producer, 1000); @@ -12122,7 +12122,7 @@ mod test { assert!(matches!(finished, Err(Error::Old)), "never finished: {finished:?}"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_drained_group_finishes_cleanly_after_the_live_edge_advances() { let mut producer = track_producer("test", Info::timed()); @@ -12137,7 +12137,7 @@ mod test { assert!(group.read_frame().await.unwrap().is_none()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_handed_out_partial_frame_expires_while_its_payload_is_stalled() { let mut producer = track_producer("test", Info::timed()); @@ -12157,8 +12157,8 @@ mod test { frame.read_chunk().await.unwrap(), Some(bytes::Bytes::from_static(b"old")) ); - let pending = moq_clock::sim::spawn(async move { frame.read_chunk().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { frame.read_chunk().await }); + kio::clock::sim::yield_now().await; assert!(!pending.is_finished(), "the partial payload is still stalled"); elapse(&producer, Duration::from_secs(1)); @@ -12608,7 +12608,7 @@ mod test { )); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetched_group_keeps_its_budget_while_reading() { let mut producer = track_producer("test", Info::timed()); @@ -12621,8 +12621,8 @@ mod test { let mut fetched = consumer.fetch_group(0, options).await.unwrap(); assert!(fetched.read_frame().await.unwrap().is_some()); - let pending = moq_clock::sim::spawn(async move { fetched.read_frame().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { fetched.read_frame().await }); + kio::clock::sim::yield_now().await; elapse(&producer, Duration::from_secs(1)); append_at(&mut producer, 1000); append_at(&mut producer, 2000); @@ -12713,7 +12713,7 @@ mod test { /// A one-shot fetch populates the shared cache but never the live arrival cursor, /// so it cannot make content available to a subscription look stale. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetched_group_is_not_a_live_drift_edge() { let mut producer = track_producer("test", Info::timed()); @@ -12848,7 +12848,7 @@ mod test { /// A group handed out before the ranges moved above it is judged against the new run, /// not a cached group below its start: here group 1 would put group 0 18s behind the /// edge, past the budget, where the run's own group 10 puts it 9s behind. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_held_group_is_judged_against_the_moved_run() { let at = |millis| Timestamp::from_millis(millis).unwrap(); @@ -12867,8 +12867,8 @@ mod test { group.finish().unwrap(); } - let pending = moq_clock::sim::spawn(async move { held.read_frame().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { held.read_frame().await }); + kio::clock::sim::yield_now().await; assert!(!pending.is_finished(), "group 0 is within the budget of its run"); } @@ -12996,7 +12996,7 @@ mod test { /// Ranges replaced through a [`Control`] republish what a held group is judged against /// at once, before the cursor next reads: group 0 is judged against the run's own /// group 10, not group 1, which the new ranges never read. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_control_update_moves_the_run_a_held_group_is_judged_against() { let at = |millis| Timestamp::from_millis(millis).unwrap(); @@ -13015,8 +13015,8 @@ mod test { group.finish().unwrap(); } - let pending = moq_clock::sim::spawn(async move { held.read_frame().await }); - moq_clock::sim::yield_now().await; + let pending = kio::clock::sim::spawn(async move { held.read_frame().await }); + kio::clock::sim::yield_now().await; assert!(!pending.is_finished(), "group 0 is within the budget of its run"); drop(subscriber); } @@ -13365,7 +13365,7 @@ mod test { /// Aborting a track also aborts a fetched head still being written, so its reader ends /// with the track's error rather than waiting on a fetch that can no longer land. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn abort_ends_an_open_fetched_head() { let producer = track_producer("test", Info::timed()); @@ -13725,7 +13725,7 @@ mod test { /// An end declared with an error keeps the history below it: every reader gets the groups /// first, then the error, and a fetch still reads them. A range short of the end ends /// cleanly, since it never reaches the error. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_errored_end_keeps_its_history() { let mut producer = track_producer("test", Info::timed()); @@ -13774,7 +13774,7 @@ mod test { producer.consume().fetch_group(1, None).await.unwrap(); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn readers_end_at_the_boundary_with_missing_lower_groups() { let mut producer = track_producer("test", Info::timed()); @@ -13805,7 +13805,7 @@ mod test { /// A received copy's end holds readers at a hole below it, since a lower group's stream /// may arrive after a higher one, until the hole fills or its grace passes. The last /// producer going ends them regardless. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_pending_tail_holds_readers_at_a_hole() { let mut producer = track_producer("test", None); @@ -13853,7 +13853,7 @@ mod test { /// The grace alone ends a reader parked at a hole, with no write to wake it: below an /// arrival it runs from that arrival, and above the last one from the declared end. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_parked_reader_wakes_when_the_tail_grace_passes() { // The subscription's max delay is the grace. @@ -14068,7 +14068,7 @@ mod test { /// A fetched copy of a group the live feed still owes never reaches an arrival-order /// reader, so it does not fill the hole: the reader waits for the live group. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_fetched_group_does_not_fill_a_pending_tail() { let mut producer = track_producer("test", None); @@ -14092,7 +14092,7 @@ mod test { /// An abort ends the wait for a pending tail. A group the tail still owed was cut off, /// so readers get the abort rather than a clean end without it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_abort_errors_a_pending_tail_short_of_a_group() { let mut producer = track_producer("test", None); @@ -14114,7 +14114,7 @@ mod test { /// A reader that got every group ends cleanly, even when the track aborts before the /// reader polls past the last one. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_abort_after_a_full_tail_ends_cleanly() { let mut producer = track_producer("test", None); @@ -14137,7 +14137,7 @@ mod test { /// A gap the grace already gave up on was lost before the abort, not cut off by it, so /// readers end cleanly. Within the grace, the same abort errors them. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_abort_past_the_grace_ends_a_pending_tail_cleanly() { for (waited, ended) in [(ledger::GRACE / 2, false), (ledger::GRACE, true)] { @@ -14214,7 +14214,7 @@ mod test { /// The wire's end can land after the highest group, with lower groups still owed. A /// reader already past that group stays held at the hole: the end never shows without /// its pending tail. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_end_after_the_highest_group_holds_the_reader() { let mut producer = track_producer("test", None); @@ -15501,7 +15501,7 @@ mod test { ); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn group_ranges_preserve_the_floor_when_the_cap_changes() { let producer = track_producer("test", Info::timed()); @@ -15781,7 +15781,7 @@ mod test { assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_)))); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_cache_hit() { let producer = track_producer("test", Info::timed()); @@ -15806,7 +15806,7 @@ mod test { assert!(dynamic.poll_requested_fill_group(&kio::Waiter::noop()).is_pending()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_miss_signals_dynamic() { let producer = track_producer("test", Info::timed()); @@ -15840,7 +15840,7 @@ mod test { assert_eq!(&g.read_frame().await.unwrap().unwrap().payload[..], b"hi"); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_miss_rejects() { let producer = track_producer("test", Info::timed()); @@ -15860,7 +15860,7 @@ mod test { assert!(fetch.read().is_empty()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_miss_drop_rejects() { let producer = track_producer("test", Info::timed()); @@ -15880,7 +15880,7 @@ mod test { /// A request stays wanted while any joined fetch waits, and once the last leaves it /// is withdrawn: a later fetch starts a fresh request instead of joining it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_request_unused_once_every_fetch_leaves() { let producer = track_producer("test", Info::timed()); @@ -15914,7 +15914,7 @@ mod test { /// A fetch abandoned before any handler took it is withdrawn from the queue too, so /// no handler serves it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_abandoned_while_queued_never_reaches_the_handler() { let producer = track_producer("test", Info::timed()); @@ -15929,7 +15929,7 @@ mod test { /// The withdrawal happens as the last caller leaves, not when the handler notices: a /// fetch arriving before the handler drops the abandoned request is not failed with it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_after_the_last_caller_left_is_not_dropped() { let producer = track_producer("test", Info::timed()); @@ -15959,7 +15959,7 @@ mod test { /// A handler that accepts after every caller left still caches the group, so a fetch /// that queued a fresh request meanwhile resolves from it and that request is moot. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_accept_after_withdrawal_caches_the_group() { let producer = track_producer("test", Info::timed()); @@ -16004,7 +16004,7 @@ mod test { /// A fetch that hits the cache holds the group until polled, so a handler that aborts /// the group once nobody wants it (an abandoned upstream fetch) leaves it alone. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_hit_keeps_the_group_wanted() { let producer = track_producer("test", Info::timed()); @@ -16033,7 +16033,7 @@ mod test { } /// A bounded FIN is local to its request, never proof that the original group ended. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn bounded_transport_copies_never_answer_whole_fetches() { let producer = track_producer("test", Info::timed()); @@ -16090,7 +16090,7 @@ mod test { } /// Tail starts replace one backfill slot rather than retaining a copy per peer range. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn bounded_tail_refills_coalesce_behind_a_live_copy() { let producer = track_producer("test", Info::timed()); @@ -16132,7 +16132,7 @@ mod test { /// A bounded fill that a later, disjoint one displaces from the cache still answers the /// fetch that asked for it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_displaced_bounded_fill_still_answers_its_fetch() { let producer = track_producer("test", Info::timed()); @@ -16167,7 +16167,7 @@ mod test { /// A copy cut short at the back never displaces a fetched one that reaches the group's /// end, so whole-group readers keep it, and it still answers its own fetch. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_bounded_fill_never_displaces_a_whole_tail() { let producer = track_producer("test", Info::timed()); @@ -16207,7 +16207,7 @@ mod test { /// A track abort ends every copy still being written, including one the cache never held /// or has since displaced: its reader gets the abort and its writer fails. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_track_abort_ends_uncached_copies() { let producer = track_producer("test", Info::timed()); @@ -16264,7 +16264,7 @@ mod test { /// A track abort keeps a finished bounded copy for the reader still draining it, as it /// does a finished whole group. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_track_abort_keeps_a_finished_bounded_copy() { let producer = track_producer("test", Info::timed()); @@ -16297,7 +16297,7 @@ mod test { /// A finished bounded copy below the declared end is nothing in flight, so an abort after /// the end is reached still ends the track cleanly. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_finished_bounded_copy_lets_the_end_settle() { let mut producer = track_producer("test", Info::timed()); @@ -16335,7 +16335,7 @@ mod test { /// A copy cut short at the back never answers a whole-group reader. A live group the /// publisher cut is still handed out as that cut, and one it cancelled stays a hole, /// whatever bounded copy of it remains. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_back_cut_copy_never_answers_a_whole_group_reader() { let producer = track_producer("test", Info::timed()); @@ -16385,7 +16385,7 @@ mod test { } /// Queued ranges widen before dispatch; a taken cap does not promise an unseen suffix. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn bounded_fetches_widen_before_dispatch_and_split_after() { let producer = track_producer("test", Info::timed()); @@ -16407,7 +16407,7 @@ mod test { /// An accepted group starts where its request did before anyone can see it, so a /// wider fetch arriving before the handler writes misses instead of being handed a /// reader that would skip the head it asked for. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn accepted_group_starts_at_the_request() { let producer = track_producer("test", Info::timed()); @@ -16440,7 +16440,7 @@ mod test { /// Once a group nobody wanted is aborted, a later fetch misses rather than reading /// the abort, and queues a fresh request. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_misses_an_abandoned_group() { let producer = track_producer("test", Info::timed()); @@ -16467,7 +16467,7 @@ mod test { assert!(retry.await.unwrap().read_frame().await.unwrap().is_none()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_reject_does_not_poison_retry() { let producer = track_producer("test", Info::timed()); @@ -16502,7 +16502,7 @@ mod test { /// A group cached from a frame-bounded subscription starts partway in. Serving it to /// someone who asked for the whole group would silently hand back a tail, so it is a /// miss and the fetch goes upstream instead. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_ignores_a_group_that_starts_too_late() { let producer = track_producer("test", Info::timed()); @@ -16557,7 +16557,7 @@ mod test { /// A fetch for the head of a live group the feed started partway into keeps that group /// in arrival order: subscribers get the fetched copy while it lasts, and the live /// group again once the fetch is gone. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_fills_the_head_of_a_live_group() { let producer = track_producer("test", Info::timed()); @@ -16602,7 +16602,7 @@ mod test { } /// A refused mid-group end caps none of its group's copies, even one that fit under it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_refused_end_leaves_every_copy_uncapped() { let mut producer = track_producer("test", Info::timed()); @@ -16697,7 +16697,7 @@ mod test { /// The fetched head serving a group to its end settles the declared end once it finishes, /// whether the live copy beside it was cut, evicted, or finished, and a later abort keeps /// that clean end, whether `closed()` saw it first or only the abort did. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_fetched_head_settles_the_end_once_it_finishes() { use std::sync::atomic::{AtomicBool, Ordering}; @@ -16739,7 +16739,7 @@ mod test { /// A fetched head aborting hands its group back to the live copy: a finished one settles /// the end, while a cut one leaves nothing that delivered the group, so an abort still /// cuts the track off. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn an_aborted_head_hands_the_end_back_to_the_live_copy() { use std::sync::atomic::{AtomicBool, Ordering}; @@ -16770,7 +16770,7 @@ mod test { /// A finished fetched head serves its group to the end, so the declared end settles while /// the live copy beside it is still written, and that copy aborting later keeps it clean. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_finished_head_settles_the_end_over_an_open_live_copy() { let mut producer = track_producer("test", Info::timed()); @@ -16789,7 +16789,7 @@ mod test { /// A fetched head still writing holds the largest stream open after the live copy /// aborted and the track ended, so a later head frame is reported rather than lost. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_fetched_head_holds_the_largest_open() { let producer = track_producer("test", Info::timed()); @@ -16830,7 +16830,7 @@ mod test { assert_eq!(reader.poll_largest(&noop), Poll::Ready(None)); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_live_abort_does_not_remove_a_parked_fetched_head() { let producer = track_producer("test", Info::timed()); @@ -16850,7 +16850,7 @@ mod test { /// The live copy ending early (its subscription went away) leaves a fetched head /// that still holds the whole group servable, instead of reclaiming the slot. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn aborted_live_group_keeps_its_fetched_head() { let producer = track_producer("test", Info::timed()); @@ -16869,7 +16869,7 @@ mod test { /// Reads land on the fetched head, so they keep the slot from expiring even though /// the live copy beside it sits idle. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn reading_the_head_keeps_the_slot_from_expiring() { let producer = track_producer("test", Info::timed()); @@ -16924,7 +16924,7 @@ mod test { /// A head left alone in its slot still joins the pool's access average when the /// slot is demoted, so memory pressure can evict it. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_head_only_slot_yields_to_memory_pressure() { assert!(pressure_evicts_a_headed_slot(true).await); @@ -16932,7 +16932,7 @@ mod test { /// A slot weighs its copies the way the pool's average samples them, so two copies /// with different access stamps can't keep it above the average on their own. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_two_copy_slot_yields_to_memory_pressure() { assert!(pressure_evicts_a_headed_slot(false).await); @@ -16940,7 +16940,7 @@ mod test { /// Joining a queued fetch widens its range. A caller that arrives once the range is /// already on the wire asks for its own frames rather than being handed the narrower group. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_widens_or_asks_afresh() { let producer = track_producer("test", Info::timed()); @@ -16999,7 +16999,7 @@ mod test { group.finish().unwrap(); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_coalesces_concurrent() { let producer = track_producer("test", Info::timed()); @@ -17052,7 +17052,7 @@ mod test { /// A looser caller that joined after a tighter budget went on the wire is not failed by /// that budget's `Old`: it asks again with its own. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_late_looser_fetch_asks_again_after_old() { let producer = track_producer("test", Info::timed()); @@ -17079,7 +17079,7 @@ mod test { assert_eq!(loose.await.unwrap().sequence, 5); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_coalesced_reject_fails_all() { let producer = track_producer("test", Info::timed()); @@ -17109,7 +17109,7 @@ mod test { assert_eq!(req.sequence(), 5); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_queued_fails_when_handlers_leave() { let producer = track_producer("test", Info::timed()); @@ -17127,7 +17127,7 @@ mod test { assert!(fetch.read().is_empty()); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_miss_no_dynamic_not_found() { // A track with no `Requests` can't serve old content, so a cache miss @@ -17138,7 +17138,7 @@ mod test { assert!(matches!(consumer.fetch_group(5, None).await, Err(Error::NotFound))); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_past_final_not_found() { let producer = track_producer("test", Info::timed()); @@ -17247,7 +17247,7 @@ mod test { } /// The latest group is never in the eviction order, so it survives any budget. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn latest_group_never_evicted() { // Far too small for even one group: the latest survives anyway. @@ -17268,7 +17268,7 @@ mod test { /// A FETCH cache hit refreshes the group's access time: anything accessed more /// recently than the pool-wide average is protected, so the eviction walk skips /// it and evicts a never-read group instead, even one that arrived later. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_refresh_survives_eviction() { let (mut producer, _pool) = pooled_producer(10_000); @@ -17298,7 +17298,7 @@ mod test { /// A consumer holding an evicted group surfaces the eviction, not a hang or a /// truncated clean end. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn eviction_aborts_readers() { let (mut producer, _pool) = pooled_producer(10_000); @@ -17406,7 +17406,7 @@ mod test { /// Accepting a track after pre-accept backfill must keep the same write /// counter: the counter is owned by the track state, so replacing the info /// can't strand the bytes already-created groups keep charging. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn accept_preserves_write_accounting() { let config = cache::Config::default() @@ -17600,7 +17600,7 @@ mod test { /// A backfill served before the track was accepted settles its own debt: the /// account exists from the moment the state does, so acceptance replacing the /// `Info` can't leave already-created groups writing for free. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn pre_accept_backfill_settles_late_writes() { let config = cache::Config::default() @@ -17669,7 +17669,7 @@ mod test { /// Continuously refreshed entries at the front of the eviction order must not /// starve expiry of entries behind them: the scan cursor rotates. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn refreshed_front_does_not_starve_expiry() { let (producer, _pool) = pooled_producer(1 << 40); @@ -17949,7 +17949,7 @@ mod test { /// A stale arrival entry whose sequence was later re-served by fetched backfill /// must not leak the replacement into arrival-order subscriptions. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn refilled_sequence_stays_out_of_subscriptions() { let (producer, _pool) = pooled_producer(1 << 40); @@ -17996,7 +17996,7 @@ mod test { /// An expired backfill can't hide behind a refreshed one: the eviction-order /// expiry scans a bounded prefix instead of stopping at the first fresh entry. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn expired_backfill_behind_refreshed_reclaimed() { let (producer, _pool) = pooled_producer(1 << 40); @@ -18032,7 +18032,7 @@ mod test { /// A FETCH hit within the same coarse clock tick still protects the group: the /// refresh stamps one tick ahead, so it reads strictly newer than the mean. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn same_tick_fetch_protects() { // No time advances at all: every timestamp lands in the same tick. @@ -18055,7 +18055,7 @@ mod test { /// A refetched group that reclaims max_sequence is the live edge again: it must /// not re-enter the eviction order, or memory pressure could evict the newest /// content. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn refetched_latest_stays_protected() { let (producer, _pool) = pooled_producer(10_000); @@ -18097,7 +18097,7 @@ mod test { /// An evicted group is a cache miss, so a fetch re-fetches it and the accepted /// replacement serves the sequence again (not `Error::Duplicate`). - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn eviction_allows_refetch() { let (mut producer, _pool) = pooled_producer(10_000); @@ -18166,7 +18166,7 @@ mod test { /// Lowering the floor re-offers only what the arrival walk could have read: a fetched /// group stays out of arrival order, while a live one is offered before its first frame. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_lowered_floor_reoffers_live_groups_but_not_fetched_ones() { let (producer, _pool) = pooled_producer(1 << 40); @@ -18210,7 +18210,7 @@ mod test { /// A fetched (backfill) group is served by sequence but never replayed to /// arrival-order subscribers. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetched_backfill_not_subscribed() { let (producer, _pool) = pooled_producer(1 << 40); @@ -18246,7 +18246,7 @@ mod test { /// Fetched backfill isn't in arrival order, so it ages out through the eviction /// order instead of lingering until the track closes. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn expired_backfill_reclaimed() { let (producer, pool) = pooled_producer(1 << 40); @@ -19875,7 +19875,7 @@ mod test { /// A group the source no longer has fails its fetch, and is named dropped for good only /// once the live feed gave up on it too: a fetch answered before a late group header /// arrives says nothing about the feed. - #[moq_clock::test] + #[kio::test] async fn dropped_fill_group_fails_its_fetch() { let producer = track_producer("test", Info::timed()); let dynamic = producer.requests(); @@ -19883,23 +19883,23 @@ mod test { assert!(matches!(drop_through_fill(&producer, &dynamic, true), Error::NotFound)); assert!(drops(&producer).is_empty(), "the feed may still deliver 3"); - moq_clock::sim::advance(Duration::from_secs(60)).await; + kio::clock::sim::advance(Duration::from_secs(60)).await; assert!(matches!(drop_through_fill(&producer, &dynamic, true), Error::NotFound)); assert_eq!(drops(&producer), vec![3..4], "clipped to the fill"); } /// Dropping a fill a reader still waits on names what it left as dropped. - #[moq_clock::test] + #[kio::test] async fn fill_dropped_unanswered_names_the_rest_dropped() { let producer = track_producer("test", Info::timed()); let dynamic = producer.requests(); write_group(&producer, 5); - moq_clock::sim::advance(Duration::from_secs(60)).await; + kio::clock::sim::advance(Duration::from_secs(60)).await; assert!(matches!(drop_through_fill(&producer, &dynamic, false), Error::Dropped)); assert_eq!(drops(&producer), vec![3..4]); } - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn fetch_aborts_with_track() { let producer = track_producer("test", Info::timed()); @@ -20244,7 +20244,7 @@ mod test { /// Fetched backfill past the newest produced group moves no relative start, whether the /// track had a produced group at subscribe or not. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_live_range_ignores_a_fetched_group_past_the_newest_group() { let producer = track_producer("test", Info::timed()); @@ -20744,7 +20744,7 @@ mod test { /// A drop judges the subscription, not a fetch: a fetched head still arriving keeps /// serving the group to its end after the drop ends the live copy. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_drop_spares_a_fetched_head_still_arriving() { let producer = track_producer("test", Info::timed()); @@ -21061,7 +21061,7 @@ mod test { /// A read parked on a time end's cap wakes when the speculative group starts, and when /// a later group starts inside the end while the speculative one stalls. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn a_read_parked_on_a_time_end_wakes_as_groups_start() { let at = |millis| Timestamp::from_millis(millis).unwrap(); @@ -21075,17 +21075,17 @@ mod test { }])); assert_eq!(drain(&mut subscriber), vec![0]); - let parked = moq_clock::sim::spawn(async move { + let parked = kio::clock::sim::spawn(async move { let one = subscriber.recv_group().await.unwrap().unwrap().sequence; let two = subscriber.recv_group().await.unwrap().unwrap().sequence; (one, two, subscriber) }); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; assert!(!parked.is_finished(), "1 waits on 0 starting"); groups[0] .write_frame(at(3000), bytes::Bytes::from_static(b"x")) .unwrap(); - moq_clock::sim::yield_now().await; + kio::clock::sim::yield_now().await; assert!(!parked.is_finished(), "1 is read, and 2 waits on 1 starting"); // 1 stalls, so only 2 starting inside the end lifts the cap past it. @@ -21387,7 +21387,7 @@ mod test { } /// Distinct transport starts retain delivery outcomes, but share the same indexed /// bytes even while every earlier delivery is held by an unread consumer. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn distinct_tail_readers_share_canonical_content() { for size in [0, 1, 1024] { @@ -21474,7 +21474,7 @@ mod test { /// Evicting a Slot does not hide a canonical owner from still-held older tails; /// explicitly recreating the live group, however, starts a new incarnation. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn tail_owner_survives_slot_removal_but_not_live_recreation() { let producer = track_producer("test", Info::timed()); @@ -21548,7 +21548,7 @@ mod test { /// Activation preserves an already-streaming reader and producer, and every /// delivery's progress, arrival and abort while sharing the origin's admission. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn canonical_activation_preserves_inflight_delivery_ownership() { for abort_first in [false, true] { @@ -21594,7 +21594,7 @@ mod test { second.write(vec![4; 256]).unwrap(); assert_eq!(first.remaining(), 512, "another delivery credits no progress"); assert!(streaming.read_chunk().now_or_never().is_none()); - moq_clock::sim::advance(Duration::from_millis(20)).await; + kio::clock::sim::advance(Duration::from_millis(20)).await; if abort_first { first.abort(Error::Cancel).unwrap(); assert!(budget.reserve(1).is_none(), "the survivor still holds admission"); @@ -21620,7 +21620,7 @@ mod test { ); assert_eq!(first.remaining(), 512); assert!(streaming.read_chunk().now_or_never().is_none()); - moq_clock::sim::advance(Duration::from_millis(10)).await; + kio::clock::sim::advance(Duration::from_millis(10)).await; first.write(vec![4; 512]).unwrap(); let mut first = first.finish().unwrap(); first.finish().unwrap(); @@ -21641,7 +21641,7 @@ mod test { } /// IETF Object IDs can occupy different delivery ordinals. Sharing bytes must /// preserve their typed fields and each delivery's independent terminal record. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn canonical_content_keys_typed_objects_by_id_not_ordinal() { fn wire(first: u64) -> group::Wire { @@ -21756,7 +21756,7 @@ mod test { /// Compressed transport refills keep the received slices, share one inflation, /// and continue widening hostile tail requests rather than minting local encoders. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn canonical_compressed_ingress_preserves_raw_plain_and_widening() { fn ingest(group: group::Producer, object: &frame::Object) -> group::Producer { @@ -21832,7 +21832,7 @@ mod test { let meter = registry.publisher_meter(crate::Path::new("demo").unwrap(), &stats::Tier::default()); let mut first = head.consume().with_meter(meter.clone()); assert_eq!(first.read_frame().await.unwrap().unwrap().payload, expected[0]); - moq_clock::sim::advance(Duration::from_millis(20)).await; + kio::clock::sim::advance(Duration::from_millis(20)).await; head = ingest(head, &stored[8]); head.finish().unwrap(); pending.await.unwrap(); @@ -21893,7 +21893,7 @@ mod test { /// An evicted streaming reader still owns in-flight storage until it is dropped. /// A refill must discover those same bytes without changing that reader's abort. - #[moq_clock::test] + #[kio::test] #[cfg(feature = "async")] async fn canonical_owner_follows_an_evicted_streaming_frame_reader() { let producer = track_producer("test", Info::timed()); diff --git a/rs/moq-net/src/model/track/miss.rs b/rs/moq-net/src/model/track/miss.rs index 45f5b710329..4c7dcd197c0 100644 --- a/rs/moq-net/src/model/track/miss.rs +++ b/rs/moq-net/src/model/track/miss.rs @@ -1009,7 +1009,7 @@ mod tests { use super::super::{Servable, Subscription}; use super::*; - #[moq_clock::test] + #[kio::test] async fn a_recreated_accounted_group_clears_its_earlier_fill_refusal() { let broadcast = crate::broadcast::Info::default().produce(); let mut track = broadcast @@ -1116,7 +1116,7 @@ mod tests { assert!(given_up.is_empty(), "a live recreation is never given up"); } - #[moq_clock::test] + #[kio::test] async fn an_aborted_live_group_keeps_its_earlier_fill_refusal() { let broadcast = crate::broadcast::Info::default().produce(); let mut track = broadcast @@ -1188,7 +1188,7 @@ mod tests { assert!(!asks.contains(&2), "a refused hole is not asked again"); assert_eq!(given_up, vec![2..3]); } - #[moq_clock::test] + #[kio::test] async fn unchanged_probes_and_late_arrivals_keep_other_gap_deadlines() { let broadcast = crate::broadcast::Info::default().produce(); let track = broadcast.create_track("sparse", crate::track::Info::default()).unwrap(); @@ -1283,7 +1283,7 @@ mod tests { /// A grace change with nothing deferred has no deadline to move, so an unchanged probe /// skips it; the next gap is still timed by the new grace. - #[moq_clock::test] + #[kio::test] async fn a_grace_change_with_nothing_deferred_times_the_next_gap() { let broadcast = crate::broadcast::Info::default().produce(); let track = broadcast.create_track("grace", crate::track::Info::default()).unwrap(); diff --git a/rs/moq-net/src/priority.rs b/rs/moq-net/src/priority.rs index 361ac502d7b..cd09c2864c1 100644 --- a/rs/moq-net/src/priority.rs +++ b/rs/moq-net/src/priority.rs @@ -929,7 +929,7 @@ mod tests { assert_eq!(low_track_high_group.current(), 4); // track=-78, group=100 } - #[moq_clock::test] + #[kio::test] async fn test_watch_notification_on_overflow_promotion() { let queue = PriorityQueue::default(); @@ -941,10 +941,10 @@ mod tests { assert_eq!(overflow_item.current(), u8::MAX); // Spawn task to wait for promotion from overflow - let task = moq_clock::sim::spawn(async move { overflow_item.next().await }); + let task = kio::clock::sim::spawn(async move { overflow_item.next().await }); // Give the task time to start waiting - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + kio::clock::sleep(std::time::Duration::from_millis(10)).await; // Drop highest priority item, which should promote from overflow fillers.remove(0); @@ -1046,7 +1046,7 @@ mod tests { assert_eq!(handles[1].current(), 0); } - #[moq_clock::test] + #[kio::test] async fn test_notification_on_demotion_to_overflow() { let queue = PriorityQueue::default(); @@ -1058,9 +1058,9 @@ mod tests { assert_eq!(at_edge.current(), 254); // Spawn task to wait for demotion notification - let task = moq_clock::sim::spawn(async move { at_edge.next().await }); + let task = kio::clock::sim::spawn(async move { at_edge.next().await }); - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + kio::clock::sleep(std::time::Duration::from_millis(10)).await; // Insert very high priority item, kicking at_edge to overflow let _high = queue.insert(live(127, 1000)); @@ -1113,7 +1113,7 @@ mod tests { assert_eq!(s1_g1.current(), 3); } - #[moq_clock::test] + #[kio::test] async fn test_steer_track_notifies_other_handles() { let queue = PriorityQueue::default(); @@ -1124,8 +1124,8 @@ mod tests { assert_eq!(h_low.current(), 1); // Wait for a change notification on h_low while another handle's steer runs. - let task = moq_clock::sim::spawn(async move { h_low.next().await }); - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + let task = kio::clock::sim::spawn(async move { h_low.next().await }); + kio::clock::sleep(std::time::Duration::from_millis(10)).await; // Demote h_high below h_low. h_high.steer(-118, Order::Descending); @@ -1223,7 +1223,7 @@ mod tests { assert_eq!(low.current(), 2); } - #[moq_clock::test] + #[kio::test] async fn test_steer_track_notifies_swapped_overflow_item() { let queue = PriorityQueue::default(); @@ -1236,8 +1236,8 @@ mod tests { let mut f1 = fillers.remove(0); assert_eq!(f1.current(), u8::MAX); - let task = moq_clock::sim::spawn(async move { f1.next().await }); - moq_clock::sim::yield_now().await; + let task = kio::clock::sim::spawn(async move { f1.next().await }); + kio::clock::sim::yield_now().await; // Demoting top below every filler swaps it with f1 in overflow. top.steer(-128, Order::Descending); diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index d44066b5627..56cf324becf 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -798,7 +798,7 @@ impl Handshake { }; let res = match deadline { // The guard refuses the session on the way out. - Some(at) => moq_clock::timeout_at(at, reply).await.map_err(|_| Error::Timeout)?, + Some(at) => kio::clock::timeout_at(at, reply).await.map_err(|_| Error::Timeout)?, None => reply.await, }; unanswered.answered(); @@ -1164,7 +1164,7 @@ mod tests { /// The session's own `auth()` (the handle the driver polls) routes a request token to that /// pre-ok consumer instead of falling to the `Unsupported` default, and granting admits. /// A QUIC server has no other point to install the verifier. - #[moq_clock::test] + #[kio::test] async fn a_pre_ok_verifier_governs_the_session() { let cases = [( FakeSession::new(ALPN_18, [ietf_setup(ietf::Version::Draft18, Some("room/alice"))]), @@ -1173,7 +1173,7 @@ mod tests { for (session, version) in cases { let mut request = Server::new() - .accept_request(moq_clock::now(), session) + .accept_request(kio::clock::now(), session) .await .unwrap_or_else(|e| panic!("accept at {version:?}: {e}")); @@ -1200,14 +1200,14 @@ mod tests { /// A peer that never takes the SETUP reply is refused at the handshake's deadline /// with the timeout code, and the session's stats count it. - #[moq_clock::test] + #[kio::test] async fn a_reply_the_peer_never_takes_fails_at_the_deadline() { let registry = stats::Registry::new(Default::default()); let version = Version::Lite(lite::Version::Lite02); let session = FakeSession::new(ALPN_LITE, []) .with_bi(moql_setup()) .withholding_credit(); - let start = moq_clock::now(); + let start = kio::clock::now(); let deadline = start + std::time::Duration::from_secs(10); let request = Server::new() .accept_request(start, session.clone()) @@ -1223,7 +1223,7 @@ mod tests { panic!("a reply the peer never took completed"); }; assert!(matches!(err, Error::Timeout), "{err:?}"); - assert_eq!(moq_clock::now(), deadline); + assert_eq!(kio::clock::now(), deadline); assert_eq!(session.close_code(), Some(version.session_code(&SessionError::Timeout))); let failed = registry.snapshot().sessions()[0].1.sessions_failed; assert_eq!(failed.count(stats::Failure::Application), 1, "{failed:?}"); @@ -1231,7 +1231,7 @@ mod tests { /// A reply the caller stops waiting for, as a relay does at its drain deadline, is /// refused like one past the handshake's own deadline. - #[moq_clock::test] + #[kio::test] async fn an_abandoned_reply_fails_like_the_deadline() { let registry = stats::Registry::new(Default::default()); let version = Version::Lite(lite::Version::Lite02); @@ -1239,7 +1239,7 @@ mod tests { .with_bi(moql_setup()) .withholding_credit(); let request = Server::new() - .accept_request(moq_clock::now(), session.clone()) + .accept_request(kio::clock::now(), session.clone()) .await .unwrap() .with_stats( @@ -1247,7 +1247,7 @@ mod tests { .tier(Default::default()) .session(crate::Path::from_static("room")), ); - let abandoned = moq_clock::timeout(std::time::Duration::from_secs(1), request.ok()).await; + let abandoned = kio::clock::timeout(std::time::Duration::from_secs(1), request.ok()).await; assert!(abandoned.is_err(), "a reply the peer never took completed"); assert_eq!(session.close_code(), Some(version.session_code(&SessionError::Timeout))); let failed = registry.snapshot().sessions()[0].1.sessions_failed; @@ -1256,7 +1256,7 @@ mod tests { /// A rejection counts by the code the peer is told, so a "no error" close is clean /// however this side spelled it. - #[moq_clock::test] + #[kio::test] async fn a_rejection_counts_by_its_code() { for (err, failed) in [ (Error::GoingAway, None), @@ -1266,7 +1266,7 @@ mod tests { let registry = stats::Registry::new(Default::default()); let session = FakeSession::new(ALPN_22, [ietf_setup(ietf::Version::Draft22, None)]); Server::new() - .accept_request(moq_clock::now(), session) + .accept_request(kio::clock::now(), session) .await .unwrap() .with_stats( @@ -1283,7 +1283,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn accept_request_exposes_the_setup_token() { let ietf = FakeSession::new( ALPN_22, @@ -1292,22 +1292,22 @@ mod tests { token_params(ietf::Version::Draft22), )], ); - let request = Server::new().accept_request(moq_clock::now(), ietf).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), ietf).await.unwrap(); assert_eq!(request.token(), Some(&setup_token())); } - #[moq_clock::test] + #[kio::test] async fn accept_request_without_a_token_reports_none() { let ietf = FakeSession::new(ALPN_22, [ietf_setup(ietf::Version::Draft22, None)]); let lite = FakeSession::new(ALPN_LITE_05, [lite05_setup(None, None, None)]); for (name, session) in [("draft-22", ietf), ("lite-05", lite)] { - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.token(), None, "{name}"); } } /// A SETUP the server refuses closes the session with the code naming why. - #[moq_clock::test] + #[kio::test] async fn a_refused_setup_token_closes_with_its_code() { let delete = [0x0, 0x7]; // DELETE alias 7 let truncated = [0x3]; // USE_VALUE with no Token Type @@ -1319,34 +1319,34 @@ mod tests { params.set_bytes(ietf::ParameterBytes::AuthorizationToken, raw.to_vec()); let session = FakeSession::new(ALPN_22, [ietf_setup_with(ietf::Version::Draft22, params)]); - let result = Server::new().accept_request(moq_clock::now(), session.clone()).await; + let result = Server::new().accept_request(kio::clock::now(), session.clone()).await; assert!(result.is_err()); assert_eq!(session.close_code(), Some(code.to_code()), "{code}"); } } - #[moq_clock::test] + #[kio::test] async fn accept_request_reads_ietf_path() { // Every draft gates on the SETUP stream before starting, so the // path is known at authorization time just like lite-05. for (alpn, version) in [(ALPN_18, ietf::Version::Draft18), (ALPN_22, ietf::Version::Draft22)] { let session = FakeSession::new(alpn, [ietf_setup(version, Some("/team/room"))]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), "/team/room", "{alpn}"); } } - #[moq_clock::test] + #[kio::test] async fn accept_request_ietf_without_path_is_empty() { let session = FakeSession::new(ALPN_22, [ietf_setup(ietf::Version::Draft22, None)]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), ""); } - #[moq_clock::test] + #[kio::test] async fn accept_request_ietf_empty_path_is_accepted() { let session = FakeSession::new(ALPN_22, [ietf_setup(ietf::Version::Draft22, Some(""))]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), ""); } @@ -1362,31 +1362,31 @@ mod tests { buf } - #[moq_clock::test] + #[kio::test] async fn accept_request_reads_lite05_path() { let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(Some("/team/room"), None, None)]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), "/team/room"); assert_eq!(request.role(), None, "a client that omits the role is bidirectional"); } - #[moq_clock::test] + #[kio::test] async fn accept_request_lite05_without_path_is_empty() { let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(None, None, None)]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), ""); } - #[moq_clock::test] + #[kio::test] async fn accept_request_lite05_empty_path_is_accepted() { // An empty path is valid on the wire and means the same as omitting it, so a // client that wants the root doesn't have to special-case the parameter. let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(Some(""), None, None)]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), ""); } - #[moq_clock::test] + #[kio::test] async fn uri_address_rejects_setup_path_presence() { for version in [ Version::Lite(lite::Version::Lite05), @@ -1406,7 +1406,7 @@ mod tests { let observed = session.clone(); let result = Server::new() .with_versions(version.into()) - .accept_request(moq_clock::now(), session) + .accept_request(kio::clock::now(), session) .await; assert!( matches!(result, Err(Error::ProtocolViolation)), @@ -1417,7 +1417,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn uri_address_accepts_setup_without_path() { for version in [ Version::Lite(lite::Version::Lite05), @@ -1435,63 +1435,63 @@ mod tests { session.address = crate::transport::Address::Uri; let request = Server::new() .with_versions(version.into()) - .accept_request(moq_clock::now(), session) + .accept_request(kio::clock::now(), session) .await .unwrap(); assert_eq!(request.path(), ""); } } - #[moq_clock::test] + #[kio::test] async fn accept_request_reads_lite05_role() { let session = FakeSession::new( ALPN_LITE_05, [lite05_setup(Some("/team/room"), Some(Role::Publisher), None)], ); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.role(), Some(Role::Publisher)); } - #[moq_clock::test] + #[kio::test] async fn accept_request_holds_uni_stream_before_setup() { let session = FakeSession::new( ALPN_LITE_05, [lite05_group(), lite05_setup(Some("/team/room"), None, None)], ); let stops = session.stops.clone(); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), "/team/room"); assert!(stops.lock().unwrap().is_empty(), "the early stream must stay open"); } - #[moq_clock::test] + #[kio::test] async fn accept_request_reads_buffered_setup_after_transport_close() { let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(Some("/closed"), None, None)]); crate::transport::poll::Session::close(&session, SessionError::Cancel.to_code(), "closed"); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.path(), "/closed"); } - #[moq_clock::test] + #[kio::test] async fn accepted_lite_setup_refuses_a_second_setup_stream() { let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(None, None, None)]); let transport = session.clone(); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); let (_session, mut driver) = request.ok().await.unwrap(); transport.uni.lock().unwrap().push_back(vec![1]); - let _ = driver.poll(moq_clock::now(), &kio::Waiter::noop()); + let _ = driver.poll(kio::clock::now(), &kio::Waiter::noop()); assert_eq!(transport.close_code(), Some(SessionError::ProtocolViolation.to_code())); } - #[moq_clock::test] + #[kio::test] async fn accept_request_reads_lite05_peer_hop() { let hop = Hop::new(42).unwrap(); let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(None, None, Some(hop))]); - let request = Server::new().accept_request(moq_clock::now(), session).await.unwrap(); + let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); assert_eq!(request.peer_hop(), Some(hop)); } - #[moq_clock::test] + #[kio::test] async fn anonymous_peer_hop_filters_routes_from_server_session() { let other = Hop::new(778).unwrap(); let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); @@ -1510,7 +1510,7 @@ mod tests { auth: crate::auth::Link::ietf(false), inner: Some(RequestInner { server: Server::new().with_publisher(&origin), - runtime: Deadlines::new(moq_clock::now()), + runtime: Deadlines::new(kio::clock::now()), deadline: None, handshake: PausedHandshake::Ietf(PausedIetf { session: Transport::new(transport), @@ -1550,13 +1550,13 @@ mod tests { .unwrap(); let (session, driver) = request.ok().await.unwrap(); - moq_clock::sim::spawn(crate::time::run(driver)); + kio::clock::sim::spawn(crate::time::run(driver)); for _ in 0..100 { if occurrences(&log, b"local-route") > 0 { break; } - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; } assert_eq!(occurrences(&log, b"echoed-route"), 0); diff --git a/rs/moq-net/src/tail.rs b/rs/moq-net/src/tail.rs index 0888b4a0508..476b89875a2 100644 --- a/rs/moq-net/src/tail.rs +++ b/rs/moq-net/src/tail.rs @@ -195,7 +195,7 @@ mod tests { /// The grace gives up on streams that never arrived, never on one still being read: /// its group, or the END_OF_TRACK it carries, still belongs to the track. - #[moq_clock::test] + #[kio::test] async fn the_grace_waits_for_a_stream_being_read() { let runtime = crate::time::sim(); let tail = kio::Producer::new(Tail::default()); @@ -203,7 +203,7 @@ mod tests { let mut settle = Settle::new(&runtime, tail.consume()); let mut settled = std::pin::pin!(kio::wait(|waiter| settle.poll(waiter, |_| false))); - moq_clock::sleep(GRACE * 2).await; + kio::clock::sleep(GRACE * 2).await; assert!( futures::poll!(settled.as_mut()).is_pending(), "a stream is still being read" @@ -214,13 +214,13 @@ mod tests { } /// A stream that outlives the grace still reaches `complete` once it finishes. - #[moq_clock::test] + #[kio::test] async fn completion_is_judged_after_the_grace() { let runtime = crate::time::sim(); let tail = kio::Producer::new(Tail::default()); let reading = Reading::open(&tail, Some(0), runtime.now()); let mut settle = Settle::new(&runtime, tail.consume()); - moq_clock::sleep(GRACE * 2).await; + kio::clock::sleep(GRACE * 2).await; drop(reading); let mut complete = false; @@ -235,7 +235,7 @@ mod tests { } /// A stream parked on another one does not hold the end open. - #[moq_clock::test] + #[kio::test] async fn a_parked_stream_does_not_hold_the_end() { let runtime = crate::time::sim(); let tail = kio::Producer::new(Tail::default()); diff --git a/rs/moq-net/src/time.rs b/rs/moq-net/src/time.rs index a2d9b7b4f67..680764439d5 100644 --- a/rs/moq-net/src/time.rs +++ b/rs/moq-net/src/time.rs @@ -2,8 +2,8 @@ //! //! Drivers take the current [`Instant`] on every poll and never read a clock. -pub use moq_clock::Instant; -pub(crate) use moq_clock::{Deadline, Deadlines}; +pub use kio::clock::Instant; +pub(crate) use kio::clock::{Deadline, Deadlines}; use crate::Error; @@ -23,13 +23,13 @@ pub trait Driver { #[cfg(feature = "async")] pub async fn run(driver: D) -> Error { let mut driver = Box::new(driver); - moq_clock::drive(move |now, waiter| driver.poll(now, waiter)).await + kio::clock::drive(move |now, waiter| driver.poll(now, waiter)).await } /// A deadline queue attached to the deterministic test clock. #[cfg(all(test, feature = "async"))] pub(crate) fn sim() -> Deadlines { - let deadlines = Deadlines::new(moq_clock::now()); - moq_clock::sim::attach(&deadlines); + let deadlines = Deadlines::new(kio::clock::now()); + kio::clock::sim::attach(&deadlines); deadlines } diff --git a/rs/moq-net/tests/integration/announce_covering_route.rs b/rs/moq-net/tests/integration/announce_covering_route.rs index 1567d7c4be2..9b1db074a8b 100644 --- a/rs/moq-net/tests/integration/announce_covering_route.rs +++ b/rs/moq-net/tests/integration/announce_covering_route.rs @@ -67,16 +67,16 @@ async fn covering(version: Option<&str>) -> Vec { let served = publisher.create_broadcast(SERVED).unwrap(); served.announce(Default::default()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; log.push(format!("served: {:?}", drain(&mut announced))); let below = publisher.create_broadcast(format!("{REQUESTED}/cam")).unwrap(); below.announce(Default::default()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; log.push(format!("below: {:?}", drain(&mut announced))); if let Some(pair) = pair { - let closed = moq_clock::timeout(SETTLE, pair.client.closed()).await; + let closed = kio::clock::timeout(SETTLE, pair.client.closed()).await; log.push(format!("session open: {}", closed.is_err())); } @@ -85,12 +85,12 @@ async fn covering(version: Option<&str>) -> Vec { const EXPECTED: &[&str] = &["served: [\"Start \"]", "below: [\"Start cam\"]"]; -#[moq_clock::test] +#[kio::test] async fn local_cursor_sees_the_covering_route_at_its_root() { assert_eq!(covering(None).await, EXPECTED); } -#[moq_clock::test] +#[kio::test] async fn remote_lite_peer_hears_the_covering_route() { let mut expected = EXPECTED.to_vec(); expected.push("session open: true"); @@ -105,7 +105,7 @@ async fn remote_lite_peer_hears_the_covering_route() { } } -#[moq_clock::test] +#[kio::test] async fn remote_ietf_peer_hears_the_covering_route() { let mut expected = EXPECTED.to_vec(); expected.push("session open: true"); @@ -117,7 +117,7 @@ async fn remote_ietf_peer_hears_the_covering_route() { /// A relay forwards a claim at `room` through a `**/*.chat` scope, since a path beneath it /// could match, so a request for `room/lobby.chat` is served across both hops. Listing that /// scope at the far end shows only literal matches, so the claim stays out of it. -#[moq_clock::test] +#[kio::test] async fn relays_route_a_covering_claim_that_listings_omit() { let chat = Patterns::from("**/*.chat".parse::().unwrap()); for version in [ @@ -148,20 +148,20 @@ async fn relays_route_a_covering_claim_that_listings_omit() { let scoped = client.consume().scope("", &chat).unwrap(); let mut listed = scoped.announced(); let mut covering = scoped.clone().covering().announced(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; assert_eq!(drain(&mut listed), ["Start lobby.chat"], "{version}"); let mut routes = drain(&mut covering); routes.sort(); assert_eq!(routes, ["Start lobby.chat", "Start room"], "{version}"); // The claim is asked once something subscribes beneath it. - let broadcast = moq_clock::timeout(SETTLE, scoped.request("room/lobby.chat", None)) + let broadcast = kio::clock::timeout(SETTLE, scoped.request("room/lobby.chat", None)) .await .expect("the request resolved") .unwrap(); let track = broadcast.track("video").unwrap(); - let _subscribing = moq_clock::sim::spawn(async move { track.subscribe(None).await.map(drop) }); - let request = moq_clock::timeout(SETTLE, claim.requested_broadcast()) + let _subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await.map(drop) }); + let request = kio::clock::timeout(SETTLE, claim.requested_broadcast()) .await .expect("the request crossed both hops") .unwrap(); diff --git a/rs/moq-net/tests/integration/announce_takeover.rs b/rs/moq-net/tests/integration/announce_takeover.rs index 98f60748698..dc966434ba7 100644 --- a/rs/moq-net/tests/integration/announce_takeover.rs +++ b/rs/moq-net/tests/integration/announce_takeover.rs @@ -31,7 +31,7 @@ async fn link(version: Version, from: &origin::Producer, to: &origin::Producer, /// Let every task settle. Time is paused, so this returns once the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// A worker claiming `claim`, answering each request with an output whose `video` track @@ -48,7 +48,7 @@ impl Worker { let claim = Rc::new(origin.requests(claim).unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (claim.clone(), outputs.clone()); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(request) = handler.requested_broadcast().await { let prepared = request.prepare(Epoch::mint()).unwrap(); let track = prepared @@ -75,7 +75,7 @@ impl Worker { /// Every announce event already delivered, as `(kind, prefix, predecessor)`. async fn drain(announced: &mut announce::Consumer) -> Vec<(&'static str, String, Option)> { let mut events = Vec::new(); - while let Ok(event) = moq_clock::timeout(Duration::from_secs(1), announced.next()).await { + while let Ok(event) = kio::clock::timeout(Duration::from_secs(1), announced.next()).await { events.push(match event.expect("announce ended") { announce::Event::Start(a) => ("start", a.prefix.to_string(), None), announce::Event::Update(a) => ("update", a.prefix.to_string(), None), @@ -93,7 +93,7 @@ async fn drain(announced: &mut announce::Consumer) -> Vec<(&'static str, String, async fn watch(origin: &origin::Producer, path: &str) -> String { let broadcast = origin.consume().request(path, None).await.unwrap(); let mut subscription = broadcast.track("video").unwrap().subscribe(None).await.unwrap(); - let mut group = moq_clock::timeout(Duration::from_secs(10), subscription.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(10), subscription.recv_group()) .await .expect("subscription hung") .expect("the first subscription was reset") @@ -160,9 +160,9 @@ async fn chain(version: &str, claim: &str) { macro_rules! chain_tests { ($($name:ident: $version:literal, $claim:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, chain($version, $claim)) + kio::clock::timeout(TEST_TIMEOUT, chain($version, $claim)) .await .expect("timed out"); } @@ -180,9 +180,9 @@ chain_tests! { /// Two workers claim `pool` on `R`. Whichever answers, `R` cannot tell a reader of the /// claim which worker it saw, so the answer is a start, while `R`'s own reader still /// keeps reading from the worker it was routed to. -#[moq_clock::test] +#[kio::test] async fn two_workers_announce_a_start() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-lite-07-wip".parse().unwrap(); let relay = produce_origin(3); let a = Worker::new(1, "pool", "a"); @@ -208,9 +208,9 @@ async fn two_workers_announce_a_start() { /// A broadcast published at the path without answering a request is no takeover, even /// from the worker holding the claim, and a reader through the claim does not inherit it. -#[moq_clock::test] +#[kio::test] async fn an_unrequested_publish_is_a_start() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-lite-07-wip".parse().unwrap(); let worker = Worker::new(1, "pool", "w"); let relay = produce_origin(2); @@ -230,9 +230,9 @@ async fn an_unrequested_publish_is_a_start() { /// `W -> R` on lite-07 and `R -> E` on lite-06: the relay keeps its reader through the /// takeover and forwards it to the older edge as a start. -#[moq_clock::test] +#[kio::test] async fn an_older_downstream_gets_a_start() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let worker = Worker::new(1, "pool", "w"); let relay = produce_origin(2); let edge = produce_origin(3); diff --git a/rs/moq-net/tests/integration/announce_to_serve.rs b/rs/moq-net/tests/integration/announce_to_serve.rs index 26525e39483..35895427298 100644 --- a/rs/moq-net/tests/integration/announce_to_serve.rs +++ b/rs/moq-net/tests/integration/announce_to_serve.rs @@ -87,7 +87,7 @@ async fn read(broadcast: &moq_net::broadcast::Consumer, name: &str) -> mpsc::Unb .await .expect("subscribe"); let (tx, rx) = mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { loop { let mut group = match sub.recv_group().await { Ok(Some(group)) => group, @@ -114,7 +114,7 @@ async fn read(broadcast: &moq_net::broadcast::Consumer, name: &str) -> mpsc::Unb /// The reader's next report, or `stalled` if nothing arrives in time. async fn next(rx: &mut mpsc::UnboundedReceiver) -> String { - match moq_clock::timeout(SETTLE, rx.next()).await { + match kio::clock::timeout(SETTLE, rx.next()).await { Ok(Some(report)) => report, _ => "stalled".to_string(), } @@ -147,7 +147,7 @@ async fn lifecycle(observer: Observer) -> Vec { // Created, not yet announced: nobody can see or reach it. let broadcast = publisher.create_broadcast(PATH).unwrap(); let track = broadcast.create_track("video", timed()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; log.push(format!( "created: {:?} {}", drain(&mut announced), @@ -156,14 +156,14 @@ async fn lifecycle(observer: Observer) -> Vec { // Announced: listed, and a request resolves. broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let first = request(&consumer).await; log.push(format!("announced: {:?} {}", drain(&mut announced), outcome(&first))); let first = first.expect("an announced broadcast resolves"); // A track in flight across the unannounce. let mut reader = read(&first, "video").await; - moq_clock::timeout(SETTLE, crate::support::wanted(track.demand())) + kio::clock::timeout(SETTLE, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); @@ -174,7 +174,7 @@ async fn lifecycle(observer: Observer) -> Vec { // than joining the broadcast still draining, which ends, while the track // already in flight carries on to its own end. broadcast.unannounce(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; log.push(format!( "unannounced: {:?} {} closed={}", drain(&mut announced), @@ -191,7 +191,7 @@ async fn lifecycle(observer: Observer) -> Vec { // Announced again: listed and servable, through a fresh broadcast. broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let again = request(&consumer).await; log.push(format!( "reannounced: {:?} {} fresh={}", @@ -203,7 +203,7 @@ async fn lifecycle(observer: Observer) -> Vec { let audio = broadcast.create_track("audio", timed()).unwrap(); let mut reader = read(&again, "audio").await; - moq_clock::timeout(SETTLE, crate::support::wanted(audio.demand())) + kio::clock::timeout(SETTLE, crate::support::wanted(audio.demand())) .await .expect("no subscriber appeared after reannouncing") .unwrap(); @@ -223,17 +223,17 @@ const EXPECTED: &[&str] = &[ "serving again: again", ]; -#[moq_clock::test] +#[kio::test] async fn local_consumer_sees_only_announced_broadcasts() { assert_eq!(lifecycle(Observer::Local).await, EXPECTED); } -#[moq_clock::test] +#[kio::test] async fn remote_lite_consumer_sees_what_a_local_one_does() { assert_eq!(lifecycle(Observer::Remote("moq-lite-05")).await, EXPECTED); } -#[moq_clock::test] +#[kio::test] async fn remote_ietf_consumer_sees_what_a_local_one_does() { // Each request has its own stream, which has to end a finished track the way // moq-lite does. diff --git a/rs/moq-net/tests/integration/auth.rs b/rs/moq-net/tests/integration/auth.rs index 2951f854752..a73dd8d4abe 100644 --- a/rs/moq-net/tests/integration/auth.rs +++ b/rs/moq-net/tests/integration/auth.rs @@ -39,13 +39,13 @@ const MOQT_22: &str = "moq-transport-22"; macro_rules! cases { ($($case:ident),* $(,)?) => { mod lite_07 { - $(#[moq_clock::test] async fn $case() { super::$case(super::LITE_07).await })* + $(#[kio::test] async fn $case() { super::$case(super::LITE_07).await })* } mod moqt_18 { - $(#[moq_clock::test] async fn $case() { super::$case(super::MOQT_18).await })* + $(#[kio::test] async fn $case() { super::$case(super::MOQT_18).await })* } mod moqt_22 { - $(#[moq_clock::test] async fn $case() { super::$case(super::MOQT_22).await })* + $(#[kio::test] async fn $case() { super::$case(super::MOQT_22).await })* } }; } @@ -81,23 +81,23 @@ cases!( ); /// moq-transport's AUTH_ERROR carries no code that may pass, so only lite retries. -#[moq_clock::test] +#[kio::test] async fn lite_07_presents_a_transiently_refused_token_again() { a_transient_refusal_is_presented_again(LITE_07).await } /// moq-transport's u16 message size is the one a test can overflow quickly. -#[moq_clock::test] +#[kio::test] async fn moqt_18_a_grant_too_large_for_one_message_is_unsupported() { a_grant_too_large_for_one_message_is_unsupported(MOQT_18).await } -#[moq_clock::test] +#[kio::test] async fn moqt_22_a_grant_too_large_for_one_message_is_unsupported() { a_grant_too_large_for_one_message_is_unsupported(MOQT_22).await } -#[moq_clock::test] +#[kio::test] async fn lite_06_has_no_grant() { older_versions_have_no_grant(LITE_06).await } @@ -105,7 +105,7 @@ async fn lite_06_has_no_grant() { /// The control for the lite versions without AUTH: on the same barrier, lite-07 has /// opened an Auth Stream on each side, which is what makes its absence on them mean /// something. -#[moq_clock::test] +#[kio::test] async fn lite_07_opens_an_auth_stream_per_side() { within(async { let (pair, _broadcast) = connect_announced(LITE_07).await; @@ -121,22 +121,22 @@ async fn lite_07_opens_an_auth_stream_per_side() { .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn lite_05_has_no_grant() { older_versions_have_no_grant("moq-lite-05").await } -#[moq_clock::test] +#[kio::test] async fn moqt_22_route_auth_renews_its_announce() { a_route_auth_renews_its_announce(MOQT_22).await } -#[moq_clock::test] +#[kio::test] async fn moqt_22_route_auth_survives_a_reconnect() { a_route_auth_survives_a_reconnect(MOQT_22).await } -#[moq_clock::test] +#[kio::test] async fn moqt_22_renewing_a_cancelled_announce_keeps_the_session() { within(async { let (mut pair, client_origin, _server_origin) = connect_route_auth(MOQT_22).await; @@ -153,7 +153,7 @@ async fn moqt_22_renewing_a_cancelled_announce_keeps_the_session() { drop(first); let (token, _again) = tokens.next().await.expect("offered again after the cancel"); assert_eq!(token, b"first"); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let (second, _) = pair.client.auth().add("second").await.expect("kept for requests"); broadcast.announce(origin::Route::default().with_auth(second)).unwrap(); let (token, _second) = tokens.next().await.expect("announced again"); @@ -164,7 +164,7 @@ async fn moqt_22_renewing_a_cancelled_announce_keeps_the_session() { .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn moqt_22_a_cancelled_renewal_keeps_the_session() { within(async { let (mut pair, client_origin, _server_origin) = connect_route_auth(MOQT_22).await; @@ -180,9 +180,9 @@ async fn moqt_22_a_cancelled_renewal_keeps_the_session() { let (second, _) = pair.client.auth().add("second").await.expect("kept for requests"); broadcast.announce(origin::Route::default().with_auth(second)).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; drop(first); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(pair.client_transport.close_reason(), None); }) .await @@ -192,7 +192,7 @@ async fn moqt_22_a_cancelled_renewal_keeps_the_session() { /// An acceptor that accepts a renewal and drops the grant it replaces in one step keeps the /// announcement: the old grant ending is not the request ending once its replacement is in. /// The replacement then holds it, so an update that stops covering it ends it. -#[moq_clock::test] +#[kio::test] async fn moqt_22_dropping_the_old_grant_with_its_renewal_keeps_the_announce() { within(async { let (mut pair, client_origin, server_origin) = connect_route_auth(MOQT_22).await; @@ -214,7 +214,7 @@ async fn moqt_22_dropping_the_old_grant_with_its_renewal_keeps_the_announce() { let second = renewal.accept(Grant::all()); drop(first); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( futures::FutureExt::now_or_never(second.closed()).is_none(), "the request ended with the grant its renewal replaced" @@ -230,7 +230,7 @@ async fn moqt_22_dropping_the_old_grant_with_its_renewal_keeps_the_announce() { /// A route auth the peer revokes on its AUTH stream is no longer carried, so its request is /// made again without it, even while another token keeps the session's grant unchanged. -#[moq_clock::test] +#[kio::test] async fn moqt_22_a_revoked_route_auth_remakes_its_announce() { within(async { let client_origin = produce_origin(2); @@ -449,7 +449,7 @@ struct Pair { /// The SETUP token the server's handshake read. setup_token: Option, /// Aborting it drops the server's driver without letting it finish. - server_driver: moq_clock::sim::JoinHandle, + server_driver: kio::clock::sim::JoinHandle, } async fn connect(opts: Options) -> Pair { @@ -505,7 +505,7 @@ async fn connect(opts: Options) -> Pair { // Taken before the session starts, the way a relay verifying tokens would. let requests = opts.server_requests.then(|| handshake.requests()); let (session, mut driver) = handshake.ok().await.expect("server accept"); - let driver = moq_clock::sim::spawn(moq_clock::drive(move |now, waiter| { + let driver = kio::clock::sim::spawn(kio::clock::drive(move |now, waiter| { moq_net::time::Driver::poll(&mut driver, now, waiter) })); (session, requests, setup_token, driver) @@ -530,7 +530,7 @@ fn serve( answer: impl Fn(&[u8]) -> Option + 'static, ) -> futures::channel::mpsc::UnboundedReceiver<(Vec, auth::Issued)> { let (tx, rx) = futures::channel::mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let mut unanswered = Vec::new(); while let Some(request) = requests.next().await { let token = request.token().to_vec(); @@ -545,8 +545,8 @@ fn serve( rx } -fn within(f: F) -> impl std::future::Future> { - moq_clock::timeout(TEST_TIMEOUT, f) +fn within(f: F) -> impl std::future::Future> { + kio::clock::timeout(TEST_TIMEOUT, f) } /// Each side's default grant is what the other side's origin handles allow: @@ -672,11 +672,11 @@ async fn an_unanswered_token_holds_the_check(version: &'static str) { let _setup = requests.next().await.unwrap().accept(grant(&["baz"], &[])); assert_eq!(granted(&pair.client).await, grant(&["baz"], &[])); let auth = pair.client.auth(); - let pending = moq_clock::sim::spawn(async move { auth.add("new").await }); + let pending = kio::clock::sim::spawn(async move { auth.add("new").await }); let unanswered = requests.next().await.unwrap(); let broadcast = publisher.create_broadcast("foo/bar").unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; use futures::FutureExt; assert!( pair.server.closed().now_or_never().is_none(), @@ -714,13 +714,13 @@ async fn a_broadcast_withdrawn_while_its_token_waits_is_not_refused(version: &'s let _setup = requests.next().await.unwrap().accept(grant(&["baz"], &[])); assert_eq!(granted(&pair.client).await, grant(&["baz"], &[])); let auth = pair.client.auth(); - let pending = moq_clock::sim::spawn(async move { auth.add("new").await }); + let pending = kio::clock::sim::spawn(async move { auth.add("new").await }); let unanswered = requests.next().await.unwrap(); let withdrawn = publisher.create_broadcast("foo/bar").unwrap(); withdrawn.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; withdrawn.unannounce(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let _issued = unanswered.accept(grant(&["other"], &[])); let _token = pending.await.unwrap().unwrap(); assert_eq!(granted(&pair.client).await, grant(&["baz", "other"], &[])); @@ -862,7 +862,7 @@ async fn a_refused_token_reports_the_code(version: &'static str) { }) .await; let mut requests = pair.requests.take().unwrap(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { while let Some(request) = requests.next().await { match request.token().is_empty() { true => { @@ -897,7 +897,7 @@ async fn a_refused_setup_token_grants_nothing(version: &'static str) { }) .await; let mut requests = pair.requests.take().unwrap(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { while let Some(request) = requests.next().await { request.reject(SessionError::Unauthorized, "bad credential"); } @@ -937,7 +937,7 @@ async fn the_setup_token_is_the_connection_credential(version: &'static str) { /// A lite version without the Token parameter carries none, so the caller's URL query /// has to. -#[moq_clock::test] +#[kio::test] async fn lite_06_sends_no_setup_token() { within(async { let pair = connect(Options { @@ -967,9 +967,9 @@ async fn dropping_the_requests_refuses_queued_tokens(version: &'static str) { let first = requests.next().await.expect("setup token"); drop(first.accept(Grant::default())); let auth = pair.client.auth(); - let pending = moq_clock::sim::spawn(async move { auth.add("queued").await.map(drop) }); + let pending = kio::clock::sim::spawn(async move { auth.add("queued").await.map(drop) }); // Give the second token time to reach the queue before dropping it. - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; drop(requests); let err = pending.await.unwrap().expect_err("refused"); @@ -1479,7 +1479,7 @@ async fn nothing_outside_the_grant_reaches_the_peer(version: &'static str) { // Hold the answer, so the peer's discovery request is in long before the grant. let mut requests = pair.requests.take().unwrap(); let setup = requests.next().await.expect("setup token"); - let leaked = moq_clock::timeout( + let leaked = kio::clock::timeout( Duration::from_millis(100), wait_announced(&relay.consume(), "foo/bar", true), ) @@ -1537,16 +1537,16 @@ async fn a_broadcast_received_from_the_peer_is_not_ours_to_check(version: &'stat macro_rules! limit_cases { ($($case:ident),* $(,)?) => { mod limit_lite_05 { - $(#[moq_clock::test] async fn $case() { super::$case("moq-lite-05").await })* + $(#[kio::test] async fn $case() { super::$case("moq-lite-05").await })* } mod limit_lite_06 { - $(#[moq_clock::test] async fn $case() { super::$case(super::LITE_06).await })* + $(#[kio::test] async fn $case() { super::$case(super::LITE_06).await })* } mod limit_lite_07 { - $(#[moq_clock::test] async fn $case() { super::$case(super::LITE_07).await })* + $(#[kio::test] async fn $case() { super::$case(super::LITE_07).await })* } mod limit_moqt_18 { - $(#[moq_clock::test] async fn $case() { super::$case(super::MOQT_18).await })* + $(#[kio::test] async fn $case() { super::$case(super::MOQT_18).await })* } }; } @@ -1558,17 +1558,17 @@ limit_cases!( a_widening_brings_back_what_the_peer_published, ); -#[moq_clock::test] +#[kio::test] async fn lite_05_narrowing_resets_a_fetch_in_flight() { a_narrowing_resets_a_fetch_in_flight("moq-lite-05").await } -#[moq_clock::test] +#[kio::test] async fn lite_06_narrowing_resets_a_fetch_in_flight() { a_narrowing_resets_a_fetch_in_flight(LITE_06).await } -#[moq_clock::test] +#[kio::test] async fn lite_07_narrowing_resets_a_fetch_in_flight() { a_narrowing_resets_a_fetch_in_flight(LITE_07).await } @@ -1936,7 +1936,7 @@ async fn a_widening_brings_back_what_the_peer_published(version: &'static str) { async fn a_shared_handle_presents_its_token_on_every_session(version: &'static str) { within(async { let handle = auth::Handle::new(); - let added = moq_clock::sim::spawn({ + let added = kio::clock::sim::spawn({ let handle = handle.clone(); async move { handle.add("token").await } }); @@ -2011,7 +2011,7 @@ async fn a_handle_backs_one_active_session(version: &'static str) { }; let mut first = connect(options()).await; let mut first_requests = first.requests.take().unwrap(); - let added = moq_clock::sim::spawn({ + let added = kio::clock::sim::spawn({ let handle = handle.clone(); async move { handle.add("token").await } }); @@ -2046,13 +2046,13 @@ async fn a_handle_backs_one_active_session(version: &'static str) { let _second_issued = presented(&mut second_tokens).await; let _token = added.await.expect("joined").expect("granted on the second session"); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( unanswered.closed().now_or_never().is_none(), "the draining session withdrew its unanswered token" ); let first_grant = unanswered.accept(Grant::all()); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( first_grant.closed().now_or_never().is_none(), "the draining session dropped its late grant" @@ -2094,7 +2094,7 @@ async fn a_token_queued_before_our_goaway_rides_only_the_successor(version: &'st let mut adding = Box::pin(handle.add("late")); assert!(adding.as_mut().now_or_never().is_none()); first.client.drain().send(moq_net::goaway::Goaway::new()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( first_tokens.next().now_or_never().is_none(), "the draining session presented a new token" @@ -2128,7 +2128,7 @@ async fn a_transient_refusal_is_presented_again(version: &'static str) { .await; let mut requests = pair.requests.take().unwrap(); let (tx, mut issued) = futures::channel::mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let mut refused = false; while let Some(request) = requests.next().await { if request.token().is_empty() || refused { diff --git a/rs/moq-net/tests/integration/broadcast_close.rs b/rs/moq-net/tests/integration/broadcast_close.rs index c8711b5c234..cd65a8ca432 100644 --- a/rs/moq-net/tests/integration/broadcast_close.rs +++ b/rs/moq-net/tests/integration/broadcast_close.rs @@ -27,7 +27,7 @@ async fn close_then_lookup(publisher: moq_net::origin::Producer, reader: moq_net broadcast.announce(Default::default()).unwrap(); let consumer = reader.consume(); - let handle = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let handle = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -35,7 +35,7 @@ async fn close_then_lookup(publisher: moq_net::origin::Producer, reader: moq_net broadcast.close(); - moq_clock::timeout(TIMEOUT, handle.closed()) + kio::clock::timeout(TIMEOUT, handle.closed()) .await .expect("the handle never closed"); assert!(matches!(handle.track("video"), Err(Error::Unroutable))); @@ -44,13 +44,13 @@ async fn close_then_lookup(publisher: moq_net::origin::Producer, reader: moq_net assert!(matches!(broadcast.announce(Default::default()), Err(Error::Closed))); } -#[moq_clock::test] +#[kio::test] async fn close_ends_a_local_consumer() { let origin = produce_origin(1); close_then_lookup(origin.clone(), origin).await; } -#[moq_clock::test] +#[kio::test] async fn close_ends_a_remote_consumer() { for version in ["moq-lite-05", "moq-transport-18"] { let publisher = produce_origin(1); diff --git a/rs/moq-net/tests/integration/catalog_acquisition.rs b/rs/moq-net/tests/integration/catalog_acquisition.rs index 78b3430fc64..f18f1cf9bf3 100644 --- a/rs/moq-net/tests/integration/catalog_acquisition.rs +++ b/rs/moq-net/tests/integration/catalog_acquisition.rs @@ -78,12 +78,12 @@ async fn acquisition(version: &str, carries_epoch: bool) { } } -#[moq_clock::test] +#[kio::test] async fn epochless_replacement_refuses_pending_catalog() { acquisition("moq-lite-06", false).await; } -#[moq_clock::test] +#[kio::test] async fn same_epoch_replacement_acquires_pending_catalog() { acquisition("moq-lite-07-wip", true).await; acquisition("moq-transport-18", true).await; diff --git a/rs/moq-net/tests/integration/catalog_churn.rs b/rs/moq-net/tests/integration/catalog_churn.rs index f7223fe1abd..8f2890e6510 100644 --- a/rs/moq-net/tests/integration/catalog_churn.rs +++ b/rs/moq-net/tests/integration/catalog_churn.rs @@ -134,7 +134,7 @@ struct Reader { expected: Vec, seen: Vec, /// Owns the subscription, so dropping the reader leaves the track. - task: moq_clock::sim::JoinHandle<()>, + task: kio::clock::sim::JoinHandle<()>, } impl Drop for Reader { @@ -146,7 +146,7 @@ impl Drop for Reader { impl Reader { fn new(id: usize, mut sub: track::Subscriber, expected: Vec) -> Self { let (tx, rx) = mpsc::unbounded(); - let task = moq_clock::sim::spawn(async move { + let task = kio::clock::sim::spawn(async move { loop { let mut group = match sub.recv_group().await { Ok(Some(group)) => group, @@ -266,7 +266,7 @@ impl Topology { /// A fresh request for the broadcast; `None` when refused, as with no route right now. async fn request(&self, step: usize) -> Result, Failure> { let request = self.subscriber.consume().request("live", None); - match moq_clock::timeout(READ_TIMEOUT, request).await { + match kio::clock::timeout(READ_TIMEOUT, request).await { Ok(result) => Ok(result.ok()), Err(_) => Err(stuck(format!("{step}: request hung"))), } @@ -331,14 +331,14 @@ async fn execute(version: Version, ops: &[Op]) -> Result<(), Failure> { written.clear(); write(&mut group, &mut written, &mut readers, "snapshot"); // Let it reach `R`, so the newest group at the next join is unambiguous. - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } Op::Join => { let Some(remote) = topology.request(step).await? else { continue; }; let subscribe = remote.track("catalog.json").unwrap().subscribe(None); - match moq_clock::timeout(READ_TIMEOUT, subscribe).await { + match kio::clock::timeout(READ_TIMEOUT, subscribe).await { Ok(Ok(sub)) => readers.push(Reader::new(joined, sub, written.clone())), Ok(Err(_)) => {} Err(_) => return Err(stuck(format!("{step}: subscribe hung"))), @@ -350,14 +350,14 @@ async fn execute(version: Version, ops: &[Op]) -> Result<(), Failure> { continue; }; let fetch = remote.track("catalog.json").unwrap().fetch_group(group.sequence, None); - let mut fetched = match moq_clock::timeout(READ_TIMEOUT, fetch).await { + let mut fetched = match kio::clock::timeout(READ_TIMEOUT, fetch).await { Ok(Ok(fetched)) => fetched, Ok(Err(_)) => continue, Err(_) => return Err(stuck(format!("{step}: fetch hung"))), }; let mut got = Vec::new(); while got.len() < written.len() { - match moq_clock::timeout(READ_TIMEOUT, fetched.read_frame()).await { + match kio::clock::timeout(READ_TIMEOUT, fetched.read_frame()).await { Ok(Ok(Some(frame))) => got.push(format!( "{}:{}", fetched.sequence, @@ -380,9 +380,9 @@ async fn execute(version: Version, ops: &[Op]) -> Result<(), Failure> { Op::ToggleA => topology.toggle(0).await, Op::ToggleB => topology.toggle(1).await, Op::ToggleDirect => topology.toggle(2).await, - Op::Sleep(pause) => moq_clock::sleep(pause).await, + Op::Sleep(pause) => kio::clock::sleep(pause).await, Op::Check => { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; let mut failed = Vec::new(); for (index, reader) in readers.iter_mut().enumerate() { let open = reader.drain(); @@ -392,7 +392,7 @@ async fn execute(version: Version, ops: &[Op]) -> Result<(), Failure> { _ if !open => failed.push(index), Verdict::Done => {} Verdict::Short => { - let _ = moq_clock::timeout(STUCK_AFTER, async { + let _ = kio::clock::timeout(STUCK_AFTER, async { while reader.judge() == Verdict::Short { match reader.rx.next().await { Some(Ok(frame)) => reader.seen.push(frame), @@ -448,13 +448,13 @@ async fn churn(version: &str) { } /// Routes carry the publisher's epoch, so subscriptions resume across them. -#[moq_clock::test] +#[kio::test] async fn catalog_churn_lite_07() { churn("moq-lite-07-wip").await; } /// No epoch on the wire: a route change ends subscriptions, which must fail loudly. -#[moq_clock::test] +#[kio::test] async fn catalog_churn_lite_06() { churn("moq-lite-06").await; } diff --git a/rs/moq-net/tests/integration/catalog_handover.rs b/rs/moq-net/tests/integration/catalog_handover.rs index ad833752fe9..8dcdea5b67a 100644 --- a/rs/moq-net/tests/integration/catalog_handover.rs +++ b/rs/moq-net/tests/integration/catalog_handover.rs @@ -55,7 +55,7 @@ fn abort(pair: MockPair) { /// Let every task settle. Time is paused, so this returns once the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// How the serving route changes. @@ -167,11 +167,11 @@ impl Topology { /// A new reader on `R`: a fresh broadcast request and a floorless subscription. async fn reader(&self) -> Reader { - let remote = moq_clock::timeout(READ_TIMEOUT, self.subscriber.consume().request("live", None)) + let remote = kio::clock::timeout(READ_TIMEOUT, self.subscriber.consume().request("live", None)) .await .expect("request hung") .expect("request refused"); - let sub = moq_clock::timeout(READ_TIMEOUT, remote.track("catalog.json").unwrap().subscribe(None)) + let sub = kio::clock::timeout(READ_TIMEOUT, remote.track("catalog.json").unwrap().subscribe(None)) .await .expect("subscribe hung") .expect("subscribe refused"); @@ -184,7 +184,7 @@ impl Topology { struct Reader { rx: mpsc::UnboundedReceiver>, /// Owns the subscription, so dropping the reader leaves the track. - task: moq_clock::sim::JoinHandle<()>, + task: kio::clock::sim::JoinHandle<()>, } impl Drop for Reader { @@ -196,7 +196,7 @@ impl Drop for Reader { impl Reader { fn new(mut sub: track::Subscriber) -> Self { let (tx, rx) = mpsc::unbounded(); - let task = moq_clock::sim::spawn(async move { + let task = kio::clock::sim::spawn(async move { loop { let mut group = match sub.recv_group().await { Ok(Some(group)) => group, @@ -232,7 +232,7 @@ impl Reader { async fn take(&mut self, n: usize, who: &str) -> Vec { let mut frames = Vec::new(); while frames.len() < n { - match moq_clock::timeout(READ_TIMEOUT, self.rx.next()).await { + match kio::clock::timeout(READ_TIMEOUT, self.rx.next()).await { Ok(Some(Ok(frame))) => frames.push(frame), Ok(Some(Err(err))) => panic!("{who}: failed after {frames:?}: {err}"), Ok(None) => panic!("{who}: ended after {frames:?}"), @@ -250,7 +250,7 @@ impl Reader { /// The subscription fails or ends, rather than hanging or delivering more. async fn expect_end(&mut self, who: &str) { - match moq_clock::timeout(READ_TIMEOUT, self.rx.next()).await { + match kio::clock::timeout(READ_TIMEOUT, self.rx.next()).await { Ok(None | Some(Err(_))) => {} Ok(Some(Ok(frame))) => panic!("{who}: delivered {frame:?} past its route"), Err(_) => panic!("{who}: hung instead of ending"), @@ -322,7 +322,7 @@ async fn handover(version: &str, trigger: Trigger, holder: Holder) { assert_eq!(viewer.take(1, &tag).await, ["0:delta3"], "{tag}: viewer continues"); } // Returning well past the relays' idle linger, so no copy of the head is warm. - moq_clock::sleep(RETURN_AFTER).await; + kio::clock::sleep(RETURN_AFTER).await; let mut returning = topology.reader().await; returning.expect_all(&topology, &format!("{tag}: returning")).await; @@ -365,14 +365,14 @@ async fn late_reader(version: &str, before: Before) { Before::Resume => { settle().await; drop(first); - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; let mut resumed = topology.reader().await; resumed.expect_all(&topology, &format!("{tag}: resumed")).await; resumed } }; - moq_clock::sleep(RETURN_AFTER).await; + kio::clock::sleep(RETURN_AFTER).await; let mut late = topology.reader().await; late.expect_all(&topology, &format!("{tag}: late")).await; } @@ -389,17 +389,17 @@ async fn fetch_after_leave(version: &str, pause: Duration) { reader.expect_all(&topology, &format!("{tag}: reader")).await; topology.write("delta1"); drop(reader); - moq_clock::sleep(pause).await; + kio::clock::sleep(pause).await; let remote = topology.subscriber.consume().request("live", None).await.unwrap(); let fetch = remote.track("catalog.json").unwrap().fetch_group(0, None); - let mut group = moq_clock::timeout(READ_TIMEOUT, fetch) + let mut group = kio::clock::timeout(READ_TIMEOUT, fetch) .await .unwrap_or_else(|_| panic!("{tag}: fetch hung")) .unwrap_or_else(|err| panic!("{tag}: fetch refused: {err}")); let mut got = Vec::new(); while got.len() < topology.written.len() { - match moq_clock::timeout(READ_TIMEOUT, group.read_frame()).await { + match kio::clock::timeout(READ_TIMEOUT, group.read_frame()).await { Ok(Ok(Some(frame))) => got.push(String::from_utf8_lossy(&frame.payload).to_string()), Ok(Ok(None)) => panic!("{tag}: fetch ended after {got:?}"), Ok(Err(err)) => panic!("{tag}: fetch failed after {got:?}: {err}"), @@ -416,61 +416,61 @@ macro_rules! handover_tests { use super::*; async fn run(trigger: Trigger, holder: Holder) { - moq_clock::timeout(TEST_TIMEOUT, handover($version, trigger, holder)) + kio::clock::timeout(TEST_TIMEOUT, handover($version, trigger, holder)) .await .expect("timed out"); } - #[moq_clock::test] + #[kio::test] async fn disconnect_with_viewer() { run(Trigger::Disconnect, Holder::Viewer).await; } - #[moq_clock::test] + #[kio::test] async fn disconnect_parked() { run(Trigger::Disconnect, Holder::Parked).await; } - #[moq_clock::test] + #[kio::test] async fn unannounce_with_viewer() { run(Trigger::Unannounce, Holder::Viewer).await; } - #[moq_clock::test] + #[kio::test] async fn unannounce_parked() { run(Trigger::Unannounce, Holder::Parked).await; } - #[moq_clock::test] + #[kio::test] async fn better_route_with_viewer() { run(Trigger::BetterRoute, Holder::Viewer).await; } - #[moq_clock::test] + #[kio::test] async fn better_route_parked() { run(Trigger::BetterRoute, Holder::Parked).await; } - #[moq_clock::test] + #[kio::test] async fn reconnect_with_viewer() { run(Trigger::Reconnect, Holder::Viewer).await; } - #[moq_clock::test] + #[kio::test] async fn reconnect_parked() { run(Trigger::Reconnect, Holder::Parked).await; } - #[moq_clock::test] + #[kio::test] async fn late_reader_after_route_change() { - moq_clock::timeout(TEST_TIMEOUT, late_reader($version, Before::RouteChange)) + kio::clock::timeout(TEST_TIMEOUT, late_reader($version, Before::RouteChange)) .await .expect("timed out"); } - #[moq_clock::test] + #[kio::test] async fn late_reader_after_resume() { - moq_clock::timeout(TEST_TIMEOUT, late_reader($version, Before::Resume)) + kio::clock::timeout(TEST_TIMEOUT, late_reader($version, Before::Resume)) .await .expect("timed out"); } @@ -491,16 +491,16 @@ macro_rules! fetch_tests { mod $name { use super::*; - #[moq_clock::test] + #[kio::test] async fn fetch_right_after_leave() { - moq_clock::timeout(TEST_TIMEOUT, fetch_after_leave($version, Duration::ZERO)) + kio::clock::timeout(TEST_TIMEOUT, fetch_after_leave($version, Duration::ZERO)) .await .expect("timed out"); } - #[moq_clock::test] + #[kio::test] async fn fetch_after_leave_settles() { - moq_clock::timeout(TEST_TIMEOUT, fetch_after_leave($version, Duration::from_millis(500))) + kio::clock::timeout(TEST_TIMEOUT, fetch_after_leave($version, Duration::from_millis(500))) .await .expect("timed out"); } diff --git a/rs/moq-net/tests/integration/compress.rs b/rs/moq-net/tests/integration/compress.rs index 8188e50d4d7..b1e33fc8a80 100644 --- a/rs/moq-net/tests/integration/compress.rs +++ b/rs/moq-net/tests/integration/compress.rs @@ -119,7 +119,7 @@ const RANGED: &[&str] = &["moq-lite-07-wip", "moq-transport-18", "moq-transport- /// A subscription starting at a group delivers it whole from its first frame across every /// pair of hops, compressed or not, whether the group began before it subscribed or after. -#[moq_clock::test] +#[kio::test] async fn a_start_group_arrives_whole() { use moq_net::track::{Anchor, Subscription}; let write = |group: &mut moq_net::group::Producer, frames: std::ops::Range| { @@ -138,7 +138,7 @@ async fn a_start_group_arrives_whole() { // or fill delivers. for head in [0, 3] { let case = format!("{upstream} -> {downstream}, compress {compress}, head {head}"); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let info = match compress { true => compressed(), false => moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI), @@ -180,10 +180,10 @@ async fn a_start_group_arrives_whole() { /// Whole and chunked frames on a compressed track read back as written on every version, /// and only a peer that can signal it learns the track is compressed. -#[moq_clock::test] +#[kio::test] async fn relay_serves_every_version() { for &version in VERSIONS { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let mut fixture = connect("moq-lite-07-wip", version).await; assert_eq!( fixture.subscriber.info().compress, @@ -230,10 +230,10 @@ async fn relay_serves_every_version() { /// A compressed track's datagrams read back as written, whether the subscriber takes them /// compressed or inflated. -#[moq_clock::test] +#[kio::test] async fn datagrams_serve_every_version() { for &version in &["moq-lite-07-wip", "moq-lite-06", "moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let mut fixture = connect("moq-lite-07-wip", version).await; fixture .track @@ -261,10 +261,10 @@ fn traffic(registry: &moq_net::stats::Registry, role: moq_net::stats::Role) -> m /// A relay meters a compressed track's datagram in the form each wire carries: compressed /// on ingress and on moq-lite 07 egress, inflated to an older subscriber. Only `inflated` /// counts the bytes the relay inflated. -#[moq_clock::test] +#[kio::test] async fn datagrams_meter_the_bytes_on_the_wire() { for &version in &["moq-lite-07-wip", "moq-lite-06"] { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); let mut track = broadcast.create_track("data", compressed()).unwrap(); @@ -324,11 +324,11 @@ async fn datagrams_meter_the_bytes_on_the_wire() { } /// Negotiated IETF ingress stays compressed across a relay to IETF or lite-07 egress. -#[moq_clock::test] +#[kio::test] async fn ietf_ingress_stays_compressed_across_protocols() { for upstream in ["moq-transport-18", "moq-transport-22"] { for downstream in ["moq-lite-07-wip", "moq-transport-22"] { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let mut fixture = connect(upstream, downstream).await; assert!(fixture.subscriber.info().compress, "{upstream} -> {downstream}"); let mut group = fixture.track.append_group().unwrap(); @@ -369,10 +369,10 @@ async fn ietf_ingress_stays_compressed_across_protocols() { } /// A finished compressed track remains fetchable without subscribing to its live feed. -#[moq_clock::test] +#[kio::test] async fn ietf_fetch_keeps_the_stored_form() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); let track = broadcast.create_track("data", compressed()).unwrap(); diff --git a/rs/moq-net/tests/integration/control_stats.rs b/rs/moq-net/tests/integration/control_stats.rs index 71f9e5ea177..4ad814fdbd9 100644 --- a/rs/moq-net/tests/integration/control_stats.rs +++ b/rs/moq-net/tests/integration/control_stats.rs @@ -17,7 +17,7 @@ fn origin() -> origin::Producer { origin } -#[moq_clock::test] +#[kio::test] async fn control_classes_cross_lite_and_ietf_sessions_without_counting_payload() { for version in ["moq-lite-03", "moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let publisher = origin(); @@ -71,7 +71,7 @@ async fn control_classes_cross_lite_and_ietf_sessions_without_counting_payload() /// The SETUP a server reads before admission counts under the stats the handshake is /// admitted with, even for a session with neither origin. -#[moq_clock::test] +#[kio::test] async fn setup_counts_under_the_admitted_stats() { for version in ["moq-lite-07-wip", "moq-transport-22"] { let version: moq_net::Version = version.parse().unwrap(); @@ -95,7 +95,7 @@ async fn setup_counts_under_the_admitted_stats() { session }; let _sessions = futures::join!(client, server); - moq_clock::sleep(std::time::Duration::from_millis(100)).await; + kio::clock::sleep(std::time::Duration::from_millis(100)).await; let rows = registry.snapshot().control(); assert!( rows.iter() diff --git a/rs/moq-net/tests/integration/datagram.rs b/rs/moq-net/tests/integration/datagram.rs index 9f70d54e84e..200cf92a824 100644 --- a/rs/moq-net/tests/integration/datagram.rs +++ b/rs/moq-net/tests/integration/datagram.rs @@ -76,9 +76,9 @@ async fn connect_datagram_track() -> Fixture { /// asserts what delivery actually guarantees rather than a fixed count: whatever /// arrives is intact and in order, and the last one written arrives, since nothing /// is pushed during the drain to evict it. -#[moq_clock::test] +#[kio::test] async fn datagrams_reach_the_subscriber_in_order() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut fixture = connect_datagram_track().await; const COUNT: u64 = 32; @@ -121,10 +121,10 @@ async fn datagrams_reach_the_subscriber_in_order() { /// MoQ Transport carries a datagram as an OBJECT_DATAGRAM at object 0, so it arrives as a /// datagram with its sequence, alongside the groups on streams. -#[moq_clock::test] +#[kio::test] async fn ietf_delivers_datagrams() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TEST_TIMEOUT, ietf_delivers_datagrams_on(version)) + kio::clock::timeout(TEST_TIMEOUT, ietf_delivers_datagrams_on(version)) .await .unwrap_or_else(|_| panic!("{version}: timed out")); } @@ -184,9 +184,9 @@ async fn ietf_delivers_datagrams_on(version: &str) { } /// Explicit insert keeps the origin sequence on the lite wire, including a gap. -#[moq_clock::test] +#[kio::test] async fn inserted_sequences_survive_the_lite_wire() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut fixture = connect_datagram_track().await; fixture @@ -228,7 +228,7 @@ async fn inserted_sequences_survive_the_lite_wire() { /// moq-lite-07, and with the NOT_FOUND an earlier version has for it. A relay carries the /// answer across in the downstream version's terms. The moq-transport side (DOES_NOT_EXIST) /// is covered by the IETF publisher's own tests. -#[moq_clock::test] +#[kio::test] async fn a_fetched_datagram_is_refused_per_version() { const NOT_FETCHABLE: &str = "not fetchable"; const NOT_FOUND: &str = "not found"; @@ -266,7 +266,7 @@ async fn a_fetched_datagram_is_refused_per_version() { (&["moq-lite-07-wip"], NOT_FETCHABLE), (&["moq-lite-07-wip", "moq-lite-06"], NOT_FOUND), ] { - let refused = moq_clock::timeout(TEST_TIMEOUT, fetch_a_datagram(versions)) + let refused = kio::clock::timeout(TEST_TIMEOUT, fetch_a_datagram(versions)) .await .unwrap_or_else(|_| panic!("{versions:?}: timed out")); assert_eq!(refused, expected, "{versions:?}"); diff --git a/rs/moq-net/tests/integration/dial_split_horizon.rs b/rs/moq-net/tests/integration/dial_split_horizon.rs index 23751e1f8d4..d017fcbe397 100644 --- a/rs/moq-net/tests/integration/dial_split_horizon.rs +++ b/rs/moq-net/tests/integration/dial_split_horizon.rs @@ -95,7 +95,7 @@ fn traffic(registry: &stats::Registry, role: stats::Role) -> stats::Traffic { /// The hop the dialer attributed `path` to, once that announce has arrived. async fn learned_hop(dialer: &origin::Producer, path: &str) -> Hop { let mut announced = dialer.consume().announced(); - let event = moq_clock::timeout(SETTLE, async { + let event = kio::clock::timeout(SETTLE, async { loop { let event = announced.next().await.expect("announce cursor closed"); let announce = match event { @@ -124,13 +124,13 @@ fn hop(id: u64) -> Hop { } /// Edges that declare their own hop over the MoQ Cluster extension. -#[moq_clock::test] +#[kio::test] async fn dialed_named_session_does_not_echo_or_route_subscribe_back() { split_horizon("moq-transport-18", [hop(2), hop(3)]).await; } /// moq-lite-01 carries no hop, so neither side declares one. -#[moq_clock::test] +#[kio::test] async fn dialed_anonymous_session_does_not_echo_or_route_subscribe_back() { split_horizon("moq-lite-01", [hop(2), hop(3)]).await; } @@ -161,7 +161,7 @@ async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) // The other edge learns the namespace, attributed to a different hop, so the // two dials are not one endpoint. let mut subscriber_announced = subscriber.consume().announced(); - let subscriber_saw = moq_clock::timeout(SETTLE, subscriber_announced.next()) + let subscriber_saw = kio::clock::timeout(SETTLE, subscriber_announced.next()) .await .expect("the other edge never learned the namespace") .expect("announce cursor closed"); @@ -176,7 +176,7 @@ async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) assert_ne!(subscriber_hop, publisher_hop, "each dial gets its own hop"); assert_ne!(subscriber_hop, Hop::UNKNOWN); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let echoed = traffic(&to_publisher.registry, stats::Role::Subscriber); assert_eq!( @@ -204,12 +204,12 @@ async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) .subscribe(subscription) .await .expect("subscriber subscribes"); - moq_clock::timeout(SETTLE, crate::support::wanted(track.demand())) + kio::clock::timeout(SETTLE, crate::support::wanted(track.demand())) .await .expect("the subscribe never reached the announcer") .unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let from_announcer = traffic(&to_publisher.registry, stats::Role::Publisher); assert_eq!( diff --git a/rs/moq-net/tests/integration/drained_claim.rs b/rs/moq-net/tests/integration/drained_claim.rs index 78bd99a3455..d7d9ced1a4e 100644 --- a/rs/moq-net/tests/integration/drained_claim.rs +++ b/rs/moq-net/tests/integration/drained_claim.rs @@ -40,7 +40,7 @@ async fn link(version: Version, from: &origin::Producer, to: &origin::Producer, /// Let every task settle. Time is paused, so this returns once the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// A worker claiming `pool`, answering each request with an output whose `video` @@ -58,7 +58,7 @@ impl Worker { let claim = Rc::new(origin.requests("pool").unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (claim.clone(), outputs.clone()); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(request) = handler.requested_broadcast().await { let prepared = request.prepare(Epoch::mint()).unwrap(); let track = prepared.broadcast().create_track("video", timed()).unwrap(); @@ -114,7 +114,7 @@ async fn drained_claim(version: &str) { a_link.server.drain().send(Goaway::new()).unwrap(); // Past the linger, which is as long as the cache window, nothing reads the relay's // front for the path. - moq_clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2).await; + kio::clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2).await; assert_eq!( watch(version, &relay).await, @@ -125,16 +125,16 @@ async fn drained_claim(version: &str) { assert_eq!(b.served(), 1, "{version}"); } -#[moq_clock::test] +#[kio::test] async fn a_drained_claims_front_ends_once_unread_lite06() { - moq_clock::timeout(TEST_TIMEOUT, drained_claim("moq-lite-06")) + kio::clock::timeout(TEST_TIMEOUT, drained_claim("moq-lite-06")) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn a_drained_claims_front_ends_once_unread_lite07() { - moq_clock::timeout(TEST_TIMEOUT, drained_claim("moq-lite-07-wip")) + kio::clock::timeout(TEST_TIMEOUT, drained_claim("moq-lite-07-wip")) .await .expect("timed out"); } diff --git a/rs/moq-net/tests/integration/empty_group.rs b/rs/moq-net/tests/integration/empty_group.rs index c83e5d46557..4fd5e61799f 100644 --- a/rs/moq-net/tests/integration/empty_group.rs +++ b/rs/moq-net/tests/integration/empty_group.rs @@ -24,7 +24,7 @@ fn produce_origin(hop: u64) -> origin::Producer { producer } -#[moq_clock::test] +#[kio::test] async fn an_empty_group_arrives_empty() { for version in VERSIONS { let publisher = produce_origin(1); @@ -36,24 +36,24 @@ async fn an_empty_group_arrives_empty() { broadcast.announce(Default::default()).unwrap(); let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); - let mut sub = moq_clock::timeout(TIMEOUT, remote.track("data").unwrap().subscribe(None)) + let mut sub = kio::clock::timeout(TIMEOUT, remote.track("data").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); subscribed(&track).await; track.append_group().unwrap().finish().unwrap(); - let mut empty = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut empty = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .unwrap_or_else(|_| panic!("{version}: the empty group was dropped")) .unwrap() .expect("a group"); assert_eq!(empty.sequence, 0, "{version}"); - let frame = moq_clock::timeout(TIMEOUT, empty.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, empty.read_frame()) .await .expect("frame timeout") .unwrap(); @@ -62,7 +62,7 @@ async fn an_empty_group_arrives_empty() { let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, &b"ok"[..]).unwrap(); group.finish().unwrap(); - let mut next = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut next = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() diff --git a/rs/moq-net/tests/integration/errored_end.rs b/rs/moq-net/tests/integration/errored_end.rs index d84a34a91fe..0eaefbee347 100644 --- a/rs/moq-net/tests/integration/errored_end.rs +++ b/rs/moq-net/tests/integration/errored_end.rs @@ -26,13 +26,13 @@ async fn read(broadcast: &moq_net::broadcast::Consumer) -> (Vec, Option (Vec, Option bool { /// A side that declines MoQ Solicit invites unsolicited advertisements, so its peer /// announces unasked and that is not held against the peer, even though the peer /// implements the extension itself. -#[moq_clock::test] +#[kio::test] async fn a_side_that_declines_solicit_takes_unsolicited_announces() { for name in MOQT { let version: Version = name.parse().unwrap(); @@ -88,7 +88,7 @@ async fn a_side_that_declines_solicit_takes_unsolicited_announces() { let broadcast = publisher.create_broadcast("room/cam").unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; assert!(announced(&subscriber, "room/cam"), "{context}: never announced"); assert_open(&pair, &context); @@ -99,7 +99,7 @@ async fn a_side_that_declines_solicit_takes_unsolicited_announces() { /// A side that declines MoQ Auth leaves it un-negotiated whichever side declines: /// neither side holds a grant, and a token is kept for the requests that name it /// rather than presented on an AUTH stream. -#[moq_clock::test] +#[kio::test] async fn a_declined_auth_extension_is_not_negotiated() { for name in AUTH { let version: Version = name.parse().unwrap(); @@ -107,7 +107,7 @@ async fn a_declined_auth_extension_is_not_negotiated() { // Control: offered by both, the client's connection credential earns a grant. let pair = connect_mock(MockConnectOptions::new(version)).await; let mut grant = pair.client.auth().grant(); - moq_clock::timeout(SETTLE, async { + kio::clock::timeout(SETTLE, async { while grant.peek().is_none() { grant.changed().await.expect("grant watch ended"); } @@ -124,13 +124,13 @@ async fn a_declined_auth_extension_is_not_negotiated() { false => options.client_extensions = no_auth, } let pair = connect_mock(options).await; - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; for session in [&pair.client, &pair.server] { assert_eq!(session.auth().grant().peek(), None, "{context}"); // Only a request that names it can carry the token, so it resolves at once with // a grant that stays unknown. - let (added, answer) = moq_clock::timeout(SETTLE, session.auth().add("token")) + let (added, answer) = kio::clock::timeout(SETTLE, session.auth().add("token")) .await .unwrap_or_else(|_| panic!("{context}: add never resolved")) .unwrap_or_else(|err| panic!("{context}: {err:?}")); @@ -170,7 +170,7 @@ fn route(origin: &origin::Producer, path: &str) -> Option { /// MoQ Epoch carries the publisher's epoch, in either direction, only when both sides /// offer it. A side declining it leaves the route epochless exactly as before the /// extension, and nothing on the wire breaks the session. -#[moq_clock::test] +#[kio::test] async fn an_epoch_crosses_only_when_both_offer_it() { for name in MOQT { let version: Version = name.parse().unwrap(); @@ -204,7 +204,7 @@ async fn an_epoch_crosses_only_when_both_offer_it() { broadcast .announce(origin::Route::default().with_epoch(epoch.clone())) .unwrap(); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let route = route(&subscriber, "room/cam").unwrap_or_else(|| panic!("{context}: never announced")); let expected = declines.is_none().then_some(epoch); diff --git a/rs/moq-net/tests/integration/fetch_cancel.rs b/rs/moq-net/tests/integration/fetch_cancel.rs index 97c097a72cc..24e3d2cfb9b 100644 --- a/rs/moq-net/tests/integration/fetch_cancel.rs +++ b/rs/moq-net/tests/integration/fetch_cancel.rs @@ -50,7 +50,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage let broadcast = nodes[0].create_broadcast("room").unwrap(); let mut dynamic = broadcast.requests(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let consumer = nodes[relays as usize].consume().request("room", None).await.unwrap(); let track = consumer.track("video").unwrap(); @@ -71,7 +71,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage match stage { Stage::Unanswered => { drop(waiting); - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { while request.wanted_changed().await.is_some() {} }) .await @@ -92,7 +92,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage while demand.wanted_changed().await? {} Ok::<_, moq_net::Error>(()) }; - moq_clock::timeout(Duration::from_secs(5), unwanted) + kio::clock::timeout(Duration::from_secs(5), unwanted) .await .unwrap_or_else(|_| panic!("{ctx}: the publisher still serves the fetch")) .unwrap(); @@ -100,7 +100,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage // No hop cached the head as the whole group: a fresh fetch reads it all. group.write_frame(Timestamp::ZERO, Bytes::from_static(b"tail")).unwrap(); group.finish().unwrap(); - let mut fetched = moq_clock::timeout(Duration::from_secs(5), track.fetch_group(0, None)) + let mut fetched = kio::clock::timeout(Duration::from_secs(5), track.fetch_group(0, None)) .await .unwrap_or_else(|_| panic!("{ctx}: the refetch stalled")) .unwrap(); @@ -126,13 +126,13 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage const LATENCY: Duration = Duration::from_millis(100); _pairs.last().unwrap().client_transport.set_latency(LATENCY); group.finish().unwrap(); - moq_clock::sleep(LATENCY).await; + kio::clock::sleep(LATENCY).await; drop(fetched); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; // The publisher can no longer serve it, so only a cached copy answers. group.abort(moq_net::Error::Cancel).unwrap(); - let mut fetched = moq_clock::timeout(Duration::from_secs(5), track.fetch_group(0, None)) + let mut fetched = kio::clock::timeout(Duration::from_secs(5), track.fetch_group(0, None)) .await .unwrap_or_else(|_| panic!("{ctx}: the refetch stalled")) .unwrap_or_else(|err| panic!("{ctx}: the whole group was not cached: {err}")); @@ -153,12 +153,12 @@ async fn abandoned_fetches_reach_the_publisher(version: &str) { } } -#[moq_clock::test] +#[kio::test] async fn abandoned_fetch_reaches_the_publisher_lite05() { abandoned_fetches_reach_the_publisher("moq-lite-05").await; } -#[moq_clock::test] +#[kio::test] async fn abandoned_fetch_reaches_the_publisher_lite06() { abandoned_fetches_reach_the_publisher("moq-lite-06").await; } @@ -175,7 +175,7 @@ async fn a_refetch_within_the_linger_stays_on_the_relay(version: &str) { let broadcast = publisher.create_broadcast("room").unwrap(); let mut dynamic = broadcast.requests(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let consumer = relay.consume().request("room", None).await.unwrap(); let mut waiting = Box::pin(consumer.track("video").unwrap().fetch_group(0, None)); @@ -201,7 +201,7 @@ async fn a_refetch_within_the_linger_stays_on_the_relay(version: &str) { group.abort(moq_net::Error::Cancel).unwrap(); // The track goes unread between segments, well inside the linger. - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; let mut refetch = Box::pin(consumer.track("video").unwrap().fetch_group(0, None)); let track_request = std::pin::pin!(dynamic.requested_track()); @@ -219,17 +219,17 @@ async fn a_refetch_within_the_linger_stays_on_the_relay(version: &str) { assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"segment"); } -#[moq_clock::test] +#[kio::test] async fn a_refetch_within_the_linger_stays_on_the_relay_lite06() { a_refetch_within_the_linger_stays_on_the_relay("moq-lite-06").await; } -#[moq_clock::test] +#[kio::test] async fn a_refetch_within_the_linger_stays_on_the_relay_lite07() { a_refetch_within_the_linger_stays_on_the_relay("moq-lite-07-wip").await; } -#[moq_clock::test] +#[kio::test] async fn a_refetch_within_the_linger_stays_on_the_relay_ietf18() { a_refetch_within_the_linger_stays_on_the_relay("moq-transport-18").await; } diff --git a/rs/moq-net/tests/integration/fetch_fanout.rs b/rs/moq-net/tests/integration/fetch_fanout.rs index ff257cadfcf..e35e461eb49 100644 --- a/rs/moq-net/tests/integration/fetch_fanout.rs +++ b/rs/moq-net/tests/integration/fetch_fanout.rs @@ -14,7 +14,7 @@ fn origin(hop: u64) -> origin::Producer { origin } -#[moq_clock::test] +#[kio::test] async fn sequential_viewers_share_the_relays_fetched_groups() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let version: Version = version.parse().unwrap(); @@ -75,7 +75,7 @@ async fn sequential_viewers_share_the_relays_fetched_groups() { .count(); assert_eq!(fetches, round as usize + 1, "{version}: viewer {i}, group {sequence}"); } - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } let types = upstream.client_transport.bidi_types(); assert_eq!( diff --git a/rs/moq-net/tests/integration/fetch_from_feed.rs b/rs/moq-net/tests/integration/fetch_from_feed.rs index c3a765b9ab8..abfc3f3ab52 100644 --- a/rs/moq-net/tests/integration/fetch_from_feed.rs +++ b/rs/moq-net/tests/integration/fetch_from_feed.rs @@ -46,7 +46,7 @@ async fn relay(version: &str) -> Relay { let pair = connect_mock(options).await; let consumer = client.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -62,22 +62,22 @@ async fn relay(version: &str) -> Relay { /// The error a fetch of `sequence` fails with. async fn fetch_err(relay: &Relay, sequence: u64) -> moq_net::Error { let fetching = relay.remote.track("video").unwrap().fetch_group(sequence, None); - match moq_clock::timeout(TIMEOUT, fetching).await.expect("fetch timed out") { + match kio::clock::timeout(TIMEOUT, fetching).await.expect("fetch timed out") { Ok(_) => panic!("group {sequence} was served"), Err(err) => err, } } /// The groups a recorder fetches as the live subscription delivers them are served. -#[moq_clock::test] +#[kio::test] async fn a_fetch_is_served_from_the_live_feed() { for version in VERSIONS { let mut relay = relay(version).await; - let mut subscriber = moq_clock::timeout(TIMEOUT, relay.remote.track("video").unwrap().subscribe(None)) + let mut subscriber = kio::clock::timeout(TIMEOUT, relay.remote.track("video").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); - let first = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let first = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .expect("group timeout") .unwrap() @@ -88,17 +88,17 @@ async fn a_fetch_is_served_from_the_live_feed() { let next = first + 1; let mut fetching = relay.remote.track("video").unwrap().fetch_group(next, None); assert!( - moq_clock::timeout(Duration::from_millis(100), &mut fetching) + kio::clock::timeout(Duration::from_millis(100), &mut fetching) .await .is_err(), "{version}: answered before the group exists" ); relay.track.write_frame(None, &b"1"[..]).unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, fetching) + let mut group = kio::clock::timeout(TIMEOUT, fetching) .await .expect("fetch timed out") .unwrap_or_else(|err| panic!("{version}: {err}")); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read timed out"); assert_eq!(&frame.unwrap().expect("a frame").payload[..], b"1", "{version}"); @@ -108,7 +108,7 @@ async fn a_fetch_is_served_from_the_live_feed() { /// A fetch that reaches the relay alongside the subscription that will carry it, as a /// recorder starting on an uncached group sends them, waits for that feed. The relay /// already serves the track, with no feed, for an earlier fetch. -#[moq_clock::test] +#[kio::test] async fn a_fetch_waits_for_a_feed_opened_with_it() { for version in VERSIONS { let mut relay = relay(version).await; @@ -118,17 +118,17 @@ async fn a_fetch_waits_for_a_feed_opened_with_it() { let track = relay.remote.track("video").unwrap(); let subscribing = track.subscribe(None); let fetching = track.fetch_group(1, None); - let _subscriber = moq_clock::timeout(TIMEOUT, subscribing) + let _subscriber = kio::clock::timeout(TIMEOUT, subscribing) .await .expect("subscribe timeout") .expect("subscribe"); relay.track.write_frame(None, &b"1"[..]).unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, fetching) + let mut group = kio::clock::timeout(TIMEOUT, fetching) .await .expect("fetch timed out") .unwrap_or_else(|err| panic!("{version}: {err}")); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read timed out"); assert_eq!(&frame.unwrap().expect("a frame").payload[..], b"1", "{version}"); @@ -137,7 +137,7 @@ async fn a_fetch_waits_for_a_feed_opened_with_it() { /// A group with no feed at all, or one the feed went past, is a miss rather than a version /// error. -#[moq_clock::test] +#[kio::test] async fn an_unfed_fetch_is_a_miss() { for version in VERSIONS { let mut relay = relay(version).await; @@ -149,11 +149,11 @@ async fn an_unfed_fetch_is_a_miss() { let mut skipped = relay.track.create_group(moq_net::group::Info { sequence: 3 }).unwrap(); skipped.write_frame(None, &b"3"[..]).unwrap(); skipped.finish().unwrap(); - let mut subscriber = moq_clock::timeout(TIMEOUT, relay.remote.track("video").unwrap().subscribe(None)) + let mut subscriber = kio::clock::timeout(TIMEOUT, relay.remote.track("video").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); - let first = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let first = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .expect("group timeout") .unwrap() diff --git a/rs/moq-net/tests/integration/fetch_only.rs b/rs/moq-net/tests/integration/fetch_only.rs index 837135889d2..7f5b0f6715b 100644 --- a/rs/moq-net/tests/integration/fetch_only.rs +++ b/rs/moq-net/tests/integration/fetch_only.rs @@ -30,7 +30,7 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { async fn resolve(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Consumer { let consumer = origin.consume(); - moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves") @@ -54,7 +54,7 @@ fn publish_finished(origin: &moq_net::origin::Producer) -> (moq_net::origin::Pub let subscribed = Arc::new(AtomicBool::new(false)); let flag = subscribed.clone(); - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { while let Ok(subscription) = track.subscription_changed().await { if subscription.is_some() { flag.store(true, Ordering::SeqCst); @@ -65,13 +65,13 @@ fn publish_finished(origin: &moq_net::origin::Producer) -> (moq_net::origin::Pub } async fn fetch(broadcast: &moq_net::broadcast::Consumer, sequence: u64) -> Result>, moq_net::Error> { - let mut group = moq_clock::timeout(TIMEOUT, async { + let mut group = kio::clock::timeout(TIMEOUT, async { broadcast.track("video").unwrap().fetch_group(sequence, None).await }) .await .expect("fetch timed out")?; let mut frames = Vec::new(); - while let Some(frame) = moq_clock::timeout(TIMEOUT, group.read_frame()) + while let Some(frame) = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read timed out")? { @@ -105,11 +105,11 @@ async fn direct(version: &str) { } /// A finished track is fetched without a SUBSCRIBE, which it would refuse. -#[moq_clock::test] +#[kio::test] async fn a_fetch_learns_the_track_without_subscribing() { let mut failures = Vec::new(); for version in VERSIONS { - if moq_clock::sim::spawn(direct(version)).await.is_err() { + if kio::clock::sim::spawn(direct(version)).await.is_err() { failures.push(*version); } } @@ -151,10 +151,10 @@ async fn relayed(version: &str) { /// A subscriber arriving at a copy learned from TRACK_STATUS still gets timestamped /// frames: the copy is timed from TRACK_STATUS_OK, and the resumed SUBSCRIBE keeps it so. -#[moq_clock::test] +#[kio::test] async fn a_subscribe_after_track_status_keeps_timestamps() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); let track = broadcast.create_track("video", timed()).unwrap(); @@ -194,11 +194,11 @@ async fn a_subscribe_after_track_status_keeps_timestamps() { } /// A relay serves a downstream fetch with a fetch upstream, never a subscription. -#[moq_clock::test] +#[kio::test] async fn a_relay_fetches_without_subscribing_upstream() { let mut failures = Vec::new(); for version in VERSIONS { - if moq_clock::sim::spawn(relayed(version)).await.is_err() { + if kio::clock::sim::spawn(relayed(version)).await.is_err() { failures.push(*version); } } diff --git a/rs/moq-net/tests/integration/finished_broadcast_mock.rs b/rs/moq-net/tests/integration/finished_broadcast_mock.rs index a6116955999..4170eba1b36 100644 --- a/rs/moq-net/tests/integration/finished_broadcast_mock.rs +++ b/rs/moq-net/tests/integration/finished_broadcast_mock.rs @@ -50,12 +50,12 @@ async fn round(finish_broadcast: bool) -> (Vec>, Option) let pair: MockPair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = moq_net::track::Subscription::default().with_range(0..); let mut sub = remote .track("video") @@ -80,7 +80,7 @@ async fn round(finish_broadcast: bool) -> (Vec>, Option) } }); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); @@ -96,7 +96,7 @@ async fn round(finish_broadcast: bool) -> (Vec>, Option) } // The session and both origins stay up until the reader is done. - let result = moq_clock::timeout(TIMEOUT, reader) + let result = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); @@ -113,13 +113,13 @@ fn assert_complete((got, err): (Vec>, Option)) { } /// The bug: finishing the broadcast after its track loses the track. -#[moq_clock::test] +#[kio::test] async fn a_finished_broadcast_delivers_its_finished_track() { assert_complete(round(true).await); } /// Control: the same track with the broadcast left alive arrives whole. -#[moq_clock::test] +#[kio::test] async fn a_finished_track_is_delivered_while_its_broadcast_lives() { assert_complete(round(false).await); } diff --git a/rs/moq-net/tests/integration/finite_relay.rs b/rs/moq-net/tests/integration/finite_relay.rs index 7635202e174..fcce2290d75 100644 --- a/rs/moq-net/tests/integration/finite_relay.rs +++ b/rs/moq-net/tests/integration/finite_relay.rs @@ -76,13 +76,13 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E let downstream = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); let (mut heads, mut opened) = futures::channel::mpsc::unbounded(); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = Subscription::default().with_max_delay(MAX_DELAY).with_range(0..); let mut sub = remote .track("tail") @@ -104,7 +104,7 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E }; assert_eq!(&head.payload[..], b"head"); heads.send(group.sequence).await.unwrap(); - tails.push(moq_clock::sim::spawn(async move { + tails.push(kio::clock::sim::spawn(async move { let tail = group.read_frame().await?.expect("tail frame"); assert_eq!(&tail.payload[..], b"tail"); assert!(group.read_frame().await?.is_none(), "extra frame"); @@ -122,14 +122,14 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E (seen, end) }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); // Let the publisher answer while the track is still empty, so no Largest Object // tells the relay where its feed starts; otherwise the outcome rests on whether the // first group is written before SUBSCRIBE_OK. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; track.finish_at(moq_net::track::Position::group(GROUPS), None).unwrap(); match arrival { Arrival::HeldTails => { @@ -139,7 +139,7 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E group.write_frame(Timestamp::ZERO, &b"head"[..]).unwrap(); groups.push(group); // IETF requests the live edge, so observe each header before advancing it. - match moq_clock::timeout(TIMEOUT, opened.next()).await.expect("head timeout") { + match kio::clock::timeout(TIMEOUT, opened.next()).await.expect("head timeout") { Some(head) => assert_eq!(head, sequence, "{name}"), None => panic!("{name}: the reader stopped: {:?}", reader.await), } @@ -147,7 +147,7 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E // Simulated time advances only once every task is idle: each group has reached // the subscriber, so the relay's downstream subscription has seen the end. - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; for mut group in groups { group.write_frame(Timestamp::ZERO, &b"tail"[..]).unwrap(); group.finish().unwrap(); @@ -162,17 +162,17 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E group.finish().unwrap(); // IETF serves from the live edge, so let each group open its stream before // the next one supersedes it. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } // Once idle, the publisher has opened every stream and ended the subscription, // so the relay knows the end before any group arrives. - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; // Deliver streams newest first (IETF also carries the end on a stream of its // own) until the last group reaches the subscriber, at the declared boundary. let newest = loop { let held = upstream.server_transport.release_newest_uni(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; match opened.try_recv() { Ok(head) => break head, Err(TryRecvError::Closed) => panic!("{name}: the reader stopped: {:?}", reader.await), @@ -181,13 +181,13 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E assert!(held > 0, "{name}: no group reached the subscriber"); }; assert_eq!(newest, GROUPS - 1, "{name}"); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; upstream.server_transport.release_unis(); } } // Lite03 carries no declared end: each of the two hops waits one max-delay grace. - let outcome = moq_clock::timeout(MAX_DELAY * 2 + TIMEOUT, reader) + let outcome = kio::clock::timeout(MAX_DELAY * 2 + TIMEOUT, reader) .await .unwrap_or_else(|_| panic!("{name}: the track never ended")) .expect("reader panicked"); @@ -195,7 +195,7 @@ async fn round(name: &str, arrival: Arrival) -> (Vec, Result<(), moq_net::E outcome } -#[moq_clock::test] +#[kio::test] async fn relay_keeps_groups_in_flight_past_the_end() { for version in VERSIONS { let (seen, end) = round(version, Arrival::HeldTails).await; @@ -206,7 +206,7 @@ async fn relay_keeps_groups_in_flight_past_the_end() { /// The relay learns the end, then receives the last group's stream before the others: it /// keeps serving until the upstream tail settles instead of ending at the boundary. -#[moq_clock::test] +#[kio::test] async fn relay_waits_for_reordered_upstream_headers() { for version in VERSIONS { let (seen, end) = round(version, Arrival::NewestFirst).await; diff --git a/rs/moq-net/tests/integration/goaway.rs b/rs/moq-net/tests/integration/goaway.rs index 75936bcff60..4be7c5e2239 100644 --- a/rs/moq-net/tests/integration/goaway.rs +++ b/rs/moq-net/tests/integration/goaway.rs @@ -37,24 +37,24 @@ const GOAWAY_VERSIONS: &[&str] = &["moq-lite-04", "moq-lite-05", "moq-transport- /// A full receive window or missing FIN ACK cannot hold a drain beyond its local deadline. async fn closes_stalled_goaway(version: Version, writes: bool) { let pair = connect_mock(MockConnectOptions::new(version)).await; - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let before = pair.server_transport.blocked_writes(); if writes { pair.server_transport.hold_writes(); } else { pair.server_transport.hold_fin_acknowledgements(); } - let started = moq_clock::now(); + let started = kio::clock::now(); let timeout = Duration::from_secs(1); pair.server.drain().send(Goaway::new().with_timeout(timeout)).unwrap(); - let reason = moq_clock::timeout(timeout * 2, pair.server.closed()) + let reason = kio::clock::timeout(timeout * 2, pair.server.closed()) .await .unwrap_or_else(|_| panic!("{version}: a stalled GOAWAY held the session past its deadline")); assert!( matches!(reason, moq_net::Error::Session(moq_net::SessionError::GoawayTimeout)), "{version}: {reason}" ); - assert_eq!(moq_clock::now() - started, timeout, "{version}: drain window moved"); + assert_eq!(kio::clock::now() - started, timeout, "{version}: drain window moved"); if writes { assert!( pair.server_transport.blocked_writes() > before, @@ -63,7 +63,7 @@ async fn closes_stalled_goaway(version: Version, writes: bool) { } } -#[moq_clock::test] +#[kio::test] async fn a_stalled_lite_goaway_is_still_closed_at_the_deadline() { for name in ["moq-lite-04", "moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let version = name.parse().unwrap(); @@ -73,7 +73,7 @@ async fn a_stalled_lite_goaway_is_still_closed_at_the_deadline() { } } -#[moq_clock::test] +#[kio::test] async fn a_stalled_ietf_goaway_is_still_closed_at_the_deadline() { for version in support::every_version() .into_iter() @@ -86,10 +86,10 @@ async fn a_stalled_ietf_goaway_is_still_closed_at_the_deadline() { /// Server drains with a redirect URI; the client observes it through /// `Session::draining()`. Exercises every GOAWAY channel in the version /// matrix, in both directions. -#[moq_clock::test] +#[kio::test] async fn goaway_send_receive_all_versions() { for version in GOAWAY_VERSIONS { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = version.parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -130,9 +130,9 @@ async fn goaway_send_receive_all_versions() { /// The IETF GOAWAY carries a timeout on the wire; the receiver observes the /// sender's advertised deadline. -#[moq_clock::test] +#[kio::test] async fn goaway_wire_timeout_moq_transport() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-transport-18".parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -158,9 +158,9 @@ async fn goaway_wire_timeout_moq_transport() { } /// The client also drains the server: GOAWAY is symmetric. -#[moq_clock::test] +#[kio::test] async fn goaway_client_to_server_moq_lite_04() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-lite-04".parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -185,9 +185,9 @@ async fn goaway_client_to_server_moq_lite_04() { /// A version with no GOAWAY message (moq-lite-03 and earlier) still drains: the /// deadline is the sender's own timer, so the session closes on schedule even /// though the peer is never told why. Callers do not branch on the version. -#[moq_clock::test] +#[kio::test] async fn goaway_drains_without_a_wire_message_moq_lite_03() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-lite-03".parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -212,9 +212,9 @@ async fn goaway_drains_without_a_wire_message_moq_lite_03() { /// A moq-transport client cannot tell a server where to reconnect, so naming a /// URI is refused locally instead of getting the session closed by the peer. -#[moq_clock::test] +#[kio::test] async fn goaway_client_redirect_refused_moq_transport_18() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-transport-18".parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -245,9 +245,9 @@ async fn goaway_client_redirect_refused_moq_transport_18() { /// The draining side force-closes the session when the peer overstays the /// deadline, and the peer observes the GOAWAY_TIMEOUT close code. -#[moq_clock::test] +#[kio::test] async fn goaway_timeout_force_close_moq_transport_17() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-transport-18".parse().unwrap(); let pair = connect_mock(MockConnectOptions::new(version)).await; @@ -284,7 +284,7 @@ async fn goaway_timeout_force_close_moq_transport_17() { /// The public API's drain claim only ever sends one GOAWAY per session, so the /// handshake is hand-rolled to keep a raw transport clone for injecting /// wire-level GOAWAY control streams. -#[moq_clock::test] +#[kio::test] async fn duplicate_goaway_keeps_first_payload_moq_lite_04() { /// Open a raw lite Goaway control stream: /// `[ControlType::Goaway][message size][uri length][uri bytes]`. @@ -315,7 +315,7 @@ async fn duplicate_goaway_keeps_first_payload_moq_lite_04() { while let Ok(Some(_)) = recv.read_chunk(usize::MAX).await {} } - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let version: Version = "moq-lite-04".parse().unwrap(); let mut mock = moq_net::transport::memory::Config::default(); @@ -366,7 +366,7 @@ async fn duplicate_goaway_keeps_first_payload_moq_lite_04() { /// After a received GOAWAY, a new subscription still opens on the draining /// session, which is the only route, while an existing one keeps delivering. async fn goaway_keeps_new_subscribes(version: Version) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { // Server publishes a broadcast with one live track. let pub_origin = produce_origin(Hop::random()); let broadcast = pub_origin.create_broadcast("test").expect("create broadcast"); @@ -459,17 +459,17 @@ async fn goaway_keeps_new_subscribes(version: Version) { .expect("test timed out (likely a mock deadlock)"); } -#[moq_clock::test] +#[kio::test] async fn goaway_keeps_new_subscribes_moq_lite_04() { goaway_keeps_new_subscribes("moq-lite-04".parse().unwrap()).await; } -#[moq_clock::test] +#[kio::test] async fn goaway_keeps_new_subscribes_moq_lite_05() { goaway_keeps_new_subscribes("moq-lite-05".parse().unwrap()).await; } -#[moq_clock::test] +#[kio::test] async fn goaway_keeps_new_subscribes_moq_transport_22() { goaway_keeps_new_subscribes("moq-transport-22".parse().unwrap()).await; } @@ -481,7 +481,7 @@ async fn goaway_keeps_new_subscribes_moq_transport_22() { /// subscriber has to react to the signal itself, not to a later announce that a /// draining peer has no reason to send. async fn goaway_drains_routes(version: Version) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let pub_origin = produce_origin(Hop::random()); let broadcast = pub_origin.create_broadcast("test").expect("create broadcast"); broadcast.announce(moq_net::origin::Route::default()).expect("announce"); @@ -523,12 +523,12 @@ async fn goaway_drains_routes(version: Version) { .expect("test timed out (likely a route that never drained)"); } -#[moq_clock::test] +#[kio::test] async fn goaway_drains_routes_moq_lite_04() { goaway_drains_routes("moq-lite-04".parse().unwrap()).await; } -#[moq_clock::test] +#[kio::test] async fn goaway_drains_routes_moq_transport_18() { goaway_drains_routes("moq-transport-18".parse().unwrap()).await; } diff --git a/rs/moq-net/tests/integration/group_order.rs b/rs/moq-net/tests/integration/group_order.rs index e5c1caf4399..b9d12b744dd 100644 --- a/rs/moq-net/tests/integration/group_order.rs +++ b/rs/moq-net/tests/integration/group_order.rs @@ -44,8 +44,8 @@ async fn connect( /// Subscribe to the test track through `origin` in `order`, then read every backlog group /// in the order it arrives. -fn read_arrivals(origin: moq_net::origin::Producer, order: Order) -> moq_clock::sim::JoinHandle> { - moq_clock::sim::spawn(async move { +fn read_arrivals(origin: moq_net::origin::Producer, order: Order) -> kio::clock::sim::JoinHandle> { + kio::clock::sim::spawn(async move { let consumer = origin.consume(); let remote = consumer .follow("bcast", None) @@ -66,7 +66,7 @@ fn read_arrivals(origin: moq_net::origin::Producer, order: Order) -> moq_clock:: let mut arrivals = Vec::new(); while arrivals.len() < BACKLOG.len() { - let group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .expect("recv_group") @@ -135,15 +135,15 @@ async fn round(version: &str, relay: bool, order: Order) -> Vec { support::harness::subscribed(&track).await; // Simulated time advances only once every task is idle, so this settles the // subscription on every hop before the groups exist. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; pair.server_transport.hold_unis(); let backlog = write_backlog(&track); // Every group stream is open and ranked before any reaches the subscriber. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; pair.server_transport.release_unis_by_priority(); - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); @@ -151,7 +151,7 @@ async fn round(version: &str, relay: bool, order: Order) -> Vec { got } -#[moq_clock::test] +#[kio::test] async fn a_backlog_is_served_in_the_subscription_order() { let mut failures = Vec::new(); for version in [ @@ -181,7 +181,7 @@ async fn a_backlog_is_served_in_the_subscription_order() { /// One relay request serves an ascending and a descending subscriber: upstream asks for /// descending so the live subscriber stays fresh, and each downstream session still sends /// its own subscriber's backlog in that subscriber's order. -#[moq_clock::test] +#[kio::test] async fn merged_subscribers_keep_their_own_order() { for version in ["moq-lite-07-wip", "moq-transport-18"] { let version: Version = version.parse().unwrap(); @@ -203,7 +203,7 @@ async fn merged_subscribers_keep_their_own_order() { let ascending = read_arrivals(ascending_origin.clone(), Order::Ascending); support::harness::subscribed(&track).await; - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; assert_eq!( upstream_order(), Some(Order::Ascending), @@ -211,7 +211,7 @@ async fn merged_subscribers_keep_their_own_order() { ); let descending = read_arrivals(descending_origin.clone(), Order::Descending); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; // lite-07 moves the upstream request with a SUBSCRIBE_UPDATE. This moq-transport // subscriber never updates a request, priority included, so its first order stands. let merged = match version.is_lite() { @@ -223,12 +223,12 @@ async fn merged_subscribers_keep_their_own_order() { descending_pair.server_transport.hold_unis(); ascending_pair.server_transport.hold_unis(); let backlog = write_backlog(&track); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; descending_pair.server_transport.release_unis_by_priority(); ascending_pair.server_transport.release_unis_by_priority(); for (reader, order) in [(descending, Order::Descending), (ascending, Order::Ascending)] { - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); diff --git a/rs/moq-net/tests/integration/history_groups.rs b/rs/moq-net/tests/integration/history_groups.rs index 2ad2684e7ac..d87b817ad03 100644 --- a/rs/moq-net/tests/integration/history_groups.rs +++ b/rs/moq-net/tests/integration/history_groups.rs @@ -71,12 +71,12 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = Subscription::default().with_max_delay(FOREVER).with_range(0..); let mut sub = remote .track("history") @@ -88,14 +88,14 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz // Group 6 never ends, so read until every frame arrived or nothing more does. let mut got = Vec::new(); while got.iter().map(|(_, frames)| frames).sum::() < 5 { - let Ok(next) = moq_clock::timeout(TIMEOUT, sub.recv_group()).await else { + let Ok(next) = kio::clock::timeout(TIMEOUT, sub.recv_group()).await else { break; }; let Some(mut group) = next.expect("recv_group") else { break; }; let mut frames = 0; - while let Ok(frame) = moq_clock::timeout(TIMEOUT, group.read_frame()).await { + while let Ok(frame) = kio::clock::timeout(TIMEOUT, group.read_frame()).await { match frame.expect("read_frame") { Some(_) => frames += 1, None => break, @@ -107,13 +107,13 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz got }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); // Simulated time advances only once every task is idle, so this settles the // subscription before the groups exist. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; // The hop the publisher's group streams cross first: into the relay, when there is one. let first_hop = upstream @@ -135,11 +135,11 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz if newest_first { // Paused time advances only once every task is idle: both streams are open. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; first_hop.release_unis_reversed(); } - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); @@ -156,7 +156,7 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz got } -#[moq_clock::test] +#[kio::test] async fn a_fresh_subscriber_receives_the_finished_older_group() { let mut failures = Vec::new(); for version in VERSIONS { @@ -192,7 +192,7 @@ async fn read_history(sub: &mut moq_net::track::Subscriber) { assert_eq!(sequences, [5, 6]); } -#[moq_clock::test] +#[kio::test] async fn a_late_subscriber_receives_the_relays_cached_history() { // Older drafts canonicalize group 0 to the live edge instead of replay. let version: Version = "moq-lite-07-wip".parse().unwrap(); @@ -219,7 +219,7 @@ async fn a_late_subscriber_receives_the_relays_cached_history() { let remote = consumer.follow("bcast", None).unwrap().available().await.unwrap(); let subscription = Subscription::default().with_max_delay(FOREVER).with_range(0..); let first_subscription = subscription.clone(); - let first_reader = moq_clock::sim::spawn(async move { + let first_reader = kio::clock::sim::spawn(async move { let mut sub = remote .track("history") .unwrap() @@ -241,9 +241,9 @@ async fn a_late_subscriber_receives_the_relays_cached_history() { live.write_frame(Timestamp::now(), &b"live"[..]).unwrap(); } // Both streams open before paused time advances; 10ms stays below linger. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; upstream.server_transport.release_unis_reversed(); - let first_sub = moq_clock::timeout(TIMEOUT, first_reader) + let first_sub = kio::clock::timeout(TIMEOUT, first_reader) .await .expect("first subscriber history") .unwrap(); @@ -255,7 +255,7 @@ async fn a_late_subscriber_receives_the_relays_cached_history() { let consumer = late.consume(); let remote = consumer.follow("bcast", None).unwrap().available().await.unwrap(); let mut late_sub = remote.track("history").unwrap().subscribe(subscription).await.unwrap(); - moq_clock::timeout(TIMEOUT, read_history(&mut late_sub)) + kio::clock::timeout(TIMEOUT, read_history(&mut late_sub)) .await .unwrap_or_else(|_| panic!("{version}: late subscriber history")); drop((first_sub, late_sub, first_pair, late_pair, upstream, live)); diff --git a/rs/moq-net/tests/integration/idle_cancel_refetch.rs b/rs/moq-net/tests/integration/idle_cancel_refetch.rs index 8538fdbc286..7ca37c81c5a 100644 --- a/rs/moq-net/tests/integration/idle_cancel_refetch.rs +++ b/rs/moq-net/tests/integration/idle_cancel_refetch.rs @@ -18,7 +18,7 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { producer } -#[moq_clock::test] +#[kio::test] async fn a_group_cut_by_an_idle_cancel_is_refetched_whole() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -40,23 +40,23 @@ async fn a_group_cut_by_an_idle_cancel_is_refetched_whole() { let _pair = connect_mock(options).await; let consumer = client.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .unwrap() .unwrap(); { - let mut subscriber = moq_clock::timeout(TIMEOUT, remote.track("audio").unwrap().subscribe(None)) + let mut subscriber = kio::clock::timeout(TIMEOUT, remote.track("audio").unwrap().subscribe(None)) .await .unwrap() .unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .unwrap() .unwrap() .unwrap(); assert_eq!(group.sequence, 1); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap() .unwrap() @@ -65,7 +65,7 @@ async fn a_group_cut_by_an_idle_cancel_is_refetched_whole() { } // The relay cancels the idle upstream subscription. - moq_clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) .await .unwrap() .unwrap(); @@ -77,13 +77,13 @@ async fn a_group_cut_by_an_idle_cancel_is_refetched_whole() { let track = remote.track("audio").unwrap(); let _feed = track.subscribe(None); - let mut group = moq_clock::timeout(TIMEOUT, track.fetch_group(1, None)) + let mut group = kio::clock::timeout(TIMEOUT, track.fetch_group(1, None)) .await .unwrap() .unwrap(); let mut frames = Vec::new(); loop { - match moq_clock::timeout(TIMEOUT, group.read_frame()) + match kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("group 1 hangs") { diff --git a/rs/moq-net/tests/integration/idle_session.rs b/rs/moq-net/tests/integration/idle_session.rs index bbcc800bc8c..8f1cf854992 100644 --- a/rs/moq-net/tests/integration/idle_session.rs +++ b/rs/moq-net/tests/integration/idle_session.rs @@ -50,7 +50,7 @@ async fn viewer( let mut probe = pair.client.recv_bandwidth().expect("lite carries PROBE"); assert_eq!(probe.changed().await.unwrap(), Some(Rate::from_bps(1_000_000))); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; (pair, probe) } @@ -60,7 +60,7 @@ fn origin() -> origin::Producer { origin } -#[moq_clock::test] +#[kio::test] async fn idle_viewer_does_not_wake_the_server() { for version in VERSIONS { let origin = origin(); @@ -70,7 +70,7 @@ async fn idle_viewer_does_not_wake_the_server() { let reads = &pair.server_transport; let (start_polls, start_reads) = (polls.load(Ordering::Relaxed), reads.stats_reads()); assert!(start_polls > 0, "the requested poll counter must observe the handshake"); - moq_clock::sleep(IDLE).await; + kio::clock::sleep(IDLE).await; let polls = polls.load(Ordering::Relaxed) - start_polls; let reads = reads.stats_reads() - start_reads; @@ -84,7 +84,7 @@ async fn idle_viewer_does_not_wake_the_server() { /// The flip side: a session the server is doing work for samples as it goes, so a /// moved estimate reaches the viewer with that work, not at the next max age. -#[moq_clock::test] +#[kio::test] async fn busy_viewer_sees_the_estimate_move() { for version in VERSIONS { let origin = origin(); @@ -98,7 +98,7 @@ async fn busy_viewer_sees_the_estimate_move() { let broadcast = origin.create_broadcast("live").unwrap(); broadcast.announce(Default::default()).unwrap(); - let moved = moq_clock::timeout(Duration::from_millis(1), probe.changed()).await; + let moved = kio::clock::timeout(Duration::from_millis(1), probe.changed()).await; assert_eq!( moved.expect("reported with the work").unwrap(), Some(Rate::from_bps(2_000_000)), @@ -108,7 +108,7 @@ async fn busy_viewer_sees_the_estimate_move() { } /// A transport estimate demanded locally still costs one poll per sampling deadline. -#[moq_clock::test] +#[kio::test] async fn ietf_stats_refresh_costs_one_driver_poll() { for version in ["moq-transport-22"] { let polls = Arc::new(AtomicUsize::new(0)); @@ -117,10 +117,10 @@ async fn ietf_stats_refresh_costs_one_driver_poll() { options.server_polls = Some(polls.clone()); let pair = connect_mock(options).await; let _bandwidth = pair.server.send_bandwidth().expect("transport estimate"); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let start = polls.load(Ordering::Relaxed); let reads = pair.server_transport.stats_reads(); - moq_clock::sleep(Duration::from_secs(10)).await; + kio::clock::sleep(Duration::from_secs(10)).await; let polls = polls.load(Ordering::Relaxed) - start; let reads = pair.server_transport.stats_reads() - reads; assert_eq!(reads, 100, "{version}: one sample per 100 ms"); @@ -129,7 +129,7 @@ async fn ietf_stats_refresh_costs_one_driver_poll() { } /// The session and stats snapshots are not demand; only held consumers open PROBE. -#[moq_clock::test] +#[kio::test] async fn probe_follows_consumer_lifetime() { for version in VERSIONS { let mut options = MockConnectOptions::new(version.parse::().unwrap()); @@ -143,7 +143,7 @@ async fn probe_follows_consumer_lifetime() { .count() }; let _ = pair.client.stats(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(probe_count(), 0, "{version}: an idle session must not open PROBE"); let mut first = pair.client.recv_bandwidth().unwrap(); @@ -152,14 +152,14 @@ async fn probe_follows_consumer_lifetime() { let second = first.clone(); let resets = pair.client_transport.resets().len(); drop(first); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!( pair.client_transport.resets().len(), resets, "{version}: a clone still needs PROBE" ); drop(second); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( pair.client_transport.resets().len() > resets, "{version}: last drop resets PROBE" @@ -167,13 +167,13 @@ async fn probe_follows_consumer_lifetime() { let mut resumed = pair.client.recv_bandwidth().unwrap(); assert_eq!(resumed.peek(), None, "{version}: an unused estimate is cleared"); assert_eq!(resumed.changed().await.unwrap(), Some(Rate::from_bps(1_000_000))); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(probe_count(), 2, "{version}: demand can resume"); } } /// A stats tick reads the transport's wire counters and adds no sampler timer or session wake. -#[moq_clock::test] +#[kio::test] async fn wire_collection_never_arms_the_idle_sampler() { for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let registry = moq_net::stats::Registry::new(Default::default()); @@ -184,7 +184,7 @@ async fn wire_collection_never_arms_the_idle_sampler() { .session(moq_net::Path::from_static("room")); options.server_polls = Some(polls.clone()); let pair = connect_mock(options).await; - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let start_polls = polls.load(Ordering::Relaxed); let start_reads = pair.server_transport.stats_reads(); for tick in 1..=60 { @@ -196,7 +196,7 @@ async fn wire_collection_never_arms_the_idle_sampler() { (report.sessions[0].presence.wire_tx, report.sessions[0].presence.wire_rx), (tick, tick * 2) ); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } assert_eq!( polls.load(Ordering::Relaxed), diff --git a/rs/moq-net/tests/integration/implementation.rs b/rs/moq-net/tests/integration/implementation.rs index 47cd6b0e8d1..6b6e720b00d 100644 --- a/rs/moq-net/tests/integration/implementation.rs +++ b/rs/moq-net/tests/integration/implementation.rs @@ -34,7 +34,7 @@ async fn exchange(version: Version, client: Option<&str>, server: Option<&str>) ) } -#[moq_clock::test] +#[kio::test] async fn each_side_reads_the_others_implementation() { for (name, carried) in VERSIONS { let version: Version = name.parse().unwrap(); @@ -53,7 +53,7 @@ async fn each_side_reads_the_others_implementation() { } /// Unconfigured, each side names this crate; configured empty, it advertises nothing. -#[moq_clock::test] +#[kio::test] async fn the_default_names_the_crate_and_empty_omits_it() { for name in ["moq-lite-07-wip", "moq-transport-22"] { let version: Version = name.parse().unwrap(); @@ -64,7 +64,7 @@ async fn the_default_names_the_crate_and_empty_omits_it() { } /// A SETUP too large to encode fails the dial instead of leaving the peer waiting for it. -#[moq_clock::test] +#[kio::test] async fn an_oversized_implementation_fails_the_dial() { let version: Version = "moq-lite-06".parse().unwrap(); let mut transport = moq_net::transport::memory::Config::default(); @@ -80,7 +80,7 @@ async fn an_oversized_implementation_fails_the_dial() { /// A session that ends before the peer's SETUP resolves `None`, even while the caller still /// holds the finished driver. -#[moq_clock::test] +#[kio::test] async fn the_wait_ends_with_the_session() { let version: Version = "moq-lite-06".parse().unwrap(); let mut transport = moq_net::transport::memory::Config::default(); @@ -95,11 +95,11 @@ async fn the_wait_ends_with_the_session() { session.abort(moq_net::Error::Cancel); // The driver outlives its result, as one kept in a struct or a join handle would. - drop(moq_clock::sim::spawn(moq_clock::drive(move |now, waiter| { + drop(kio::clock::sim::spawn(kio::clock::drive(move |now, waiter| { Ok::<_, std::convert::Infallible>(driver.poll(now, waiter).unwrap_or(None)) }))); - let seen = moq_clock::timeout(std::time::Duration::from_secs(5), session.peer_implementation()) + let seen = kio::clock::timeout(std::time::Duration::from_secs(5), session.peer_implementation()) .await .expect("the wait ends with the session"); assert_eq!(seen, None); diff --git a/rs/moq-net/tests/integration/late_lower_group.rs b/rs/moq-net/tests/integration/late_lower_group.rs index 8c5ea8aff13..d895c1e8377 100644 --- a/rs/moq-net/tests/integration/late_lower_group.rs +++ b/rs/moq-net/tests/integration/late_lower_group.rs @@ -56,7 +56,7 @@ fn write_group(track: &moq_net::track::Producer, sequence: u64) { async fn read_all(sub: &mut moq_net::track::Subscriber) -> Vec<(u64, usize)> { let mut got = Vec::new(); loop { - let next = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let next = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv_group timed out"); let Some(mut group) = next.expect("recv_group") else { @@ -64,7 +64,7 @@ async fn read_all(sub: &mut moq_net::track::Subscriber) -> Vec<(u64, usize)> { }; let mut frames = 0; loop { - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timed out") .expect("read_frame"); @@ -114,7 +114,7 @@ async fn session(version: &str, relay: bool, start: Option) -> Vec<(u64, us let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -122,7 +122,7 @@ async fn session(version: &str, relay: bool, start: Option) -> Vec<(u64, us let subscription = Subscription::default() .with_max_delay(BUDGET) .with_ranges([floored(start)]); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let mut sub = remote .track("late") .unwrap() @@ -132,19 +132,19 @@ async fn session(version: &str, relay: bool, start: Option) -> Vec<(u64, us read_all(&mut sub).await }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); // Idle time lets the subscription settle, and again lets SUBSCRIBE_START land, // before the lower group is created. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 1); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 0); track.finish().unwrap(); - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); @@ -167,13 +167,13 @@ async fn in_process(start: Option) -> Vec<(u64, usize)> { .with_max_delay(BUDGET) .with_ranges([floored(start)]); let mut sub = track.subscribe(subscription); - let reader = moq_clock::sim::spawn(async move { read_all(&mut sub).await }); - moq_clock::sleep(Duration::from_millis(10)).await; + let reader = kio::clock::sim::spawn(async move { read_all(&mut sub).await }); + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 1); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 0); track.finish().unwrap(); - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); @@ -181,7 +181,7 @@ async fn in_process(start: Option) -> Vec<(u64, usize)> { got } -#[moq_clock::test] +#[kio::test] async fn an_explicit_floor_receives_a_group_created_below_the_first_served_group() { let want = vec![(1, 4), (0, 4)]; let mut failures = Vec::new(); @@ -231,7 +231,7 @@ async fn merged(version: &str) -> (Vec<(u64, usize)>, Vec<(u64, usize)>) { let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -240,22 +240,22 @@ async fn merged(version: &str) -> (Vec<(u64, usize)>, Vec<(u64, usize)>) { let track = remote.track("late").unwrap(); async move { let subscription = Subscription::default().with_max_delay(BUDGET).with_ranges([range]); - moq_clock::timeout(TIMEOUT, track.subscribe(subscription)) + kio::clock::timeout(TIMEOUT, track.subscribe(subscription)) .await .expect("subscribe timeout") .expect("subscribe") } }; let mut live = subscribe(Range::live()).await; - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 1); // The live reader is on group 1 before the other joins. - let first = moq_clock::timeout(TIMEOUT, live.recv_group()) + let first = kio::clock::timeout(TIMEOUT, live.recv_group()) .await .expect("recv_group timed out") .expect("recv_group") @@ -264,7 +264,7 @@ async fn merged(version: &str) -> (Vec<(u64, usize)>, Vec<(u64, usize)>) { let mut oldest = subscribe(floored(Some(0))).await; // Idle time lets the merged demand reach the publisher before the lower group exists. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 0); track.finish().unwrap(); @@ -280,7 +280,7 @@ async fn merged(version: &str) -> (Vec<(u64, usize)>, Vec<(u64, usize)>) { /// A wire with one span cannot carry both starts, and lite-05 reads an absent start as /// the latest group, so the relay must spell group 0 for a fresh group 0 to reach the /// reader that asked for it. The live reader joined above it and never sees it. -#[moq_clock::test] +#[kio::test] async fn a_merged_subscription_keeps_an_absolute_floor() { let mut failures = Vec::new(); for version in LITE { @@ -295,7 +295,7 @@ async fn a_merged_subscription_keeps_an_absolute_floor() { /// Pre-06, an omitted floor joins at the first served group. Group 0, created after /// group 1 was served, is below that join. Lite-06 cannot spell this separately from /// a floor of group 0; that case is the explicit-floor test. -#[moq_clock::test] +#[kio::test] async fn an_unfloored_lite05_join_drops_a_group_created_below_the_first_served_group() { let want = vec![(1, 4)]; let mut failures = Vec::new(); diff --git a/rs/moq-net/tests/integration/lazy_discovery.rs b/rs/moq-net/tests/integration/lazy_discovery.rs index 4abc7f3bfb7..811f89b2f31 100644 --- a/rs/moq-net/tests/integration/lazy_discovery.rs +++ b/rs/moq-net/tests/integration/lazy_discovery.rs @@ -58,7 +58,7 @@ impl Lazy { options.client_subscribe = Some(subscriber.clone()); options.client_discovers_all = false; let pair = connect_mock(options).await; - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; Self { subscriber, pair, @@ -104,7 +104,7 @@ impl Lazy { async fn synced(announced: &mut announce::Consumer) -> Vec { let mut seen = Vec::new(); while !announced.poll_synced(&moq_net::kio::Waiter::noop()).is_ready() { - let event = moq_clock::timeout(SETTLE, announced.next()) + let event = kio::clock::timeout(SETTLE, announced.next()) .await .expect("synced in time") .expect("the stream stays open"); @@ -121,7 +121,7 @@ async fn synced(announced: &mut announce::Consumer) -> Vec { } /// Nothing watched, nothing asked: the peer's broadcasts stay undiscovered. -#[moq_clock::test] +#[kio::test] async fn asks_nothing_until_watched() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -131,7 +131,7 @@ async fn asks_nothing_until_watched() { } /// A watch asks about its own prefix and nothing else. -#[moq_clock::test] +#[kio::test] async fn asks_only_about_the_watched_prefix() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -144,7 +144,7 @@ async fn asks_only_about_the_watched_prefix() { } /// A watch made before the session exists is asked about once it connects. -#[moq_clock::test] +#[kio::test] async fn a_new_session_asks_about_existing_watches() { let subscriber = produce_origin(2); let mut watch = subscriber @@ -159,7 +159,7 @@ async fn a_new_session_asks_about_existing_watches() { } /// The request outlives its last watcher by the linger, then closes and retracts. -#[moq_clock::test] +#[kio::test] async fn lingers_after_the_last_watcher() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -167,23 +167,23 @@ async fn lingers_after_the_last_watcher() { synced(&mut watch).await; drop(watch); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(lazy.routes("a/x").await, "{version}: still lingering"); // Watched again within the linger: the same request carries on. let again = lazy.watch("a"); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(lazy.routes("a/x").await, "{version}: rewatched"); assert_eq!(lazy.requests(), 1, "{version}"); drop(again); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("a/x").await, "{version}: closed"); } } /// A narrower watch rides an open broader request, which stays open while it does. -#[moq_clock::test] +#[kio::test] async fn a_narrower_watch_rides_the_broader_request() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -194,7 +194,7 @@ async fn a_narrower_watch_rides_the_broader_request() { assert_eq!(lazy.requests(), 1, "{version}"); drop(root); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert_eq!(lazy.requests(), 1, "{version}: nothing reopened"); assert!(lazy.routes("a/x").await, "{version}"); assert!(narrower.try_next().is_none(), "{version}: nothing retracted"); @@ -202,7 +202,7 @@ async fn a_narrower_watch_rides_the_broader_request() { } /// A narrower request open before a broader one stays until the broader one goes. -#[moq_clock::test] +#[kio::test] async fn a_broader_request_holds_the_narrower_open() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -213,22 +213,22 @@ async fn a_broader_request_holds_the_narrower_open() { assert_eq!(lazy.requests(), 2, "{version}"); drop(narrower); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(root.try_next().is_none(), "{version}: nothing retracted"); // The broader request lingers out, then the narrower one it held does. drop(root); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("b/y").await, "{version}"); assert!(lazy.routes("a/x").await, "{version}"); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("a/x").await, "{version}"); } } /// A narrower request still lingering when a broader one opens is held like one still /// watched, rather than lingering out on its own timer. -#[moq_clock::test] +#[kio::test] async fn a_broader_request_holds_a_lingering_narrower_open() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -236,28 +236,28 @@ async fn a_broader_request_holds_a_lingering_narrower_open() { synced(&mut narrower).await; drop(narrower); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let mut root = lazy.watch(""); assert_eq!(synced(&mut root).await, ["a/x", "b/y"], "{version}"); assert_eq!(lazy.requests(), 2, "{version}"); // Past the narrower request's own linger: it is held, not closed. - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(root.try_next().is_none(), "{version}: nothing retracted"); // The broader request lingers out, then the narrower one it held does. drop(root); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("b/y").await, "{version}"); assert!(lazy.routes("a/x").await, "{version}"); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("a/x").await, "{version}"); } } /// A broadcast resolved through a discovered route keeps it discovered after the /// listing that found it closes. -#[moq_clock::test] +#[kio::test] async fn a_resolved_broadcast_keeps_its_route() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -266,7 +266,7 @@ async fn a_resolved_broadcast_keeps_its_route() { let broadcast = lazy.subscriber.consume().request("a/x", None).await.unwrap(); drop(watch); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(lazy.routes("a/x").await, "{version}"); assert!(!lazy.routes("b/y").await, "{version}"); @@ -275,17 +275,17 @@ async fn a_resolved_broadcast_keeps_its_route() { } /// Waiting on a path asks about it. -#[moq_clock::test] +#[kio::test] async fn waiting_on_a_path_asks_about_it() { for version in VERSIONS { let lazy = Lazy::new(version).await; let consumer = lazy.subscriber.consume(); - moq_clock::timeout(SETTLE, consumer.follow("a/x", None).unwrap().available()) + kio::clock::timeout(SETTLE, consumer.follow("a/x", None).unwrap().available()) .await .expect("routed in time") .unwrap(); let mut followed = consumer.follow("b/y", None).unwrap(); - moq_clock::timeout(SETTLE, followed.available()) + kio::clock::timeout(SETTLE, followed.available()) .await .expect("announced in time") .unwrap(); @@ -295,7 +295,7 @@ async fn waiting_on_a_path_asks_about_it() { /// A relay's link asks for everything, watched or not, so discovery never narrows /// what a relay learns. -#[moq_clock::test] +#[kio::test] async fn a_relay_link_asks_for_everything() { for version in VERSIONS { for upstream in [false, true] { @@ -315,7 +315,7 @@ async fn a_relay_link_asks_for_everything() { } /// A server asks a client for everything it may, so a relay ingests what clients publish. -#[moq_clock::test] +#[kio::test] async fn a_server_asks_for_everything() { for version in VERSIONS { let publisher = produce_origin(1); @@ -326,14 +326,14 @@ async fn a_server_asks_for_everything() { options.client_publish = Some(publisher.consume()); options.server_subscribe = Some(relay.clone()); let _pair = connect_mock(options).await; - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; relay.consume().request("a/x", None).await.unwrap(); } } /// Serving the peer's own request is no local reader: a client publishing and /// consuming through one origin still asks about only what its readers watch. -#[moq_clock::test] +#[kio::test] async fn serving_the_peer_asks_nothing() { for version in VERSIONS { let local = produce_origin(2); @@ -348,7 +348,7 @@ async fn serving_the_peer_asks_nothing() { options.server_publish = Some(remote.consume()); options.server_subscribe = Some(remote.clone()); let pair = connect_mock(options).await; - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let requests = pair .client_transport @@ -370,7 +370,7 @@ async fn serving_the_peer_asks_nothing() { } /// Resolving a path owns the discovery that makes the peer's announcement visible. -#[moq_clock::test] +#[kio::test] async fn requesting_an_unwatched_path_discovers_its_instance() { for version in VERSIONS { let lazy = Lazy::new(version).await; @@ -387,23 +387,23 @@ async fn requesting_an_unwatched_path_discovers_its_instance() { } /// Absence is answered by the peer's sync boundary, without a timer in resolution. -#[moq_clock::test] +#[kio::test] async fn an_unwatched_missing_path_is_unroutable_after_sync() { for version in VERSIONS { let lazy = Lazy::new(version).await; - let result = moq_clock::timeout(SETTLE, lazy.subscriber.consume().request("missing", None)) + let result = kio::clock::timeout(SETTLE, lazy.subscriber.consume().request("missing", None)) .await .expect("the peer synced"); assert!(matches!(result, Err(Error::Unroutable)), "{version}"); assert_eq!(lazy.requests(), 1, "{version}"); let broadcast = lazy.subscriber.consume().request("a/x", None).await.unwrap(); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!( lazy.routes("a/x").await, "{version}: request ownership keeps discovery alive" ); drop(broadcast); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!( !lazy.routes("a/x").await, "{version}: dropping the last reader releases discovery" @@ -417,7 +417,7 @@ const IETF: &[&str] = &["moq-transport-18", "moq-transport-22"]; /// Apply what `announced` reports once everything in flight has arrived to `held`, and /// say whether any of it ended a prefix. async fn settled(announced: &mut announce::Consumer, held: &mut Vec) -> bool { - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; let mut ended = false; while let Some(event) = announced.try_next() { match event { @@ -437,7 +437,7 @@ async fn settled(announced: &mut announce::Consumer, held: &mut Vec) -> } /// Nothing watched, nothing asked: the peer's broadcasts stay undiscovered. -#[moq_clock::test] +#[kio::test] async fn ietf_asks_nothing_until_watched() { for version in IETF { let lazy = Lazy::new(version).await; @@ -446,7 +446,7 @@ async fn ietf_asks_nothing_until_watched() { } /// A watch asks about its own prefix and nothing else. -#[moq_clock::test] +#[kio::test] async fn ietf_asks_only_about_the_watched_prefix() { for version in IETF { let lazy = Lazy::new(version).await; @@ -461,7 +461,7 @@ async fn ietf_asks_only_about_the_watched_prefix() { /// The request outlives its last watcher by the linger, then ends, and what it reported /// goes with it. -#[moq_clock::test] +#[kio::test] async fn ietf_lingers_after_the_last_watcher() { for version in IETF { let lazy = Lazy::new(version).await; @@ -469,22 +469,22 @@ async fn ietf_lingers_after_the_last_watcher() { settled(&mut watch, &mut Vec::new()).await; drop(watch); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(lazy.routes("a/x").await, "{version}: still lingering"); let again = lazy.watch("a"); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(lazy.routes("a/x").await, "{version}: rewatched"); drop(again); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(!lazy.routes("a/x").await, "{version}: ended"); } } /// A broader watch after a narrower one discovers everything, and retracts nothing the /// narrower one holds. -#[moq_clock::test] +#[kio::test] async fn ietf_a_broader_watch_retracts_nothing() { for version in IETF { let lazy = Lazy::new(version).await; @@ -503,7 +503,7 @@ async fn ietf_a_broader_watch_retracts_nothing() { ); drop(root); - moq_clock::sleep(LINGERED).await; + kio::clock::sleep(LINGERED).await; assert!(lazy.routes("a/x").await, "{version}: the narrower watch still holds it"); assert!( !settled(&mut narrower, &mut held).await, @@ -511,19 +511,19 @@ async fn ietf_a_broader_watch_retracts_nothing() { ); drop(narrower); - moq_clock::sleep(LINGERED * 2).await; + kio::clock::sleep(LINGERED * 2).await; assert!(!lazy.routes("a/x").await, "{version}"); assert!(!lazy.routes("b/y").await, "{version}"); } } /// Waiting on a path asks about it. -#[moq_clock::test] +#[kio::test] async fn ietf_waiting_on_a_path_asks_about_it() { for version in IETF { let lazy = Lazy::new(version).await; let consumer = lazy.subscriber.consume(); - moq_clock::timeout(SETTLE, consumer.follow("a/x", None).unwrap().available()) + kio::clock::timeout(SETTLE, consumer.follow("a/x", None).unwrap().available()) .await .expect("routed in time") .unwrap(); @@ -532,7 +532,7 @@ async fn ietf_waiting_on_a_path_asks_about_it() { } /// A relay's link still asks for everything it may. -#[moq_clock::test] +#[kio::test] async fn ietf_a_relay_link_asks_for_everything() { for version in IETF { let relay = produce_origin(2); diff --git a/rs/moq-net/tests/integration/mesh_withdraw.rs b/rs/moq-net/tests/integration/mesh_withdraw.rs index c9022b9bd81..cde4c667dd6 100644 --- a/rs/moq-net/tests/integration/mesh_withdraw.rs +++ b/rs/moq-net/tests/integration/mesh_withdraw.rs @@ -22,7 +22,7 @@ fn produce_origin(hop: u64) -> origin::Producer { /// An origin holding route updates for `hold`. Its cache never expires idle /// groups: nothing here carries media, and the expiry sweep would keep a timer -/// armed forever, so [`moq_clock::sim::idle`] could never see the mesh settle. +/// armed forever, so [`kio::clock::sim::idle`] could never see the mesh settle. fn produce(hop: u64, hold: Duration) -> origin::Producer { let mut config = origin::Config::new(Hop::new(hop).unwrap()); config.pool = cache::Pool::unbounded(); @@ -42,7 +42,7 @@ enum Kind { End, } -/// Every update per prefix the watcher has seen. Await [`moq_clock::sim::idle`] +/// Every update per prefix the watcher has seen. Await [`kio::clock::sim::idle`] /// first, so every link, hold and quarantine in the mesh has settled. fn drain(watched: &mut mpsc::UnboundedReceiver<(String, Kind)>) -> HashMap> { let mut updates = HashMap::>::new(); @@ -57,7 +57,7 @@ fn drain(watched: &mut mpsc::UnboundedReceiver<(String, Kind)>) -> HashMap mpsc::UnboundedReceiver<(String, Kind)> { let (tx, rx) = mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { while let Some(event) = announced.next().await { let (kind, announce) = match event { announce::Event::Start(announce) => (Kind::Start, announce), @@ -110,7 +110,7 @@ impl Mesh { broadcast }) .collect(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let updates = drain(&mut self.watched); assert_eq!(updates.len(), count); for (prefix, kinds) in updates { @@ -133,12 +133,12 @@ fn ring_with_chords(n: usize) -> Vec<(usize, usize)> { /// Every relay neighbors the publisher's, so each hears the withdrawal first-hand /// and drops every path derived from it at once. Lite04 names the peer only in /// the chain, later versions in the announce handshake too. -#[moq_clock::test] +#[kio::test] async fn full_mesh_withdraw_retracts_once_lite04() { full_mesh_withdraw_retracts_once("moq-lite-04").await; } -#[moq_clock::test] +#[kio::test] async fn full_mesh_withdraw_retracts_once_lite06() { full_mesh_withdraw_retracts_once("moq-lite-06").await; } @@ -147,7 +147,7 @@ async fn full_mesh_withdraw_retracts_once(version: &str) { let mut mesh = Mesh::new(version, 8, &full_mesh(8)).await; let broadcasts = mesh.publish(100, 0).await; drop(broadcasts); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let updates = drain(&mut mesh.watched); assert_eq!(updates.len(), 100); for (prefix, kinds) in updates { @@ -161,12 +161,12 @@ async fn full_mesh_withdraw_retracts_once(version: &str) { /// why, so it can still pass through a stale path or two. Every broadcast must still /// end retracted, and republishing from other relays must reach the watcher again: /// no withdrawal outlives the peer announcing the path again. -#[moq_clock::test] +#[kio::test] async fn partial_mesh_withdraw_then_republish() { let mut mesh = Mesh::new("moq-lite-06", 12, &ring_with_chords(12)).await; let broadcasts = mesh.publish(100, 0).await; drop(broadcasts); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let updates = drain(&mut mesh.watched); assert_eq!(updates.len(), 100); for (prefix, kinds) in updates { @@ -215,7 +215,7 @@ const PRODUCTION_LATENCY_MS: &[u64] = &[ /// announcement. Holding route updates (`origin::Config::update_hold`) lets the /// withdrawal remove those paths first; with link latency and no hold, each /// withdrawal here costs tens of thousands of announcements. -#[moq_clock::test] +#[kio::test] async fn partial_mesh_withdraw_retracts_once() { let version: Version = "moq-lite-06".parse().unwrap(); let nodes: Vec<_> = (1..=34).map(produce_origin).collect(); @@ -228,7 +228,7 @@ async fn partial_mesh_withdraw_retracts_once() { for publisher in [5, 13, 22, 26, 32] { let broadcast = nodes[publisher].create_broadcast(format!("room/{publisher}")).unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; for (relay, watched) in watched.iter_mut().enumerate() { let updates = drain(watched); assert!( @@ -238,7 +238,7 @@ async fn partial_mesh_withdraw_retracts_once() { } drop(broadcast); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let mut hunted = Vec::new(); for (relay, watched) in watched.iter_mut().enumerate() { let updates = drain(watched); @@ -270,7 +270,7 @@ const STALE_PATHS: &[Link] = &[ /// again. Its neighbors, two or more hops from the publisher's relay, still hunt /// through stale paths; one that falls back to a path not through this relay /// offers it as a new route after the relay forgot the withdrawal. -#[moq_clock::test] +#[kio::test] async fn retracted_relay_ignores_a_stale_path() { let version: Version = "moq-lite-06".parse().unwrap(); let nodes: Vec<_> = (1..=8).map(produce_origin).collect(); @@ -282,13 +282,13 @@ async fn retracted_relay_ignores_a_stale_path() { let broadcast = nodes[7].create_broadcast("room/7").unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; for watched in watched.iter_mut() { drain(watched); } drop(broadcast); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let mut revived = Vec::new(); for (relay, watched) in watched.iter_mut().enumerate() { let kinds = drain(watched).remove("room/7").unwrap(); @@ -354,7 +354,7 @@ impl Cluster { relays: relays.iter().map(|relay| watch(relay.consume().announced())).collect(), }; // Let every session's announce interest land before anything is published. - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; assert!(drain(&mut cluster.client).is_empty()); cluster } @@ -364,7 +364,7 @@ impl Cluster { async fn publish(&mut self, path: &str) -> (moq_net::origin::Publication, Vec) { let broadcast = self.publisher.create_broadcast(path).unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let client = drain(&mut self.client).remove(path).unwrap(); assert_ne!(client.last(), Some(&Kind::End), "client: {client:?}"); for (relay, watched) in self.relays.iter_mut().enumerate() { @@ -377,7 +377,7 @@ impl Cluster { /// Close `broadcast` cleanly: what the watching client, then each relay, saw. async fn close(&mut self, path: &str, broadcast: moq_net::origin::Publication) -> (Vec, Vec>) { drop(broadcast); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let client = drain(&mut self.client).remove(path).unwrap(); let mut relays = Vec::new(); for watched in self.relays.iter_mut() { @@ -392,12 +392,12 @@ impl Cluster { /// release before the retraction quarantine (#5376), this client saw it /// retracted, announced, and retracted again. Relay 0 still restarts onto a /// stale path after the hold; see [`residual_slow_ring_reannounces`]. -#[moq_clock::test] +#[kio::test] async fn cross_node_close_retracts_once_lite06() { cross_node_close_retracts_once("moq-lite-06").await; } -#[moq_clock::test] +#[kio::test] async fn cross_node_close_retracts_once_lite07() { cross_node_close_retracts_once("moq-lite-07-wip").await; } @@ -426,7 +426,7 @@ async fn cross_node_close_retracts_once(version: &str) { /// The positive control for [`cross_node_close_retracts_once`]: without the /// update hold and the quarantine, the client sees the broadcast come back /// before it ends. -#[moq_clock::test] +#[kio::test] async fn cross_node_close_without_hold_reannounces() { let mut cluster = Cluster::new( "moq-lite-06", @@ -454,7 +454,7 @@ async fn cross_node_close_without_hold_reannounces() { /// from relay 2 at 84 ms, but relay 5's equal-cost copy, the long way round, /// stays live until 446 ms. That outlasts the hold, so relay 3 restarts onto /// the stale copy and its client sees the broadcast come back. -#[moq_clock::test] +#[kio::test] async fn residual_slow_ring_reannounces() { #[rustfmt::skip] const EDGES: &[Link] = &[ @@ -473,7 +473,7 @@ async fn residual_slow_ring_reannounces() { /// Nine relays, reduced from a seeded random mesh with [`random_mesh`]'s /// links. Relays 2 and 8 retract the broadcast and then announce it again: a /// revival the quarantine misses. -#[moq_clock::test] +#[kio::test] async fn residual_mesh_revives() { #[rustfmt::skip] const EDGES: &[Link] = &[ @@ -561,14 +561,14 @@ fn random_mesh(seed: u64) -> (Vec, usize) { /// onto a stale path, or by reviving it after retracting), how many of those /// revive, and how many updates they send beyond the one retraction. Pinned at /// today's counts; Routes and announces brings all three to zero. -#[moq_clock::test] +#[kio::test] async fn residual_random_meshes() { assert_eq!(withdrawal_counts(false).await, (179, 3, 192)); } /// The same topologies and terminal states with room for the diameter and two /// extra hops, including the publishing client outside the relay graph. -#[moq_clock::test] +#[kio::test] async fn capped_random_meshes_hunt_less() { let capped = withdrawal_counts(true).await; assert_eq!(capped, (151, 1, 154)); @@ -625,7 +625,7 @@ async fn withdrawal_counts(capped: bool) -> (usize, usize, usize) { /// A permissive source sends an over-limit path to prove ingress refusal; an /// accepted boundary path then proves egress counts the relay's own stamp. -#[moq_clock::test] +#[kio::test] async fn hop_limit_bounds_receive_and_send() { for name in [ "moq-lite-03", @@ -648,7 +648,7 @@ async fn hop_limit_bounds_receive_and_send() { let _downstream = peer(version, &relay, &sink).await; let mut received = watch(relay.consume().announced()); let mut sent = watch(sink.consume().announced()); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let route = |count: u64| { origin::Route::default().with_hops( moq_net::Hops::try_from((100..100 + count).map(|id| Hop::new(id).unwrap()).collect::>()) @@ -658,7 +658,7 @@ async fn hop_limit_bounds_receive_and_send() { let _long = source.publish("long", route(2)).unwrap(); let _boundary = source.publish("boundary", route(1)).unwrap(); let short = source.publish("short", route(0)).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let received = drain(&mut received); assert!(!received.contains_key("long"), "{name}: accepted over-limit path"); assert!(received.contains_key("boundary"), "{name}: refused boundary path"); @@ -670,19 +670,19 @@ async fn hop_limit_bounds_receive_and_send() { if matches!(name, "moq-lite-03" | "moq-lite-04") { // These wires have no route metadata update: withdraw, then replace it. drop(short); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; assert_eq!( drain(&mut sent).get("short").and_then(|kinds| kinds.last()), Some(&Kind::End), "{name}" ); let _replacement = source.publish("short", route(1)).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; assert!(drain(&mut sent).is_empty(), "{name}: forwarded over-limit replacement"); continue; } short.announce(route(1)).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let ended = drain(&mut sent); assert_eq!( ended.get("short").and_then(|kinds| kinds.last()), @@ -695,7 +695,7 @@ async fn hop_limit_bounds_receive_and_send() { /// A cheaper route at the cap wins locally but cannot be forwarded, so the relay /// advertises the pricier in-cap route instead of withdrawing the prefix, and /// withdraws only once no in-cap route is left. -#[moq_clock::test] +#[kio::test] async fn hop_limit_falls_back_to_a_forwardable_route() { // Only wires carrying a route cost can rank a longer route first. for name in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { @@ -712,7 +712,7 @@ async fn hop_limit_falls_back_to_a_forwardable_route() { let _far = peer(version, &far, &relay).await; let _downstream = peer(version, &relay, &sink).await; let mut sent = watch(sink.consume().announced()); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let route = |first: u64, count: u64, cost: u64| { origin::Route::default() @@ -730,7 +730,7 @@ async fn hop_limit_falls_back_to_a_forwardable_route() { let _cheap = far.publish("room", route(100, 2, 1)).unwrap(); // Two hops at the relay, so it has room for the relay's own. let pricey = near.publish("room", route(200, 1, 50)).unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let started = drain(&mut sent); assert_eq!( started.get("room").and_then(|kinds| kinds.last()), @@ -739,7 +739,7 @@ async fn hop_limit_falls_back_to_a_forwardable_route() { ); drop(pricey); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let ended = drain(&mut sent); assert_eq!( ended.get("room").and_then(|kinds| kinds.last()), diff --git a/rs/moq-net/tests/integration/multi_cdn.rs b/rs/moq-net/tests/integration/multi_cdn.rs index 318f36be969..005e99dbd5c 100644 --- a/rs/moq-net/tests/integration/multi_cdn.rs +++ b/rs/moq-net/tests/integration/multi_cdn.rs @@ -39,7 +39,7 @@ fn produce_origin(hop: u64) -> origin::Producer { /// Let every task settle. Time is paused, so this returns once the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// `P` pushes everything it publishes to `cdn`. @@ -84,7 +84,7 @@ type Delivery = (u64, moq_net::Result<(Option, Vec)>); /// Read every group in full, reporting each frame as it arrives. fn read(mut sub: track::Subscriber) -> mpsc::UnboundedReceiver { let (tx, rx) = mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { loop { let mut group = match sub.recv_group().await { Ok(Some(group)) => group, @@ -118,7 +118,7 @@ fn read(mut sub: track::Subscriber) -> mpsc::UnboundedReceiver { /// The next frame the reader reports, failing on an error or a hang. async fn next(rx: &mut mpsc::UnboundedReceiver) -> (u64, Option, Vec) { - let (group, frame) = moq_clock::timeout(Duration::from_secs(10), rx.next()) + let (group, frame) = kio::clock::timeout(Duration::from_secs(10), rx.next()) .await .expect("reader hung") .expect("reader ended"); @@ -272,7 +272,7 @@ fn assert_continuous(seen: &[(u64, Vec, Option)], groups: u64) { /// Two CDNs under one epoch, `B` over `secondary`: `S` reads through `A` although `B` is /// cheaper, resumes on `B` when `A` goes, and moves back once `A` returns, every frame once. async fn fails_over_and_back(secondary: &str) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut topology = Topology::new(secondary.parse().unwrap()).await; let mut announced = topology.subscriber.consume().announced(); let start = announced.next().await.expect("announced"); @@ -309,7 +309,7 @@ async fn fails_over_and_back(secondary: &str) { .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn preferred_cdn_fails_over_and_back() { fails_over_and_back("moq-lite-07-wip").await; } @@ -319,7 +319,7 @@ async fn preferred_cdn_fails_over_and_back() { /// it crossed, and one epoch means identical content: `S` refuses the copy, so the track /// ends with no frame of `B`'s. async fn refused_across_protocols(secondary: &str) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let mut topology = Topology::new(secondary.parse().unwrap()).await; let mut announced = topology.subscriber.consume().announced(); let start = announced.next().await.expect("announced"); @@ -348,13 +348,13 @@ async fn refused_across_protocols(secondary: &str) { .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn transport_secondary_is_refused() { refused_across_protocols("moq-transport-22").await; } /// The same over the first draft that can carry the epoch. -#[moq_clock::test] +#[kio::test] async fn transport_17_secondary_is_refused() { refused_across_protocols("moq-transport-18").await; } diff --git a/rs/moq-net/tests/integration/partial_group.rs b/rs/moq-net/tests/integration/partial_group.rs index 585c2808897..8cf08502427 100644 --- a/rs/moq-net/tests/integration/partial_group.rs +++ b/rs/moq-net/tests/integration/partial_group.rs @@ -40,11 +40,11 @@ async fn round(version: &str) -> Option, moq_net::Error>> { broadcast.announce(Default::default()).unwrap(); let consumer = downstream.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); - let mut live = moq_clock::timeout( + let mut live = kio::clock::timeout( TIMEOUT, remote .track("data") @@ -58,7 +58,7 @@ async fn round(version: &str) -> Option, moq_net::Error>> { let mut stalled = track.append_group().unwrap(); stalled.write_frame(Timestamp::ZERO, &b"head"[..]).unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, live.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, live.recv_group()) .await .expect("group timeout") .unwrap() @@ -67,21 +67,21 @@ async fn round(version: &str) -> Option, moq_net::Error>> { assert!(group.read_frame().await.unwrap().is_some()); // The live edge moves a full second past the stalled group's reach. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; for millis in [1000, 2000] { let mut next = track.append_group().unwrap(); next.write_frame(Timestamp::from_millis(millis).unwrap(), &b"edge"[..]) .unwrap(); next.finish().unwrap(); } - let tail = moq_clock::timeout(TIMEOUT, group.read_frame()) + let tail = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("the stalled group never gave up"); assert!(tail.is_err(), "{version}: the live reader saw a clean end: {tail:?}"); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; // A reader with no budget to apply sees only what the downstream hop cached. - let mut cached = moq_clock::timeout( + let mut cached = kio::clock::timeout( TIMEOUT, remote.track("data").unwrap().subscribe( Subscription::default() @@ -92,7 +92,7 @@ async fn round(version: &str) -> Option, moq_net::Error>> { .await .expect("subscribe timeout") .expect("subscribe"); - let first = moq_clock::timeout(TIMEOUT, cached.recv_group()) + let first = kio::clock::timeout(TIMEOUT, cached.recv_group()) .await .expect("group timeout") .unwrap() @@ -104,7 +104,7 @@ async fn round(version: &str) -> Option, moq_net::Error>> { let mut first = first; let mut frames = 0; let end = loop { - match moq_clock::timeout(TIMEOUT, first.read_frame()) + match kio::clock::timeout(TIMEOUT, first.read_frame()) .await .expect("read timeout") { @@ -117,7 +117,7 @@ async fn round(version: &str) -> Option, moq_net::Error>> { Some(end) } -#[moq_clock::test] +#[kio::test] async fn a_stalled_group_is_never_cached_downstream_as_finished() { let mut failures = Vec::new(); for version in VERSIONS { diff --git a/rs/moq-net/tests/integration/quiet_catalog.rs b/rs/moq-net/tests/integration/quiet_catalog.rs index d87cf564cb4..9855715de07 100644 --- a/rs/moq-net/tests/integration/quiet_catalog.rs +++ b/rs/moq-net/tests/integration/quiet_catalog.rs @@ -43,7 +43,7 @@ fn abort(pair: MockPair) { } async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// Announce `live/catalog.json` holding one finished snapshot group. @@ -68,16 +68,16 @@ async fn read_snapshot(remote: &broadcast::Consumer) -> Result>>(versions: &[&str], let mut failures = Vec::new(); for version in versions { let version: Version = version.parse().unwrap(); - match moq_clock::timeout(Duration::from_secs(30), scenario(version)).await { + match kio::clock::timeout(Duration::from_secs(30), scenario(version)).await { Ok(Ok(())) => {} Ok(Err(err)) => failures.push(format!("{version}: {err}")), Err(_) => failures.push(format!("{version}: scenario timed out")), @@ -104,7 +104,7 @@ async fn each_version>>(versions: &[&str], /// `P -> A -> R` is serving a finished catalog and `P -> B -> R` is standing by. /// `A` dies. A new reader on `R` has to receive the snapshot `P` still holds. -#[moq_clock::test] +#[kio::test] async fn a_quiet_catalog_reaches_a_late_reader_after_its_route_dies() { each_version(VERSIONS, |version| async move { let publisher = produce_origin(1); @@ -143,14 +143,14 @@ async fn a_quiet_catalog_reaches_a_late_reader_after_its_route_dies() { /// A peer resumes one group past a finished catalog before anyone else has /// fetched it, so the relay's upstream subscription is created past the only /// group. A fresh reader must still receive that group. -#[moq_clock::test] +#[kio::test] async fn a_quiet_catalog_reaches_a_fresh_reader_when_a_peer_resumes_past_it() { each_version(LITE, |version| resume_then_fresh(version, false)).await; } /// The same, with the fresh reader in-process at the relay. It names no floor at all, /// so the aggregate must not keep the resume's floor above the only group. -#[moq_clock::test] +#[kio::test] async fn a_quiet_catalog_reaches_an_unfloored_relay_reader_when_a_peer_resumes_past_it() { each_version(LITE, |version| resume_then_fresh(version, true)).await; } @@ -169,20 +169,20 @@ async fn resume_then_fresh(version: Version, in_process: bool) -> Result<(), Str let resume_remote = request(&resuming).await; // Held until the scenario returns. Dropping it would cancel the upstream // subscription and let the fresh reader open a new one at the live edge. - let _resume = moq_clock::sim::spawn(async move { + let _resume = kio::clock::sim::spawn(async move { let _sub = resume_remote .track("catalog.json") .unwrap() .subscribe(track::Subscription::default().with_range(1..)) .await .expect("resume subscribe"); - moq_clock::sleep(Duration::from_secs(60)).await; + kio::clock::sleep(Duration::from_secs(60)).await; }); // Wait for the resume to reach the publisher, so the fresh reader widens it // rather than opening its own floorless subscription. let resumed = vec![track::Range::groups(1..)]; - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while track.subscription().map(|sub| sub.ranges).as_ref() != Some(&resumed) { track.subscription_changed().await.unwrap(); } diff --git a/rs/moq-net/tests/integration/range_anchors.rs b/rs/moq-net/tests/integration/range_anchors.rs index 93903a32b7e..796cb5ddee7 100644 --- a/rs/moq-net/tests/integration/range_anchors.rs +++ b/rs/moq-net/tests/integration/range_anchors.rs @@ -62,14 +62,14 @@ async fn read(version: Option<&str>, range: Range) -> Result, Error> { let _pair; let remote = match version { // Through the origin, as a reader of a local route. - None => moq_clock::timeout(TIMEOUT, publisher.consume().request("room", None)) + None => kio::clock::timeout(TIMEOUT, publisher.consume().request("room", None)) .await .expect("resolve timeout") .expect("broadcast resolves"), Some(version) => { _pair = peer(version.parse::().unwrap(), &publisher, &subscriber).await; let consumer = subscriber.consume(); - moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves") @@ -80,12 +80,12 @@ async fn read(version: Option<&str>, range: Range) -> Result, Error> { .with_max_delay(FOREVER) .with_order(Order::Ascending) .with_ranges([range]); - let mut reader = moq_clock::timeout(TIMEOUT, remote.track("data").unwrap().subscribe(subscription)) + let mut reader = kio::clock::timeout(TIMEOUT, remote.track("data").unwrap().subscribe(subscription)) .await .expect("subscribe timeout")?; let mut read = Vec::new(); - while let Ok(group) = moq_clock::timeout(TIMEOUT, reader.recv_group()).await { + while let Ok(group) = kio::clock::timeout(TIMEOUT, reader.recv_group()).await { match group? { Some(group) => read.push(group.sequence), None => break, @@ -117,7 +117,7 @@ fn anchored() -> [(Range, Vec); 6] { /// Each wire resolves the anchors it carries as the held track does and refuses the rest, /// rather than resolve them against the part of the track its copy happens to hold. -#[moq_clock::test] +#[kio::test] async fn each_wire_refuses_only_the_anchors_it_drops() { for version in std::iter::once(None).chain(VERSIONS.iter().copied().map(Some)) { // Lite-07 reports the largest and media time and asks for everything the budget @@ -150,7 +150,7 @@ async fn each_wire_refuses_only_the_anchors_it_drops() { /// Every wire carries the live and oldest starts, which it spells with no floor. A wire whose /// copy starts at the live edge reads oldest from there: no floor asks for the older groups. -#[moq_clock::test] +#[kio::test] async fn every_wire_carries_the_live_and_oldest_starts() { for version in VERSIONS { let live = read(Some(version), Range::live()).await; diff --git a/rs/moq-net/tests/integration/received_rewind.rs b/rs/moq-net/tests/integration/received_rewind.rs index 43989957b87..7e7618817d4 100644 --- a/rs/moq-net/tests/integration/received_rewind.rs +++ b/rs/moq-net/tests/integration/received_rewind.rs @@ -65,13 +65,13 @@ async fn relay( let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); let subscription = Subscription::default().with_max_delay(BUDGET).with_range(0..); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let mut sub = remote .track("data") .unwrap() @@ -81,13 +81,13 @@ async fn relay( let timescale = sub.info().timescale; let mut got = Vec::new(); loop { - let next = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let next = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv_group timed out"); let Some(mut group) = next.expect("recv_group") else { break; }; - while moq_clock::timeout(TIMEOUT, group.read_frame()) + while kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timed out") .expect("read_frame") @@ -98,18 +98,18 @@ async fn relay( (timescale, got) }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 1); // Sent later, so group 0's send time lands after group 1's. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; write_group(&track, 0); track.finish().unwrap(); - let got = moq_clock::timeout(TIMEOUT * 3, reader) + let got = kio::clock::timeout(TIMEOUT * 3, reader) .await .expect("reader hung") .expect("reader panicked"); @@ -117,7 +117,7 @@ async fn relay( got } -#[moq_clock::test] +#[kio::test] async fn a_relay_forwards_descending_send_times_without_closing_the_track() { let mut failures = Vec::new(); for downstream in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { @@ -132,7 +132,7 @@ async fn a_relay_forwards_descending_send_times_without_closing_the_track() { /// A moq-transport peer may stamp arrival times, so a relay keeps a timed track's timestamps /// unchecked and passes them on only over moq-transport: a moq-lite hop, which checks every /// timestamp it receives, is served the track untimed. -#[moq_clock::test] +#[kio::test] async fn moq_transport_timestamps_stay_on_moq_transport() { let mut failures = Vec::new(); for (downstream, expected) in [ @@ -167,7 +167,7 @@ async fn fetch_only(version: &str) -> Vec> { let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -179,15 +179,15 @@ async fn fetch_only(version: &str) -> Vec> { while group.read_frame().await?.is_some() {} Ok(group.sequence) }; - got.push(moq_clock::timeout(TIMEOUT, read).await.expect("fetch timed out")); + got.push(kio::clock::timeout(TIMEOUT, read).await.expect("fetch timed out")); // Answered later, so group 0's send time lands after group 1's. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } drop((pair, remote, broadcast, publisher, subscriber)); got } -#[moq_clock::test] +#[kio::test] async fn fetches_alone_accept_descending_send_times() { let mut failures = Vec::new(); for version in ["moq-lite-05", "moq-lite-06"] { diff --git a/rs/moq-net/tests/integration/rejoin.rs b/rs/moq-net/tests/integration/rejoin.rs index 6e10b19851f..caeb3cc94dc 100644 --- a/rs/moq-net/tests/integration/rejoin.rs +++ b/rs/moq-net/tests/integration/rejoin.rs @@ -37,11 +37,11 @@ async fn read_all(group: &mut group::Consumer) -> moq_net::Result>> /// The relay cancels its idle upstream subscription, resetting that group mid-transfer. /// Resuming the rejoin at the frame where the reset landed would ask upstream for a tail /// whose head is gone, so the group would never reach the returning reader. -#[moq_clock::test] +#[kio::test] async fn rejoin_recovers_the_group_reset_on_leave() { for advance in [false, true] { for version in ["moq-lite-05", "moq-lite-06"] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); @@ -124,7 +124,7 @@ async fn rejoin_recovers_the_group_reset_on_leave() { /// on meanwhile. The cache is stale until the route answers again, so the rejoining reader /// starts at the live edge, whether the answer carries the largest position (lite-07) or /// the first frame says where the feed is. -#[moq_clock::test] +#[kio::test] async fn rejoin_skips_a_cache_kept_by_another_handle() { for version in [ "moq-lite-05", @@ -133,7 +133,7 @@ async fn rejoin_skips_a_cache_kept_by_another_handle() { "moq-transport-18", "moq-transport-22", ] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); @@ -188,10 +188,10 @@ async fn rejoin_skips_a_cache_kept_by_another_handle() { /// last subscriber leaves. The publisher writes groups 1 to 3 meanwhile, and the rejoin /// asks again from the cached head, which a descending track answers newest first. Group /// 3 landing first is not a gap after group 0, so a reader asking from group 0 gets it. -#[moq_clock::test] +#[kio::test] async fn rejoin_keeps_the_cache_when_the_backlog_lands_newest_first() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); @@ -231,14 +231,14 @@ async fn rejoin_keeps_the_cache_when_the_backlog_lands_newest_first() { pair.server_transport.hold_unis(); let rejoin = remote.track("video").unwrap().subscribe(prefs().with_range(0..)); let release = async { - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; pair.server_transport.release_unis_reversed(); }; let (sub, ()) = futures::join!(rejoin, release); let mut sub = sub.unwrap(); let mut rejoined = Vec::new(); // Arrival order, newest first: whatever the reader gets once the backlog settled. - while let Ok(group) = moq_clock::timeout(Duration::from_secs(1), sub.recv_group()).await { + while let Ok(group) = kio::clock::timeout(Duration::from_secs(1), sub.recv_group()).await { rejoined.push(group.unwrap().unwrap().sequence); } rejoined.sort(); @@ -254,7 +254,7 @@ async fn rejoin_keeps_the_cache_when_the_backlog_lands_newest_first() { /// The client still holds the group's head when it rejoins, so it may ask the relay for /// only the rest. A later reader at the relay joins at the live edge and needs the group /// from its first frame, so the relay's copy must keep it. -#[moq_clock::test] +#[kio::test] async fn rejoin_mid_group_keeps_the_head_for_later_readers() { for version in [ "moq-lite-05", @@ -263,7 +263,7 @@ async fn rejoin_mid_group_keeps_the_head_for_later_readers() { "moq-transport-18", "moq-transport-22", ] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); let client = produce_origin(3); @@ -332,10 +332,10 @@ async fn rejoin_mid_group_keeps_the_head_for_later_readers() { /// The publisher accepts the join, but its stream is lost before its header. The open group /// is gone for this copy, but the groups after it must still reach readers, local and /// downstream, rather than wait on a head that is never coming. -#[moq_clock::test] +#[kio::test] async fn rejoin_goes_live_without_the_join_head() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); let client = produce_origin(3); @@ -366,7 +366,7 @@ async fn rejoin_goes_live_without_the_join_head() { // The rejoin's join stream is lost before its header. upstream.server_transport.hold_unis(); - let rejoin = moq_clock::sim::spawn(async move { + let rejoin = kio::clock::sim::spawn(async move { let mut sub = remote.track("video").unwrap().subscribe(None).await.unwrap(); loop { let mut group = sub.recv_group().await.unwrap().unwrap(); @@ -376,7 +376,7 @@ async fn rejoin_goes_live_without_the_join_head() { } }); crate::support::wanted(track.demand()).await.unwrap(); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; upstream.server_transport.drop_unis(); let mut next = track.append_group().unwrap(); @@ -402,10 +402,10 @@ async fn rejoin_goes_live_without_the_join_head() { /// Cancelling waits on the publisher, a round trip on a slow link, but the publisher stops /// serving as soon as the cancel lands. A reader returning in between must already find the /// copy idle, or it takes the cached group as the live edge. -#[moq_clock::test] +#[kio::test] async fn rejoin_during_the_cancel_skips_the_cache() { for version in support::every_version() { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); @@ -459,7 +459,7 @@ async fn rejoin_during_the_cancel_skips_the_cache() { /// rejoin with that group, right after the one the relay cached. Its header lands before its /// first frame. Shown in between, it would leave the cached group without a stamped /// successor, and a reader at the live edge would be handed that older group first. -#[moq_clock::test] +#[kio::test] async fn rejoin_waits_for_the_answers_first_frame() { // Lite01/02 carry no max age, so the publisher serves the relay's cached head again and // that answer is what makes the cache current. @@ -468,7 +468,7 @@ async fn rejoin_waits_for_the_answers_first_frame() { .into_iter() .filter(|version| !unbudgeted.contains(&version.as_str())) { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let relay = produce_origin(2); @@ -503,7 +503,7 @@ async fn rejoin_waits_for_the_answers_first_frame() { pair.server_transport.split_unis(); let mut sub = remote.track("video").unwrap().subscribe(None).await.unwrap(); - let early = moq_clock::timeout(Duration::from_secs(1), sub.recv_group()).await; + let early = kio::clock::timeout(Duration::from_secs(1), sub.recv_group()).await; assert!( early.is_err(), "{version}: the rejoining reader got the cached group {:?} first", @@ -530,7 +530,7 @@ async fn rejoin_waits_for_the_answers_first_frame() { /// A catalog's latest group can sit unread past the cache's idle expiry. A downstream /// session that read it and then leaves must not take the relay's copy of that group with /// it: a reader that joins afterwards needs it, and no newer group may ever come. -#[moq_clock::test] +#[kio::test] async fn leaving_after_the_cache_window_keeps_the_latest_group() { for version in [ "moq-lite-05", @@ -539,7 +539,7 @@ async fn leaving_after_the_cache_window_keeps_the_latest_group() { "moq-transport-18", "moq-transport-22", ] { - moq_clock::timeout(TEST_TIMEOUT + moq_net::cache::DEFAULT_EXPIRY * 3, async { + kio::clock::timeout(TEST_TIMEOUT + moq_net::cache::DEFAULT_EXPIRY * 3, async { let version: Version = version.parse().unwrap(); let publisher = produce_origin(1); let relay = produce_origin(2); @@ -580,7 +580,7 @@ async fn leaving_after_the_cache_window_keeps_the_latest_group() { let mut sub = leaver.track("catalog").unwrap().subscribe(None).await.unwrap(); let mut group = sub.recv_group().await.unwrap().unwrap(); assert_eq!(read_all(&mut group).await.unwrap(), [b"c0"], "{version}"); - moq_clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2).await; + kio::clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2).await; drop((group, sub, leaver, leaver_session)); // Right after the leave, and again once the leaver's front has lingered and let go @@ -589,10 +589,10 @@ async fn leaving_after_the_cache_window_keeps_the_latest_group() { (5, Duration::from_millis(100)), (6, moq_net::cache::DEFAULT_EXPIRY + Duration::from_secs(1)), ] { - moq_clock::sleep(after).await; + kio::clock::sleep(after).await; let (later, _later) = session(hop).await; let mut sub = later.track("catalog").unwrap().subscribe(None).await.unwrap(); - let group = moq_clock::timeout(Duration::from_secs(1), sub.recv_group()).await; + let group = kio::clock::timeout(Duration::from_secs(1), sub.recv_group()).await; let mut group = group .unwrap_or_else(|_| panic!("{version}: reader {hop} never got the latest group")) .unwrap() @@ -611,10 +611,10 @@ async fn leaving_after_the_cache_window_keeps_the_latest_group() { /// The returning subscription opts out of the track's properties from draft-22, since the /// copy already learned them, so its units must come from that first answer rather than /// the empty block the second one carries. -#[moq_clock::test] +#[kio::test] async fn rejoin_keeps_source_timestamps() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let publisher = produce_origin(1); let client = produce_origin(2); @@ -667,7 +667,7 @@ async fn rejoin_keeps_source_timestamps() { /// group must stay protected while that reader holds the track open: a reader joining /// after the cache window needs it, and no newer group may ever come. Once a newer group /// supersedes it, it expires like any other. -#[moq_clock::test] +#[kio::test] async fn rejoined_quiet_catalog_survives_cache_expiry() { for version in [ "moq-lite-05", @@ -685,7 +685,7 @@ async fn rejoined_quiet_catalog_survives_cache_expiry() { /// The publisher reconnects while a reader holds the catalog. A late reader through the /// new connection still needs the quiet catalog, even on a wire without epochs where /// the old reader ends with its route. -#[moq_clock::test] +#[kio::test] async fn taken_over_quiet_catalog_survives_cache_expiry() { for version in [ "moq-lite-05", @@ -699,7 +699,7 @@ async fn taken_over_quiet_catalog_survives_cache_expiry() { } async fn quiet_catalog_survives_cache_expiry(version: Version, takeover: bool) { - moq_clock::timeout(TEST_TIMEOUT + moq_net::cache::DEFAULT_EXPIRY * 5, async { + kio::clock::timeout(TEST_TIMEOUT + moq_net::cache::DEFAULT_EXPIRY * 5, async { let publisher = produce_origin(1); let relay = produce_origin(2); let broadcast = publisher.create_broadcast("bench").unwrap(); @@ -769,9 +769,9 @@ async fn quiet_catalog_survives_cache_expiry(version: Version, takeover: bool) { (holder, remote, pair) }; - moq_clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2 + Duration::from_secs(2)).await; + kio::clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2 + Duration::from_secs(2)).await; let (mut later, later_remote, _later_pair) = session(5).await; - let mut group = moq_clock::timeout(Duration::from_secs(1), later.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(1), later.recv_group()) .await .unwrap_or_else(|_| panic!("{version} takeover={takeover}: late reader lost the latest catalog")) .unwrap() @@ -788,13 +788,13 @@ async fn quiet_catalog_survives_cache_expiry(version: Version, takeover: bool) { // Epochless wires end the old holder on takeover. The late reader uses the // current route on every version, and keeps that copy live for the expiry check. assert_eq!(later.recv_group().await.unwrap().unwrap().sequence, 1, "{version}"); - moq_clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2 + Duration::from_secs(2)).await; + kio::clock::sleep(moq_net::cache::DEFAULT_EXPIRY * 2 + Duration::from_secs(2)).await; let old = async { let mut group = later_remote.track("catalog").unwrap().fetch_group(0, None).await?; group.read_frame().await }; assert!( - moq_clock::timeout(Duration::from_secs(1), old).await.unwrap().is_err(), + kio::clock::timeout(Duration::from_secs(1), old).await.unwrap().is_err(), "{version} takeover={takeover}: the superseded catalog never expired" ); drop(upstream_session); diff --git a/rs/moq-net/tests/integration/relay_upstream_close.rs b/rs/moq-net/tests/integration/relay_upstream_close.rs index b9ff817eff0..f0e68bec5d8 100644 --- a/rs/moq-net/tests/integration/relay_upstream_close.rs +++ b/rs/moq-net/tests/integration/relay_upstream_close.rs @@ -113,7 +113,7 @@ async fn round(name: &str, end: End) -> Vec { let downstream = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -122,12 +122,12 @@ async fn round(name: &str, end: End) -> Vec { for (index, track) in tracks.iter().enumerate() { let subscription = Subscription::default().with_max_delay(MAX_DELAY).with_range(0..); let sub = remote.track(&format!("track{index}")).unwrap().subscribe(subscription); - let sub = moq_clock::timeout(TIMEOUT, sub) + let sub = kio::clock::timeout(TIMEOUT, sub) .await .expect("the subscription never became active") .expect("subscribe"); - readers.push(moq_clock::sim::spawn(read(sub))); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(track)) + readers.push(kio::clock::sim::spawn(read(sub))); + kio::clock::timeout(TIMEOUT, support::harness::subscribed(track)) .await .expect("no subscriber appeared"); } @@ -148,25 +148,25 @@ async fn round(name: &str, end: End) -> Vec { } match end { - End::Close => moq_clock::timeout(TIMEOUT, upstream.server.clone().close()) + End::Close => kio::clock::timeout(TIMEOUT, upstream.server.clone().close()) .await .expect("close timed out") .expect("the close drains"), End::Abort => { // Simulated time advances only once every task is idle: the relay has read // everything the unheld upstream hop carried. - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; upstream.server.abort(Error::Cancel); } } drop((tracks, broadcast, publisher, upstream)); // The relay sees the session and its broadcast go before the subscriber reads on. - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; downstream.server_transport.release_unis(); let mut outcomes = Vec::new(); for reader in readers { - let outcome = moq_clock::timeout(TIMEOUT, reader) + let outcome = kio::clock::timeout(TIMEOUT, reader) .await .unwrap_or_else(|_| panic!("{name} {end:?}: a track never ended")) .expect("reader panicked"); @@ -180,7 +180,7 @@ async fn round(name: &str, end: End) -> Vec { /// track's SUBSCRIBE FIN, which lets the close drain, before the relay has read it, so the /// relay must still read it from the closed session. Lite03 and Lite04 declare no end, so /// there the relay is still waiting out its tail grace and the FIN is the track's only end. -#[moq_clock::test] +#[kio::test] async fn relay_delivers_finished_tracks_after_upstream_closes() { let want: Vec<(u64, u64)> = (0..GROUPS) .flat_map(|group| (0..FRAMES).map(move |frame| (group, frame))) diff --git a/rs/moq-net/tests/integration/replacement.rs b/rs/moq-net/tests/integration/replacement.rs index 2e94c937366..05c51b24d48 100644 --- a/rs/moq-net/tests/integration/replacement.rs +++ b/rs/moq-net/tests/integration/replacement.rs @@ -40,7 +40,7 @@ async fn link(version: Version, from: &origin::Producer, to: &origin::Producer) /// The next announce event, failing on a hang. async fn next_event(announced: &mut announce::Consumer) -> announce::Event { - moq_clock::timeout(Duration::from_secs(10), announced.next()) + kio::clock::timeout(Duration::from_secs(10), announced.next()) .await .expect("announce hung") .expect("announce ended") @@ -55,7 +55,7 @@ fn write(track: &track::Producer, tag: &str) { /// The next frame a subscription delivers, as text. async fn read(subscription: &mut track::Subscriber) -> String { - let mut group = moq_clock::timeout(Duration::from_secs(10), subscription.recv_group()) + let mut group = kio::clock::timeout(Duration::from_secs(10), subscription.recv_group()) .await .expect("subscription hung") .unwrap() @@ -65,7 +65,7 @@ async fn read(subscription: &mut track::Subscriber) -> String { } async fn subscribe(broadcast: &broadcast::Consumer, name: &str) -> Result { - moq_clock::timeout(Duration::from_secs(10), broadcast.track(name)?.subscribe(None)) + kio::clock::timeout(Duration::from_secs(10), broadcast.track(name)?.subscribe(None)) .await .expect("subscribe hung") } @@ -103,7 +103,7 @@ async fn replace(version: &str, epoch: Option) { // The replacement: the same peer re-announces everything over a second session, // while the first one is still open. let _second = link(version, &publisher, &viewer).await; - moq_clock::sleep(WITHIN_HOLD).await; + kio::clock::sleep(WITHIN_HOLD).await; // A request through the old handle right after the replacement is still served. let mut late = subscribe(&old, "audio") @@ -115,7 +115,7 @@ async fn replace(version: &str, epoch: Option) { if epoch.is_some() { // The epoch continues across the replacement: nothing to restart, and the old // handle keeps serving. - if let Ok(event) = moq_clock::timeout(PAST_HOLD, announced.next()).await { + if let Ok(event) = kio::clock::timeout(PAST_HOLD, announced.next()).await { panic!("{version}: an epoch route restarted on replacement: {event:?}"); } let mut later = subscribe(&old, "meta").await.unwrap(); @@ -126,7 +126,7 @@ async fn replace(version: &str, epoch: Option) { // Without an epoch the replacement is a restart: once the hold releases it, the old // handle refuses new requests, and the restart is already there to follow. - moq_clock::sleep(PAST_HOLD).await; + kio::clock::sleep(PAST_HOLD).await; let Err(err) = subscribe(&old, "meta").await else { panic!("{version}: a retired handle served a request"); }; @@ -149,43 +149,43 @@ fn epoch() -> Epoch { "01900000-0000-7000-8000-000000000001".parse().unwrap() } -#[moq_clock::test] +#[kio::test] async fn epochless_lite06() { - moq_clock::timeout(TEST_TIMEOUT, replace("moq-lite-06", None)) + kio::clock::timeout(TEST_TIMEOUT, replace("moq-lite-06", None)) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn epochless_lite07() { - moq_clock::timeout(TEST_TIMEOUT, replace("moq-lite-07-wip", None)) + kio::clock::timeout(TEST_TIMEOUT, replace("moq-lite-07-wip", None)) .await .expect("timed out"); } /// Only lite-07 carries the epoch. -#[moq_clock::test] +#[kio::test] async fn epoch_lite07() { - moq_clock::timeout(TEST_TIMEOUT, replace("moq-lite-07-wip", Some(epoch()))) + kio::clock::timeout(TEST_TIMEOUT, replace("moq-lite-07-wip", Some(epoch()))) .await .expect("timed out"); } /// moq-transport carries the epoch with the MoQ Epoch extension. -#[moq_clock::test] +#[kio::test] async fn epoch_ietf() { for version in ["moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TEST_TIMEOUT, replace(version, Some(epoch()))) + kio::clock::timeout(TEST_TIMEOUT, replace(version, Some(epoch()))) .await .expect("timed out"); } } /// Without one, a moq-transport replacement restarts as it does over lite. -#[moq_clock::test] +#[kio::test] async fn epochless_ietf() { for version in ["moq-transport-22"] { - moq_clock::timeout(TEST_TIMEOUT, replace(version, None)) + kio::clock::timeout(TEST_TIMEOUT, replace(version, None)) .await .expect("timed out"); } @@ -221,7 +221,7 @@ async fn route_death(version: &str, relayed: bool, wait: Duration) { assert_eq!(read(&mut sticky).await, "video:0", "{version}"); let _replacement = link(version, &publisher, upstream).await; - moq_clock::sleep(wait).await; + kio::clock::sleep(wait).await; write(&video, "video:1"); assert_eq!( read(&mut sticky).await, @@ -230,7 +230,7 @@ async fn route_death(version: &str, relayed: bool, wait: Duration) { ); let _ = old_session.server.close().await; - let end = moq_clock::timeout(Duration::from_secs(10), async { + let end = kio::clock::timeout(Duration::from_secs(10), async { loop { match sticky.recv_group().await { Ok(Some(_)) => continue, @@ -247,22 +247,22 @@ async fn route_death(version: &str, relayed: bool, wait: Duration) { ); } -#[moq_clock::test] +#[kio::test] async fn route_death_within_hold_errors() { for version in ["moq-lite-06", "moq-lite-07-wip"] { for relayed in [false, true] { - moq_clock::timeout(TEST_TIMEOUT, route_death(version, relayed, WITHIN_HOLD)) + kio::clock::timeout(TEST_TIMEOUT, route_death(version, relayed, WITHIN_HOLD)) .await .expect("timed out"); } } } -#[moq_clock::test] +#[kio::test] async fn route_death_past_hold_errors() { for version in ["moq-lite-06", "moq-lite-07-wip"] { for relayed in [false, true] { - moq_clock::timeout(TEST_TIMEOUT, route_death(version, relayed, PAST_HOLD)) + kio::clock::timeout(TEST_TIMEOUT, route_death(version, relayed, PAST_HOLD)) .await .expect("timed out"); } @@ -291,7 +291,7 @@ async fn restart_while_the_old_session_lingers(version: &str, old_hop: u64, new_ let new_cam = new.publish("cam", origin::Route::default()).unwrap(); let new_video = new_cam.create_track("video", timed()).unwrap(); let _new_session = link(version, &new, &viewer).await; - moq_clock::sleep(PAST_HOLD).await; + kio::clock::sleep(PAST_HOLD).await; let cam = viewer.consume().request("cam", None).await.unwrap(); let mut video = subscribe(&cam, "video") @@ -301,11 +301,11 @@ async fn restart_while_the_old_session_lingers(version: &str, old_hop: u64, new_ assert_eq!(read(&mut video).await, "new:0", "{version} ({old_hop} -> {new_hop})"); } -#[moq_clock::test] +#[kio::test] async fn restart_while_the_old_session_lingers_wins() { for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { for (old_hop, new_hop) in [(1, 4), (4, 1)] { - moq_clock::timeout( + kio::clock::timeout( TEST_TIMEOUT, restart_while_the_old_session_lingers(version, old_hop, new_hop), ) diff --git a/rs/moq-net/tests/integration/request_caps.rs b/rs/moq-net/tests/integration/request_caps.rs index 4414e4e5385..165552593fa 100644 --- a/rs/moq-net/tests/integration/request_caps.rs +++ b/rs/moq-net/tests/integration/request_caps.rs @@ -66,13 +66,13 @@ fn limits(announces: usize) -> Limits { /// Many more requests than the stream credit admits at once, opened and closed in turn, all /// succeed: each one that closes is granted back. -#[moq_clock::test] +#[kio::test] async fn closed_requests_are_granted_back() { const ROUNDS: usize = 64; for version in VERSIONS { let setup = setup(version, limits(0), ROUNDS).await; - let broadcast = moq_clock::timeout( + let broadcast = kio::clock::timeout( TIMEOUT, setup.client.consume().follow("bcast", None).unwrap().available(), ) @@ -82,7 +82,7 @@ async fn closed_requests_are_granted_back() { for round in 0..ROUNDS { let track = broadcast.track(&format!("t{round}")).unwrap(); - let subscriber = moq_clock::timeout(TIMEOUT, track.subscribe(None)) + let subscriber = kio::clock::timeout(TIMEOUT, track.subscribe(None)) .await .unwrap_or_else(|_| panic!("{version}: round {round} stalled")) .unwrap_or_else(|err| panic!("{version}: round {round} refused: {err}")); @@ -91,7 +91,7 @@ async fn closed_requests_are_granted_back() { // Wait for the server to see it end, so the next round is a fresh request. let published = &setup.tracks[round]; - moq_clock::timeout(TIMEOUT, crate::support::unwanted(published.demand())) + kio::clock::timeout(TIMEOUT, crate::support::unwanted(published.demand())) .await .unwrap_or_else(|_| panic!("{version}: round {round} never ended")) .unwrap(); @@ -102,7 +102,7 @@ async fn closed_requests_are_granted_back() { /// With no subscription cap, a client asking for more subscriptions than the server admits /// still holds no more than the stream credit at once. The rest wait rather than close the /// session. -#[moq_clock::test] +#[kio::test] async fn flow_control_bounds_the_subscriptions_a_peer_holds() { // 8 bidi streams toward the server. const BOUND: usize = 8; @@ -125,26 +125,26 @@ async fn flow_control_bounds_the_subscriptions_a_peer_holds() { options.server_limits = Some(limits(0)); let pair = connect_mock(options).await; - let remote = moq_clock::timeout(TIMEOUT, client.consume().follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, client.consume().follow("bcast", None).unwrap().available()) .await .expect("announce timeout") .unwrap(); let subscribing: Vec<_> = (0..TRACKS) .map(|i| { let track = remote.track(&format!("t{i}")).unwrap(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let _subscriber = track.subscribe(None).await; std::future::pending::<()>().await }) }) .collect(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let held = tracks.iter().filter(|track| track.demand().wanted().is_some()).count(); assert!(held > 0, "{version}: nothing was subscribed"); assert!(held <= BOUND, "{version}: the server holds {held} subscriptions"); assert!( - moq_clock::timeout(Duration::from_millis(100), pair.client.closed()) + kio::clock::timeout(Duration::from_millis(100), pair.client.closed()) .await .is_err(), "{version}: the session closed" @@ -156,7 +156,7 @@ async fn flow_control_bounds_the_subscriptions_a_peer_holds() { } /// A broadcast announced past the cap closes the session with TOO_MANY_REQUESTS. -#[moq_clock::test] +#[kio::test] async fn an_announce_past_the_cap_closes_the_session() { for version in VERSIONS { let version: Version = version.parse().unwrap(); @@ -173,7 +173,7 @@ async fn an_announce_past_the_cap_closes_the_session() { options.server_limits = Some(limits(1)); let pair = connect_mock(options).await; - let err = moq_clock::timeout(TIMEOUT, pair.client.closed()) + let err = kio::clock::timeout(TIMEOUT, pair.client.closed()) .await .unwrap_or_else(|_| panic!("{version}: the session stayed open")); assert!( diff --git a/rs/moq-net/tests/integration/route_change.rs b/rs/moq-net/tests/integration/route_change.rs index 89dbd6a0288..a19a209941b 100644 --- a/rs/moq-net/tests/integration/route_change.rs +++ b/rs/moq-net/tests/integration/route_change.rs @@ -66,7 +66,7 @@ fn tagged(name: &str, group: u64, frame: u64) -> Vec { /// Let every task settle. Time is paused, so this returns once the runtime is idle. async fn settle() { - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; } /// How the serving route goes away (or is beaten). @@ -182,7 +182,7 @@ type Delivery = (u64, moq_net::Result<(Option, Vec)>); /// Read every group in full, reporting each frame as it arrives. fn read(mut sub: track::Subscriber) -> mpsc::UnboundedReceiver { let (tx, rx) = mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { loop { let mut group = match sub.recv_group().await { Ok(Some(group)) => group, @@ -220,7 +220,7 @@ async fn next(rx: &mut mpsc::UnboundedReceiver) -> (u64, Vec) { /// [`next`], keeping the frame's timestamp. async fn next_timed(rx: &mut mpsc::UnboundedReceiver) -> (u64, Option, Vec) { - let (group, frame) = moq_clock::timeout(Duration::from_secs(10), rx.next()) + let (group, frame) = kio::clock::timeout(Duration::from_secs(10), rx.next()) .await .expect("reader hung") .expect("reader ended"); @@ -343,7 +343,7 @@ async fn route_dies_without_an_epoch(version: &str, trigger: Trigger) { let mut group = topology.track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, payload(1, 0)).unwrap(); settle().await; - match moq_clock::timeout(Duration::from_secs(10), rx.next()) + match kio::clock::timeout(Duration::from_secs(10), rx.next()) .await .expect("reader hung") { @@ -424,37 +424,37 @@ macro_rules! route_change_tests { use super::*; async fn run(trigger: Trigger, position: Position) { - moq_clock::timeout(TEST_TIMEOUT, route_change($version, trigger, position)) + kio::clock::timeout(TEST_TIMEOUT, route_change($version, trigger, position)) .await .expect("timed out"); } - #[moq_clock::test] + #[kio::test] async fn disconnect_between_groups() { run(Trigger::Disconnect, Position::BetweenGroups).await; } - #[moq_clock::test] + #[kio::test] async fn disconnect_mid_group() { run(Trigger::Disconnect, Position::MidGroup).await; } - #[moq_clock::test] + #[kio::test] async fn unannounce_between_groups() { run(Trigger::Unannounce, Position::BetweenGroups).await; } - #[moq_clock::test] + #[kio::test] async fn unannounce_mid_group() { run(Trigger::Unannounce, Position::MidGroup).await; } - #[moq_clock::test] + #[kio::test] async fn better_route_between_groups() { run(Trigger::BetterRoute, Position::BetweenGroups).await; } - #[moq_clock::test] + #[kio::test] async fn better_route_mid_group() { run(Trigger::BetterRoute, Position::MidGroup).await; } @@ -477,26 +477,26 @@ macro_rules! pinned_tests { use super::*; async fn run(trigger: Trigger) { - moq_clock::timeout(TEST_TIMEOUT, route_dies_without_an_epoch($version, trigger)) + kio::clock::timeout(TEST_TIMEOUT, route_dies_without_an_epoch($version, trigger)) .await .expect("timed out"); } - #[moq_clock::test] + #[kio::test] async fn disconnect_ends_the_subscription() { run(Trigger::Disconnect).await; } - #[moq_clock::test] + #[kio::test] async fn unannounce_ends_the_subscription() { run(Trigger::Unannounce).await; } /// A better route without an epoch wins new requests and announces as a /// restart, while the incumbent's subscriptions continue. - #[moq_clock::test] + #[kio::test] async fn better_route_keeps_the_incumbent() { - moq_clock::timeout(TEST_TIMEOUT, better_route_restarts($version)) + kio::clock::timeout(TEST_TIMEOUT, better_route_restarts($version)) .await .expect("timed out"); } @@ -601,17 +601,17 @@ async fn lagging_route_dies(version: Version) { let _keep = (broadcast, track, group, p_a, p_b, b_w, b_r, warm, a_r, p, a, b, r, w); } -#[moq_clock::test] +#[kio::test] async fn lite_resumes_after_a_lagging_route_dies() { lagging_route_dies("moq-lite-07-wip".parse().unwrap()).await; } -#[moq_clock::test] +#[kio::test] async fn ietf_17_resumes_after_a_lagging_route_dies() { lagging_route_dies("moq-transport-18".parse().unwrap()).await; } -#[moq_clock::test] +#[kio::test] async fn ietf_22_resumes_after_a_lagging_route_dies() { lagging_route_dies("moq-transport-22".parse().unwrap()).await; } @@ -671,7 +671,7 @@ async fn undetected_outage(budget: Duration) -> BTreeMap> { pair.client_transport.set_latency(Duration::from_secs(3600)); } } - moq_clock::sleep(STEP).await; + kio::clock::sleep(STEP).await; } group.finish().unwrap(); if sequence == O_NOTICES { @@ -680,13 +680,13 @@ async fn undetected_outage(budget: Duration) -> BTreeMap> { } if sequence == E_NOTICES { // Off the group boundary, so no group's age sits on the budget. - moq_clock::sleep(STEP * 5 / 2).await; + kio::clock::sleep(STEP * 5 / 2).await; // The groups `O` asks for again reach it newest first, as a congested `P` sends // a descending track. p_o.server_transport.hold_unis(); m1_e.server.abort(Error::Cancel); m1_e.client.abort(Error::Cancel); - moq_clock::sleep(STEP).await; + kio::clock::sleep(STEP).await; p_o.server_transport.release_unis_by_priority(); } while let Ok((group, frame)) = rx.try_recv() { @@ -711,9 +711,9 @@ fn resumed(groups: std::ops::RangeInclusive) -> BTreeMap> } /// A budget that outlasts the outage gets every group it held back. -#[moq_clock::test] +#[kio::test] async fn resume_delivers_an_outage_within_the_budget() { - let after = moq_clock::timeout(TEST_TIMEOUT, undetected_outage(Duration::from_secs(10))) + let after = kio::clock::timeout(TEST_TIMEOUT, undetected_outage(Duration::from_secs(10))) .await .expect("timed out"); assert_eq!(after, resumed(5..=12)); @@ -722,9 +722,9 @@ async fn resume_delivers_an_outage_within_the_budget() { /// A budget shorter than the outage gets only the groups it still covers: a group is /// stale once its successor arrived a full budget ago. Group 4 is the one being read, so /// it continues regardless. -#[moq_clock::test] +#[kio::test] async fn resume_delivers_the_outage_tail_within_the_budget() { - let after = moq_clock::timeout(TEST_TIMEOUT, undetected_outage(Duration::from_secs(4))) + let after = kio::clock::timeout(TEST_TIMEOUT, undetected_outage(Duration::from_secs(4))) .await .expect("timed out"); assert_eq!(after, resumed(6..=12)); @@ -733,9 +733,9 @@ async fn resume_delivers_the_outage_tail_within_the_budget() { macro_rules! route_flap_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, route_flaps($version)) + kio::clock::timeout(TEST_TIMEOUT, route_flaps($version)) .await .expect("timed out"); } @@ -857,9 +857,9 @@ async fn redundant_pair_fails_over(version: &str, loss: Loss) { drop(kept); } -#[moq_clock::test] +#[kio::test] async fn redundant_pair_fails_over_when_unreachable() { - moq_clock::timeout( + kio::clock::timeout( TEST_TIMEOUT, redundant_pair_fails_over("moq-lite-07-wip", Loss::Unreachable), ) @@ -867,9 +867,9 @@ async fn redundant_pair_fails_over_when_unreachable() { .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn redundant_pair_fails_over_when_the_incumbent_ends() { - moq_clock::timeout(TEST_TIMEOUT, redundant_pair_fails_over("moq-lite-07-wip", Loss::Ends)) + kio::clock::timeout(TEST_TIMEOUT, redundant_pair_fails_over("moq-lite-07-wip", Loss::Ends)) .await .expect("timed out"); } @@ -960,34 +960,34 @@ async fn replaced_behind_a_relay(version: &str, epoch: Option, r drop((dead, replicas)); } -#[moq_clock::test] +#[kio::test] async fn replaced_without_an_epoch_ends_lite_06() { - moq_clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-06", None, false)) + kio::clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-06", None, false)) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn replaced_without_an_epoch_ends_lite_07() { - moq_clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-07-wip", None, false)) + kio::clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-07-wip", None, false)) .await .expect("timed out"); } /// The relay resumes a pair sharing an epoch, so nothing reaches `D`. -#[moq_clock::test] +#[kio::test] async fn pair_behind_a_relay_fails_over_lite_07() { let epoch = Some(moq_net::Epoch::mint()); - moq_clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-07-wip", epoch, true)) + kio::clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-07-wip", epoch, true)) .await .expect("timed out"); } /// lite-06 carries no epoch, so the relay cannot tell the pair is one broadcast. -#[moq_clock::test] +#[kio::test] async fn pair_behind_a_relay_ends_lite_06() { let epoch = Some(moq_net::Epoch::mint()); - moq_clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-06", epoch, false)) + kio::clock::timeout(TEST_TIMEOUT, replaced_behind_a_relay("moq-lite-06", epoch, false)) .await .expect("timed out"); } @@ -1076,16 +1076,16 @@ async fn compression_changes_behind_a_relay(compress: bool) { drop((dead, replicas)); } -#[moq_clock::test] +#[kio::test] async fn same_compression_resumes_behind_a_relay() { - moq_clock::timeout(TEST_TIMEOUT, compression_changes_behind_a_relay(true)) + kio::clock::timeout(TEST_TIMEOUT, compression_changes_behind_a_relay(true)) .await .expect("timed out"); } -#[moq_clock::test] +#[kio::test] async fn different_compression_is_refused_behind_a_relay() { - moq_clock::timeout(TEST_TIMEOUT, compression_changes_behind_a_relay(false)) + kio::clock::timeout(TEST_TIMEOUT, compression_changes_behind_a_relay(false)) .await .expect("timed out"); } @@ -1107,7 +1107,7 @@ async fn producer_replaced(version: &str) { .announce(origin::Route::default().with_epoch(moq_net::Epoch::mint())) .unwrap(); let (tx, mut producers) = mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { while let Ok(request) = dynamic.requested_track().await { if tx.unbounded_send(request.accept(timed())).is_err() { return; @@ -1138,7 +1138,7 @@ async fn producer_replaced(version: &str) { // The encoder restarts: the old producer goes away mid-broadcast, and the resumed // subscription asks for the track again. first.abort(Error::Cancel).unwrap(); - let second = moq_clock::timeout(Duration::from_secs(10), producers.next()) + let second = kio::clock::timeout(Duration::from_secs(10), producers.next()) .await .expect("the track was not requested again") .unwrap(); @@ -1162,9 +1162,9 @@ async fn producer_replaced(version: &str) { macro_rules! producer_replaced_tests { ($($name:ident: $version:literal,)*) => { $( - #[moq_clock::test] + #[kio::test] async fn $name() { - moq_clock::timeout(TEST_TIMEOUT, producer_replaced($version)) + kio::clock::timeout(TEST_TIMEOUT, producer_replaced($version)) .await .expect("timed out"); } diff --git a/rs/moq-net/tests/integration/segmented_frame.rs b/rs/moq-net/tests/integration/segmented_frame.rs index 27ac7c9e608..c87d4c7db06 100644 --- a/rs/moq-net/tests/integration/segmented_frame.rs +++ b/rs/moq-net/tests/integration/segmented_frame.rs @@ -23,7 +23,7 @@ fn origin(hop: u64) -> origin::Producer { origin } -#[moq_clock::test] +#[kio::test] async fn a_segmented_frame_crosses_whole() { let payload = Bytes::from((0..SIZE).map(|i| (i % 251) as u8).collect::>()); for version in VERSIONS { @@ -40,7 +40,7 @@ async fn a_segmented_frame_crosses_whole() { options.client_subscribe = Some(viewer.clone()); let _pair = connect_mock(options).await; - let remote = moq_clock::timeout(TIMEOUT, viewer.consume().follow("room", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, viewer.consume().follow("room", None).unwrap().available()) .await .expect("broadcast timeout") .unwrap(); @@ -63,7 +63,7 @@ async fn a_segmented_frame_crosses_whole() { } group.finish().unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() diff --git a/rs/moq-net/tests/integration/session_close.rs b/rs/moq-net/tests/integration/session_close.rs index 7d268a3dbc8..7cb486cb067 100644 --- a/rs/moq-net/tests/integration/session_close.rs +++ b/rs/moq-net/tests/integration/session_close.rs @@ -32,7 +32,7 @@ type Read = (Vec>, Result<(), Error>); struct Setup { pair: MockPair, track: moq_net::track::Producer, - reader: moq_clock::sim::JoinHandle, + reader: kio::clock::sim::JoinHandle, _broadcast: moq_net::origin::Publication, } @@ -54,14 +54,14 @@ async fn setup_with_gate(version: &str, gate: Option>) -> Se let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); // The publisher only learns of a subscription once the subscriber polls it. let (ready, active) = futures::channel::oneshot::channel(); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let mut sub = remote.track("video").unwrap().subscribe(None).await.expect("subscribe"); let _ = ready.send(()); let mut got = Vec::new(); @@ -81,12 +81,12 @@ async fn setup_with_gate(version: &str, gate: Option>) -> Se } }); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); // Both ends hold the subscription, so a close tests only the group tail and not a // control response still in flight. - moq_clock::timeout(TIMEOUT, active) + kio::clock::timeout(TIMEOUT, active) .await .expect("the subscription never became active") .expect("reader alive"); @@ -100,7 +100,7 @@ async fn setup_with_gate(version: &str, gate: Option>) -> Se } /// TRACK_INFO creates demand before any SUBSCRIBE, so demand alone cannot gate a drain test. -#[moq_clock::test] +#[kio::test] async fn track_info_interest_precedes_a_subscription() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let publisher = produce_origin(1); @@ -125,12 +125,12 @@ async fn track_info_interest_precedes_a_subscription() { /// A finished track's last group and FIN reach the subscriber, even though the /// close is requested before the session wrote them. -#[moq_clock::test] +#[kio::test] async fn close_delivers_a_finished_track() { close_delivers_a_finished_track_for("moq-lite-05").await; } -#[moq_clock::test] +#[kio::test] async fn ietf_close_delivers_a_finished_track() { close_delivers_a_finished_track_for("moq-transport-22").await; } @@ -145,17 +145,17 @@ async fn close_delivers_a_finished_track_for(version: &str) { group.finish().unwrap(); track.finish().unwrap(); - let started = moq_clock::now(); - moq_clock::timeout(TIMEOUT, pair.client.close()) + let started = kio::clock::now(); + kio::clock::timeout(TIMEOUT, pair.client.close()) .await .expect("close timed out") .expect("the close drains"); assert!( - (moq_clock::now() - started) < Duration::from_secs(1), + (kio::clock::now() - started) < Duration::from_secs(1), "drained before the deadline" ); - let (got, end) = moq_clock::timeout(TIMEOUT, reader) + let (got, end) = kio::clock::timeout(TIMEOUT, reader) .await .expect("reader timed out") .unwrap(); @@ -165,12 +165,12 @@ async fn close_delivers_a_finished_track_for(version: &str) { /// A track that never finishes holds the drain until the deadline, then the /// session closes anyway. -#[moq_clock::test] +#[kio::test] async fn close_gives_up_on_a_live_track() { close_gives_up_on_a_live_track_for("moq-lite-05").await; } -#[moq_clock::test] +#[kio::test] async fn ietf_close_gives_up_on_a_live_track() { close_gives_up_on_a_live_track_for("moq-transport-22").await; } @@ -180,21 +180,21 @@ async fn close_gives_up_on_a_live_track_for(version: &str) { pair, track: _track, .. } = setup(version).await; - let started = moq_clock::now(); - let res = moq_clock::timeout(TIMEOUT, pair.client.close()) + let started = kio::clock::now(); + let res = kio::clock::timeout(TIMEOUT, pair.client.close()) .await .expect("close timed out"); assert!(matches!(res, Err(Error::Timeout)), "{res:?}"); - assert_eq!((moq_clock::now() - started), Duration::from_secs(1)); + assert_eq!((kio::clock::now() - started), Duration::from_secs(1)); } /// An abort from another handle cuts a drain short. -#[moq_clock::test] +#[kio::test] async fn abort_cuts_a_drain_short() { abort_cuts_a_drain_short_for("moq-lite-05").await; } -#[moq_clock::test] +#[kio::test] async fn ietf_abort_cuts_a_drain_short() { abort_cuts_a_drain_short_for("moq-transport-22").await; } @@ -205,24 +205,24 @@ async fn abort_cuts_a_drain_short_for(version: &str) { } = setup(version).await; let other = pair.client.clone(); - let started = moq_clock::now(); - let close = moq_clock::sim::spawn(pair.client.close()); - moq_clock::sleep(Duration::from_millis(100)).await; + let started = kio::clock::now(); + let close = kio::clock::sim::spawn(pair.client.close()); + kio::clock::sleep(Duration::from_millis(100)).await; other.abort(Error::Cancel); - let res = moq_clock::timeout(TIMEOUT, close) + let res = kio::clock::timeout(TIMEOUT, close) .await .expect("close timed out") .unwrap(); assert!(res.is_err() && !matches!(res, Err(Error::Timeout)), "{res:?}"); assert!( - (moq_clock::now() - started) < Duration::from_secs(1), + (kio::clock::now() - started) < Duration::from_secs(1), "{res:?} after {:?}", - (moq_clock::now() - started) + (kio::clock::now() - started) ); } -#[moq_clock::test] +#[kio::test] async fn close_withdraws_announcements_before_closing_the_transport() { for version in ["moq-lite-01", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { let publisher = produce_origin(1); @@ -243,7 +243,7 @@ async fn close_withdraws_announcements_before_closing_the_transport() { } } -#[moq_clock::test] +#[kio::test] async fn close_times_out_waiting_for_announcement_acknowledgements() { for version in ["moq-lite-01", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { let publisher = produce_origin(1); @@ -256,14 +256,14 @@ async fn close_times_out_waiting_for_announcement_acknowledgements() { let pair = connect_mock(options).await; crate::support::announced(&subscriber.consume(), "bcast").await; pair.client_transport.hold_fin_acknowledgements(); - let started = moq_clock::now(); + let started = kio::clock::now(); assert!(matches!(pair.client.close().await, Err(Error::Timeout)), "{version}"); - assert_eq!(moq_clock::now() - started, Duration::from_secs(1)); + assert_eq!(kio::clock::now() - started, Duration::from_secs(1)); } } /// A transport ACK is not proof the subscriber read the final group. -#[moq_clock::test] +#[kio::test] async fn close_tail() { let Setup { pair, track, reader, .. @@ -274,8 +274,8 @@ async fn close_tail() { group.write_frame(Timestamp::ZERO, b"last".as_slice()).unwrap(); group.finish().unwrap(); track.finish().unwrap(); - let close = moq_clock::sim::spawn(pair.client.close()); - moq_clock::sleep(Duration::from_millis(100)).await; + let close = kio::clock::sim::spawn(pair.client.close()); + kio::clock::sleep(Duration::from_millis(100)).await; assert!( !close.is_finished(), "close must wait for the subscriber, not the transport ACK" @@ -291,7 +291,7 @@ async fn close_tail() { } /// A lite07 peer that never acknowledges the track end cannot report a successful close. -#[moq_clock::test] +#[kio::test] async fn close_requires_subscriber_fin() { let Setup { pair, @@ -305,27 +305,27 @@ async fn close_requires_subscriber_fin() { group.write_frame(Timestamp::ZERO, b"last".as_slice()).unwrap(); group.finish().unwrap(); track.finish().unwrap(); - let started = moq_clock::now(); + let started = kio::clock::now(); assert!(matches!(pair.client.close().await, Err(Error::Timeout))); - assert_eq!(moq_clock::now() - started, Duration::from_secs(1)); + assert_eq!(kio::clock::now() - started, Duration::from_secs(1)); } /// Released drafts retain ACK-based close even when application delivery is delayed. -#[moq_clock::test] +#[kio::test] async fn older_lite_close_keeps_ack_drain() { for version in ["moq-lite-05", "moq-lite-06"] { peer_close_reads_buffered_tail(version).await; } } -#[moq_clock::test] +#[kio::test] async fn earlier_lite_peer_close_reads_buffered_tail() { for version in ["moq-lite-01", "moq-lite-02", "moq-lite-03", "moq-lite-04"] { peer_close_reads_buffered_tail(version).await; } } -#[moq_clock::test] +#[kio::test] async fn ietf_peer_close_reads_buffered_tail() { for version in ["moq-transport-18", "moq-transport-22"] { peer_close_reads_buffered_tail(version).await; @@ -350,7 +350,7 @@ async fn peer_close_reads_buffered_tail(version: &str) { /// Legacy session/control streams and the accept error race the buffered group. /// Holding the whole receiver ensures the close is visible on its first poll. -#[moq_clock::test] +#[kio::test] async fn peer_close_before_receiver_poll_keeps_buffered_tail() { for version in [ "moq-lite-01", @@ -377,7 +377,7 @@ async fn peer_close_before_receiver_poll_keeps_buffered_tail() { } /// A locally unsupported feature uses only the negotiated session registry. -#[moq_clock::test] +#[kio::test] async fn unsupported_abort_uses_the_negotiated_session_registry() { for protocol in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { let version: Version = protocol.parse().unwrap(); @@ -390,7 +390,7 @@ async fn unsupported_abort_uses_the_negotiated_session_registry() { } /// A Lite-only close code arriving on IETF stays unknown instead of gaining Lite semantics. -#[moq_clock::test] +#[kio::test] async fn unsupported_close_is_decoded_by_the_negotiated_session_registry() { for protocol in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { let version: Version = protocol.parse().unwrap(); @@ -408,7 +408,7 @@ async fn unsupported_close_is_decoded_by_the_negotiated_session_registry() { /// moq-lite's own session range (0x30-0x3f) is never sent as an unknown code on either /// wire, while a code outside it passes through. -#[moq_clock::test] +#[kio::test] async fn an_unknown_lite_range_abort_is_unspecified_on_every_wire() { for protocol in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { for (unknown, expected) in [(0x31, 0x1), (0x20, 0x20)] { @@ -432,12 +432,12 @@ async fn ended(version: &str, close: impl FnOnce(&MockPair)) -> (Error, moq_net: .session(moq_net::Path::from_static("room")); let pair = connect_mock(options).await; close(&pair); - let err = moq_clock::timeout(TIMEOUT, pair.server.closed()) + let err = kio::clock::timeout(TIMEOUT, pair.server.closed()) .await .expect("the session closes"); drop(pair); // The drivers release the stats once the transport has closed under them. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let presence = registry.snapshot().sessions()[0].1; assert_eq!(presence.sessions_ended, 1, "{version}: the session ended"); (err, presence.sessions_failed) @@ -445,7 +445,7 @@ async fn ended(version: &str, close: impl FnOnce(&MockPair)) -> (Error, moq_net: /// A clean close is `Error::Cancel` and no failure, whichever side closed. Anything else /// counts by its kind, without the caller recording it. -#[moq_clock::test] +#[kio::test] async fn a_session_records_how_it_ended() { use moq_net::stats::Failures; for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { diff --git a/rs/moq-net/tests/integration/session_idle.rs b/rs/moq-net/tests/integration/session_idle.rs index 53123dec4ea..542d7bde485 100644 --- a/rs/moq-net/tests/integration/session_idle.rs +++ b/rs/moq-net/tests/integration/session_idle.rs @@ -49,7 +49,7 @@ async fn setup(version: &str) -> Setup { options.server_subscribe = Some(subscriber.clone()); let pair = connect_mock(options).await; - let remote = moq_clock::timeout(TIMEOUT, subscriber.consume().follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, subscriber.consume().follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -64,7 +64,7 @@ async fn setup(version: &str) -> Setup { /// An announcement alone leaves both ends idle. A subscription keeps the end serving it /// and the end holding it busy until the reader leaves. -#[moq_clock::test] +#[kio::test] async fn a_subscription_keeps_both_ends_busy() { for version in [ "moq-lite-04", @@ -88,11 +88,11 @@ async fn a_subscription_keeps_both_ends_busy() { let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, b"live".as_ref()).unwrap(); group.finish().unwrap(); - let mut sub = moq_clock::timeout(TIMEOUT, remote.track("video").unwrap().subscribe(None)) + let mut sub = kio::clock::timeout(TIMEOUT, remote.track("video").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); - let received = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let received = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv timeout") .expect("recv") @@ -102,17 +102,17 @@ async fn a_subscription_keeps_both_ends_busy() { assert!(!idle(&pair.server), "{version}: idle while holding a subscription"); drop((received, sub)); - moq_clock::timeout(TIMEOUT, pair.server.idle()) + kio::clock::timeout(TIMEOUT, pair.server.idle()) .await .unwrap_or_else(|_| panic!("{version}: the subscriber stayed busy after the reader left")); - moq_clock::timeout(TIMEOUT, pair.client.idle()) + kio::clock::timeout(TIMEOUT, pair.client.idle()) .await .unwrap_or_else(|_| panic!("{version}: the publisher stayed busy after the reader left")); } } /// A fetch keeps both ends busy until it ends: here, until the group it reads finishes. -#[moq_clock::test] +#[kio::test] async fn a_fetch_keeps_both_ends_busy() { for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let Setup { @@ -125,7 +125,7 @@ async fn a_fetch_keeps_both_ends_busy() { let mut writing = track.append_group().unwrap(); writing.write_frame(Timestamp::ZERO, b"first".as_ref()).unwrap(); let fetching = remote.track("video").unwrap(); - let fetch = moq_clock::sim::spawn(async move { + let fetch = kio::clock::sim::spawn(async move { let mut fetched = fetching.fetch_group(0, None).await?; let mut frames = Vec::new(); while let Some(frame) = fetched.read_frame().await? { @@ -134,22 +134,22 @@ async fn a_fetch_keeps_both_ends_busy() { Ok::<_, moq_net::Error>(frames) }); // Simulated: every task runs until the fetch waits on the unfinished group. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(!idle(&pair.client), "{version}: idle while serving a fetch"); assert!(!idle(&pair.server), "{version}: idle while a fetch is in flight"); writing.write_frame(Timestamp::ZERO, b"last".as_ref()).unwrap(); writing.finish().unwrap(); - let frames = moq_clock::timeout(TIMEOUT, fetch) + let frames = kio::clock::timeout(TIMEOUT, fetch) .await .expect("fetch timeout") .expect("fetch task") .expect("fetch"); assert_eq!(frames, [&b"first"[..], &b"last"[..]], "{version}"); - moq_clock::timeout(TIMEOUT, pair.server.idle()) + kio::clock::timeout(TIMEOUT, pair.server.idle()) .await .unwrap_or_else(|_| panic!("{version}: the fetching side stayed busy after the fetch")); - moq_clock::timeout(TIMEOUT, pair.client.idle()) + kio::clock::timeout(TIMEOUT, pair.client.idle()) .await .unwrap_or_else(|_| panic!("{version}: the serving side stayed busy after the fetch")); } diff --git a/rs/moq-net/tests/integration/session_panic.rs b/rs/moq-net/tests/integration/session_panic.rs index e2ca79092de..9f0f34dbec5 100644 --- a/rs/moq-net/tests/integration/session_panic.rs +++ b/rs/moq-net/tests/integration/session_panic.rs @@ -31,7 +31,7 @@ struct Publisher { client: Session, server: Session, server_transport: MockSession, - server_driver: moq_clock::sim::JoinHandle, + server_driver: kio::clock::sim::JoinHandle, /// The client's origin, which it publishes from. origin: origin::Producer, _broadcast: moq_net::origin::Publication, @@ -59,7 +59,7 @@ async fn publish(version: Version, relay: &origin::Producer, hop: u64, name: &st }; let server = async { let (session, mut driver) = server.accept(now(), server_transport.clone()).await.unwrap(); - let driver = moq_clock::sim::spawn(moq_clock::drive(move |now, waiter| { + let driver = kio::clock::sim::spawn(kio::clock::drive(move |now, waiter| { moq_net::time::Driver::poll(&mut driver, now, waiter) })); (session, driver) @@ -92,12 +92,12 @@ async fn until(announced: &mut announce::Consumer, path: &str, active: bool) { } } }; - moq_clock::timeout(TIMEOUT, wait) + kio::clock::timeout(TIMEOUT, wait) .await .unwrap_or_else(|_| panic!("{path} never became active={active}")); } -#[moq_clock::test] +#[kio::test] async fn a_panicking_session_leaves_the_others_serving() { for version in ["moq-lite-07-wip", "moq-transport-22"] { let version: Version = version.parse().unwrap(); @@ -111,7 +111,7 @@ async fn a_panicking_session_leaves_the_others_serving() { broken.server_transport.panic_on_stats(); let _ = broken.server.stats(); - let ended = moq_clock::timeout(TIMEOUT, broken.server_driver) + let ended = kio::clock::timeout(TIMEOUT, broken.server_driver) .await .expect("the driver never sampled the stats"); assert!( @@ -120,7 +120,7 @@ async fn a_panicking_session_leaves_the_others_serving() { ); until(&mut announced, "broken", false).await; - moq_clock::timeout(TIMEOUT, broken.server.closed()) + kio::clock::timeout(TIMEOUT, broken.server.closed()) .await .unwrap_or_else(|_| panic!("{version}: the panicked session never closed")); diff --git a/rs/moq-net/tests/integration/settled_end_survives_abort.rs b/rs/moq-net/tests/integration/settled_end_survives_abort.rs index 2938df38e66..05a1f0cf8ce 100644 --- a/rs/moq-net/tests/integration/settled_end_survives_abort.rs +++ b/rs/moq-net/tests/integration/settled_end_survives_abort.rs @@ -77,19 +77,19 @@ fn assert_whole((got, err): (Vec, Option), what: &str) { } /// The groups a settled track holds outlive an abort: a late reader gets all of them. -#[moq_clock::test] +#[kio::test] async fn an_abort_after_the_end_settled_keeps_the_groups_for_a_late_reader() { assert_whole(round(true, false).await, "arrival order, aborted after the end settled"); } /// The same in sequence order: the ordered cursor ends clean too, not with the abort. -#[moq_clock::test] +#[kio::test] async fn an_abort_after_the_end_settled_keeps_the_groups_for_a_late_ordered_reader() { assert_whole(round(true, true).await, "sequence order, aborted after the end settled"); } /// Control: with no abort the same late reader gets every group, then the clean end. -#[moq_clock::test] +#[kio::test] async fn a_settled_track_delivers_every_group_to_a_late_reader() { assert_whole(round(false, false).await, "arrival order, no abort"); assert_whole(round(false, true).await, "sequence order, no abort"); diff --git a/rs/moq-net/tests/integration/setup_negotiation.rs b/rs/moq-net/tests/integration/setup_negotiation.rs index 1ea725b1aec..48c7fffa682 100644 --- a/rs/moq-net/tests/integration/setup_negotiation.rs +++ b/rs/moq-net/tests/integration/setup_negotiation.rs @@ -45,7 +45,7 @@ async fn dial( ) } -#[moq_clock::test] +#[kio::test] async fn every_lite_version_negotiates_in_setup() { for name in [ "moq-lite-07-wip", @@ -70,7 +70,7 @@ async fn every_lite_version_negotiates_in_setup() { } } -#[moq_clock::test] +#[kio::test] async fn disjoint_versions_are_refused() { let (upstream, downstream) = (origin(), origin()); let (client, server) = dial( diff --git a/rs/moq-net/tests/integration/slow_joiner.rs b/rs/moq-net/tests/integration/slow_joiner.rs index 9397eec2961..7cb77328e7b 100644 --- a/rs/moq-net/tests/integration/slow_joiner.rs +++ b/rs/moq-net/tests/integration/slow_joiner.rs @@ -57,7 +57,7 @@ async fn stalled_read(version: Version, budget: Duration) -> BTreeSet { let remote = consumer.request("live", None).await.unwrap(); let subscription = track::Subscription::default().with_max_delay(budget); let mut reader = remote.track("audio").unwrap().subscribe(subscription).await.unwrap(); - moq_clock::timeout(TIMEOUT, subscribed(&source)).await.unwrap(); + kio::clock::timeout(TIMEOUT, subscribed(&source)).await.unwrap(); *gate.write().ok().unwrap() = false; for sequence in 0..GROUPS { @@ -66,14 +66,14 @@ async fn stalled_read(version: Version, budget: Duration) -> BTreeSet { .write_frame(Timestamp::from_millis(sequence * 1000).unwrap(), &b"x"[..]) .unwrap(); group.finish().unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } source.finish().unwrap(); *gate.write().ok().unwrap() = true; // Read until the track ends, so a skipped group can't be one that merely arrived late. let mut got = BTreeSet::new(); - while let Some(mut group) = moq_clock::timeout(TIMEOUT, reader.recv_group()) + while let Some(mut group) = kio::clock::timeout(TIMEOUT, reader.recv_group()) .await .unwrap_or_else(|_| panic!("{version}: the track never finished")) .unwrap() @@ -89,7 +89,7 @@ async fn stalled_read(version: Version, budget: Duration) -> BTreeSet { got } -#[moq_clock::test] +#[kio::test] async fn a_stalled_reader_keeps_every_group_its_budget_covers() { for version in VERSIONS { let version: Version = version.parse().unwrap(); @@ -100,7 +100,7 @@ async fn a_stalled_reader_keeps_every_group_its_budget_covers() { /// The stall backs up the relay: with a budget shorter than it, the groups that waited for /// credit past the budget are skipped. Group 0 took the one free credit as the stall began. -#[moq_clock::test] +#[kio::test] async fn a_budget_shorter_than_the_stall_skips_what_waited_past_it() { for version in VERSIONS { let version: Version = version.parse().unwrap(); diff --git a/rs/moq-net/tests/integration/source_errors.rs b/rs/moq-net/tests/integration/source_errors.rs index 9ba9f6824d0..5aecf07e94d 100644 --- a/rs/moq-net/tests/integration/source_errors.rs +++ b/rs/moq-net/tests/integration/source_errors.rs @@ -40,7 +40,7 @@ struct Relayed { async fn resolve(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Consumer { let consumer = origin.consume(); - moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves") @@ -101,20 +101,20 @@ fn assert_ended(result: Result<(), Error>, expected: StreamError, version: &str) /// #5347: a TRACK request is in flight to an upstream publisher session that dies before /// answering. The relay's request, and the far end's through it, find the path has no /// route; neither is an internal error. -#[moq_clock::test] +#[kio::test] async fn request_in_flight_to_a_dead_upstream_is_unroutable() { for version in VERSIONS { let setup = relayed(version).await; let _track = setup.broadcast.create_track("catalog", timed()).unwrap(); // The relay's requests never reach the publisher. setup.upstream.client_transport.hold_bidis(); - let relayed = moq_clock::sim::spawn(read_to_end(setup.relayed.clone(), "catalog")); - let remote = moq_clock::sim::spawn(read_to_end(setup.remote.clone(), "catalog")); - moq_clock::sleep(Duration::from_secs(1)).await; + let relayed = kio::clock::sim::spawn(read_to_end(setup.relayed.clone(), "catalog")); + let remote = kio::clock::sim::spawn(read_to_end(setup.remote.clone(), "catalog")); + kio::clock::sleep(Duration::from_secs(1)).await; assert!(!relayed.is_finished(), "{version}: answered through a held stream"); setup.upstream.server.abort(Error::Timeout); for reader in [relayed, remote] { - let result = moq_clock::timeout(TIMEOUT, reader) + let result = kio::clock::timeout(TIMEOUT, reader) .await .expect("request hung") .unwrap(); @@ -125,7 +125,7 @@ async fn request_in_flight_to_a_dead_upstream_is_unroutable() { /// A subscription already delivering when the upstream session dies, with nothing to /// replace it: the far end learns the path is gone, not that its own session closed. -#[moq_clock::test] +#[kio::test] async fn track_in_flight_through_a_dead_upstream_is_unroutable() { for version in VERSIONS { let setup = relayed(version).await; @@ -134,13 +134,13 @@ async fn track_in_flight_through_a_dead_upstream_is_unroutable() { let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, b"head".as_ref()).unwrap(); group.finish().unwrap(); - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() .unwrap(); setup.upstream.server.abort(Error::Timeout); - let result = moq_clock::timeout(TIMEOUT, async { + let result = kio::clock::timeout(TIMEOUT, async { while sub.recv_group().await?.is_some() {} Ok(()) }) @@ -153,7 +153,7 @@ async fn track_in_flight_through_a_dead_upstream_is_unroutable() { /// #4349: the broadcast is withdrawn under an active subscription, then its track fails /// with a specific error. The withdrawal does not disturb the subscription, which ends /// with that error. -#[moq_clock::test] +#[kio::test] async fn withdrawn_broadcast_keeps_the_source_error() { for version in VERSIONS { let setup = relayed(version).await; @@ -162,15 +162,15 @@ async fn withdrawn_broadcast_keeps_the_source_error() { let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, b"head".as_ref()).unwrap(); group.finish().unwrap(); - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() .unwrap(); setup.broadcast.unannounce(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; track.abort(Error::App(7)).unwrap(); - let result = moq_clock::timeout(TIMEOUT, async { + let result = kio::clock::timeout(TIMEOUT, async { while sub.recv_group().await?.is_some() {} Ok(()) }) @@ -181,15 +181,15 @@ async fn withdrawn_broadcast_keeps_the_source_error() { } /// A subscribe on a broadcast whose route was withdrawn is refused as unroutable. -#[moq_clock::test] +#[kio::test] async fn subscribe_after_withdrawal_is_unroutable() { for version in VERSIONS { let setup = relayed(version).await; let _track = setup.broadcast.create_track("video", timed()).unwrap(); setup.broadcast.unannounce(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; for broadcast in [setup.relayed.clone(), setup.remote.clone()] { - let result = moq_clock::timeout(TIMEOUT, read_to_end(broadcast, "video")) + let result = kio::clock::timeout(TIMEOUT, read_to_end(broadcast, "video")) .await .expect("subscribe hung"); assert_ended(result, StreamError::Unroutable, version); diff --git a/rs/moq-net/tests/integration/stream_credit.rs b/rs/moq-net/tests/integration/stream_credit.rs index fc89fadefd0..d51a3dd8d89 100644 --- a/rs/moq-net/tests/integration/stream_credit.rs +++ b/rs/moq-net/tests/integration/stream_credit.rs @@ -14,7 +14,7 @@ fn origin(hop: u64) -> origin::Producer { origin } -#[moq_clock::test] +#[kio::test] async fn one_stream_credit_serves_every_backlogged_group() { for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let version: Version = version.parse().unwrap(); @@ -59,7 +59,7 @@ async fn one_stream_credit_serves_every_backlogged_group() { // The transport, not the publisher, picks which parked open gets the next grant. let mut received = Vec::new(); while received.len() < 4 { - let group = moq_clock::timeout(Duration::from_secs(5), subscriber.recv_group()) + let group = kio::clock::timeout(Duration::from_secs(5), subscriber.recv_group()) .await .unwrap_or_else(|_| panic!("{version}: only {received:?} arrived")) .unwrap() diff --git a/rs/moq-net/tests/integration/subscribe_priority.rs b/rs/moq-net/tests/integration/subscribe_priority.rs index a972876700c..e71b5e77ade 100644 --- a/rs/moq-net/tests/integration/subscribe_priority.rs +++ b/rs/moq-net/tests/integration/subscribe_priority.rs @@ -27,7 +27,7 @@ fn produce_origin(hop: u64) -> origin::Producer { /// Wait until the subscription `track` serves asks for `want`. async fn priority(track: &moq_net::track::Producer, want: i8) -> Result<(), String> { let mut track = track.clone(); - let reached = moq_clock::timeout(TIMEOUT, async { + let reached = kio::clock::timeout(TIMEOUT, async { while track .subscription() .is_none_or(|subscription| subscription.priority != want) @@ -65,14 +65,14 @@ async fn follows(version: Version, relay: bool) -> Result<(), String> { } let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); let subscribe = |priority: i8| { let track = remote.track("video").unwrap(); async move { - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, track.subscribe(Subscription::default().with_priority(priority)), ) @@ -95,7 +95,7 @@ async fn follows(version: Version, relay: bool) -> Result<(), String> { Ok(()) } -#[moq_clock::test] +#[kio::test] async fn upstream_priority_follows_the_subscribers() { let mut failures = Vec::new(); for version in VERSIONS { diff --git a/rs/moq-net/tests/integration/subscribe_ranges.rs b/rs/moq-net/tests/integration/subscribe_ranges.rs index 494b14fb903..c33e815427b 100644 --- a/rs/moq-net/tests/integration/subscribe_ranges.rs +++ b/rs/moq-net/tests/integration/subscribe_ranges.rs @@ -32,7 +32,7 @@ fn write_group(track: &moq_net::track::Producer, sequence: u64) { /// The next group's sequence, or `None` once the track ends or nothing arrives in time. async fn next(sub: &mut moq_net::track::Subscriber) -> Option { - let group = moq_clock::timeout(TIMEOUT, sub.recv_group()).await.ok()?; + let group = kio::clock::timeout(TIMEOUT, sub.recv_group()).await.ok()?; group.expect("recv_group").map(|group| group.sequence) } @@ -91,7 +91,7 @@ async fn ahead_then_live(version: Option<&str>, relay: bool) -> (Vec, Vec, relay: bool) -> (Vec, Vec, relay: bool) -> (Vec, Vec Rang } /// Mixed fixed and live ranges retain history for both live and finished cached sources. -#[moq_clock::test] +#[kio::test] async fn initial_mixed_ranges_keep_the_absolute_history() { for version in ["moq-transport-18", "moq-transport-22"] { for relay in [false, true] { @@ -286,7 +286,7 @@ async fn initial_mixed_ranges_keep_the_absolute_history() { /// A widening fill crosses cached groups without replacing them or losing the groups /// after them. A later narrowing reaches the publisher and can be widened again. -#[moq_clock::test] +#[kio::test] async fn draft22_updates_both_bounds_across_cached_groups() { for relay in [false, true] { let mut fixture = range_fixture(relay).await; @@ -307,7 +307,7 @@ async fn draft22_updates_both_bounds_across_cached_groups() { got.sort_unstable(); assert_eq!(got, [0, 1, 4, 5], "relay={relay}"); reader.update(initial.clone().with_range(4..5)).unwrap(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, kio::wait(|waiter| { assert!( @@ -344,7 +344,7 @@ async fn draft22_updates_both_bounds_across_cached_groups() { } /// A warm copy resolves a time end before updating upstream; an unknown end is refused. -#[moq_clock::test] +#[kio::test] async fn draft22_resolves_cached_time_ends() { for relay in [false, true] { let mut fixture = range_fixture(relay).await; @@ -371,7 +371,7 @@ async fn draft22_resolves_cached_time_ends() { let mut got = vec![next(&mut reader).await.unwrap(), next(&mut reader).await.unwrap()]; got.sort_unstable(); assert_eq!(got, [0, 1], "relay={relay}"); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { if fixture .track @@ -399,7 +399,7 @@ async fn draft22_resolves_cached_time_ends() { /// A quiet current group does not hold its filled head while a later range update /// asks for older history; the subgroup header transfers ownership before any tail byte. -#[moq_clock::test] +#[kio::test] async fn draft22_can_widen_while_the_current_group_is_quiet() { for relay in [false, true] { let fixture = range_fixture(relay).await; @@ -411,14 +411,14 @@ async fn draft22_can_widen_while_the_current_group_is_quiet() { .write_frame(Timestamp::from_millis(6000).unwrap(), b"head".as_slice()) .unwrap(); let mut live = subscribe(&fixture.remote, Subscription::default().with_ranges([Range::live()])).await; - let mut current = moq_clock::timeout(TIMEOUT, live.recv_group()) + let mut current = kio::clock::timeout(TIMEOUT, live.recv_group()) .await .unwrap() .unwrap() .unwrap(); assert_eq!(current.sequence, 6); assert_eq!( - moq_clock::timeout(TIMEOUT, current.read_frame()) + kio::clock::timeout(TIMEOUT, current.read_frame()) .await .unwrap() .unwrap() @@ -436,7 +436,7 @@ async fn draft22_can_widen_while_the_current_group_is_quiet() { assert_eq!(got, [0, 1], "relay={relay}"); quiet.finish().unwrap(); assert!( - moq_clock::timeout(TIMEOUT, current.read_frame()) + kio::clock::timeout(TIMEOUT, current.read_frame()) .await .unwrap() .unwrap() @@ -447,7 +447,7 @@ async fn draft22_can_widen_while_the_current_group_is_quiet() { /// Draft-18 peers already join live and fetch the head. Their filters can narrow that /// established subscription and widen it over groups published meanwhile. -#[moq_clock::test] +#[kio::test] async fn draft18_updates_narrow_then_widen() { let version = "moq-transport-18"; for relay in [false, true] { @@ -461,7 +461,7 @@ async fn draft18_updates_narrow_then_widen() { seen.sort_unstable(); assert_eq!(seen, [5], "{version} relay={relay}"); reader.update(initial.clone().with_range(6..7)).unwrap(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, kio::wait(|waiter| { assert!(reader.poll_recv_group(waiter).is_pending()); @@ -494,20 +494,20 @@ async fn draft18_updates_narrow_then_widen() { reader.update(initial).unwrap(); let mut seen = Vec::new(); for _ in 0..2 { - let mut group = moq_clock::timeout(TIMEOUT, reader.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, reader.recv_group()) .await .unwrap_or_else(|_| panic!("{version} relay={relay}: widening lost history; got {seen:?}")) .unwrap() .unwrap(); seen.push(group.sequence); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap() .unwrap() .unwrap(); assert_eq!(frame.payload, group.sequence.to_be_bytes().as_slice()); assert!( - moq_clock::timeout(TIMEOUT, group.read_frame()) + kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap() .unwrap() @@ -521,7 +521,7 @@ async fn draft18_updates_narrow_then_widen() { /// Empty ranges retire only demand no other reader holds. A later widening reuses /// the copy and joins the new live group, without disturbing a sibling reader. -#[moq_clock::test] +#[kio::test] async fn empty_ranges_retire_the_wire_and_can_widen_again() { for version in ["moq-transport-18", "moq-transport-22"] { for relay in [false, true] { @@ -546,7 +546,7 @@ async fn empty_ranges_retire_the_wire_and_can_widen_again() { assert_eq!(next(&mut reader).await, Some(6)); drop(sibling); reader.update(live.clone().with_ranges([])).unwrap(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, kio::wait(|waiter| { assert!(reader.poll_recv_group(waiter).is_pending()); @@ -577,7 +577,7 @@ async fn empty_ranges_retire_the_wire_and_can_widen_again() { } /// A largest-group fill finishes its snapshot before the publisher produces another group. -#[moq_clock::test] +#[kio::test] async fn draft22_cold_widening_finishes_the_largest_group() { for relay in [false, true] { let mut fixture = range_fixture_history("moq-transport-22", relay, 0).await; @@ -586,7 +586,7 @@ async fn draft22_cold_widening_finishes_the_largest_group() { for start in [0, 1, 2] { let future = start + 1; reader.update(initial.clone().with_range(future..)).unwrap(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, kio::wait(|waiter| { assert!(reader.poll_recv_group(waiter).is_pending()); @@ -616,7 +616,7 @@ async fn draft22_cold_widening_finishes_the_largest_group() { reader.update(initial.clone().with_range(start..)).unwrap(); let mut sequences = Vec::new(); for _ in start..future { - let mut group = moq_clock::timeout(TIMEOUT, reader.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, reader.recv_group()) .await .unwrap_or_else(|_| { panic!("relay={relay}: a filled group from {start} did not arrive; got {sequences:?}") @@ -624,14 +624,14 @@ async fn draft22_cold_widening_finishes_the_largest_group() { .unwrap() .unwrap(); sequences.push(group.sequence); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap() .unwrap() .unwrap(); assert_eq!(frame.payload, group.sequence.to_be_bytes().as_slice()); assert!( - moq_clock::timeout(TIMEOUT, group.read_frame()) + kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("relay={relay}: group {} never finished", group.sequence)) .unwrap() @@ -645,7 +645,7 @@ async fn draft22_cold_widening_finishes_the_largest_group() { } /// A pending refusal is local to the new reader even before it is awaited. -#[moq_clock::test] +#[kio::test] async fn unresolved_time_reader_never_changes_sibling_demand() { for version in ["moq-transport-18", "moq-transport-22"] { for relay in [false, true] { @@ -653,7 +653,7 @@ async fn unresolved_time_reader_never_changes_sibling_demand() { let mut healthy = subscribe(&fixture.remote, Subscription::default()).await; assert_eq!(next(&mut healthy).await, Some(5)); healthy.update(Subscription::default().with_range(4..8)).unwrap(); - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, kio::wait(|waiter| { assert!(healthy.poll_recv_group(waiter).is_pending()); @@ -698,7 +698,7 @@ async fn unresolved_time_reader_never_changes_sibling_demand() { ) .unwrap(); group.finish().unwrap(); - let mut got = moq_clock::timeout(TIMEOUT, healthy.recv_group()) + let mut got = kio::clock::timeout(TIMEOUT, healthy.recv_group()) .await .unwrap() .unwrap_or_else(|err| panic!("{version} relay={relay}: pending refusal aborted sibling: {err:?}")) @@ -719,7 +719,7 @@ async fn unresolved_time_reader_never_changes_sibling_demand() { /// track does not end, the same range reads again from the cache, and a wider one /// subscribes again for the rest, past a group that never existed. Older versions park /// instead, since their subscriber reads a FIN as the track's end. -#[moq_clock::test] +#[kio::test] async fn a_covered_bounded_subscription_ends_on_lite07() { for version in LITE { let publisher = produce_origin(1); @@ -738,7 +738,7 @@ async fn a_covered_bounded_subscription_ends_on_lite07() { options.client_subscribe = Some(subscriber.clone()); let session = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -753,7 +753,7 @@ async fn a_covered_bounded_subscription_ends_on_lite07() { assert_eq!(next(&mut reader).await, Some(1), "{version}"); assert_eq!(next(&mut reader).await, Some(2), "{version}"); - let released = moq_clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())).await; + let released = kio::clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())).await; if *version != "moq-lite-07-wip" { assert!(released.is_err(), "{version}: the publisher parks"); drop((reader, track, session, subscriber, broadcast, publisher)); @@ -761,7 +761,7 @@ async fn a_covered_bounded_subscription_ends_on_lite07() { } released.expect("the covered subscription ends").unwrap(); assert!( - moq_clock::timeout(TIMEOUT, reader.finished()).await.is_err(), + kio::clock::timeout(TIMEOUT, reader.finished()).await.is_err(), "the track goes on" ); @@ -778,7 +778,7 @@ async fn a_covered_bounded_subscription_ends_on_lite07() { assert_eq!(got, [1, 2, 4, 5]); // Group 3 may still arrive on a live track, so it is dropped once the feed gives up // on it, past the arrivals grace. - moq_clock::timeout(Duration::from_secs(60), crate::support::unwanted(track.demand())) + kio::clock::timeout(Duration::from_secs(60), crate::support::unwanted(track.demand())) .await .expect("the wider subscription ends past the missing group") .unwrap(); diff --git a/rs/moq-net/tests/integration/subscribe_tracks.rs b/rs/moq-net/tests/integration/subscribe_tracks.rs index 1719df73de1..821c21b6f10 100644 --- a/rs/moq-net/tests/integration/subscribe_tracks.rs +++ b/rs/moq-net/tests/integration/subscribe_tracks.rs @@ -60,13 +60,13 @@ async fn setup(version: Version) -> Setup { let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); let (tx, frames) = futures::channel::mpsc::unbounded(); - moq_clock::sim::spawn(async move { + kio::clock::sim::spawn(async move { let mut sub = remote.track("video").unwrap().subscribe(None).await.expect("subscribe"); while let Ok(Some(mut group)) = sub.recv_group().await { while let Ok(Some(frame)) = group.read_frame().await { @@ -75,7 +75,7 @@ async fn setup(version: Version) -> Setup { } }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); @@ -92,7 +92,7 @@ async fn deliver(setup: &mut Setup, payload: &'static [u8]) { let mut group = setup.track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, payload).unwrap(); group.finish().unwrap(); - let got = moq_clock::timeout(TIMEOUT, setup.frames.next()) + let got = kio::clock::timeout(TIMEOUT, setup.frames.next()) .await .expect("frame timed out") .expect("the subscription ended"); @@ -111,7 +111,7 @@ async fn subscribe_tracks(pair: &MockPair) -> Vec { send.write(SUBSCRIBE_TRACKS).await.expect("write"); let mut reply = Vec::new(); - while let Some(chunk) = moq_clock::timeout(TIMEOUT, recv.read_chunk(usize::MAX)) + while let Some(chunk) = kio::clock::timeout(TIMEOUT, recv.read_chunk(usize::MAX)) .await .expect("reply timed out") .expect("read") @@ -123,7 +123,7 @@ async fn subscribe_tracks(pair: &MockPair) -> Vec { /// We list no tracks by PUBLISH, so a SUBSCRIBE_TRACKS gets NOT_SUPPORTED on its own /// stream, and the subscription already on the session keeps going. -#[moq_clock::test] +#[kio::test] async fn subscribe_tracks_is_refused_per_request() { for version in ["moq-transport-18", "moq-transport-20", "moq-transport-22"] { let mut setup = setup(version.parse().unwrap()).await; diff --git a/rs/moq-net/tests/integration/subscriber_max_age.rs b/rs/moq-net/tests/integration/subscriber_max_age.rs index a67328124ed..10393544d3a 100644 --- a/rs/moq-net/tests/integration/subscriber_max_age.rs +++ b/rs/moq-net/tests/integration/subscriber_max_age.rs @@ -15,7 +15,7 @@ fn origin(hop: u64) -> origin::Producer { } async fn budget(track: &mut track::Producer, millis: u64, version: Version) { - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { loop { if track .subscription() @@ -30,7 +30,7 @@ async fn budget(track: &mut track::Producer, millis: u64, version: Version) { .unwrap_or_else(|_| panic!("{version}: wanted {millis}ms, publisher has {:?}", track.subscription())); } -#[moq_clock::test] +#[kio::test] async fn relay_forwards_the_most_tolerant_subscriber_max_age() { for draft in [18, 22] { let version: Version = format!("moq-transport-{draft}").parse().unwrap(); @@ -65,7 +65,7 @@ async fn relay_forwards_the_most_tolerant_subscriber_max_age() { drop(tolerant); budget(&mut source, 10, version).await; // A quiet catalog survives far longer than the budget because it has no successor. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(snapshot.sequence, 0, "{version}"); assert_eq!( snapshot.read_frame().await.unwrap().unwrap().payload, diff --git a/rs/moq-net/tests/integration/subscription_end_integrity.rs b/rs/moq-net/tests/integration/subscription_end_integrity.rs index d98cb0f72f6..dcf562285b4 100644 --- a/rs/moq-net/tests/integration/subscription_end_integrity.rs +++ b/rs/moq-net/tests/integration/subscription_end_integrity.rs @@ -44,7 +44,7 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { /// Let the drivers run until nothing is runnable: under paused time an idle runtime /// auto-advances the clock, so this returns once every queued write has been sent. async fn settle() { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } fn expected() -> Vec> { @@ -67,7 +67,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { let MockPair { client, server, .. } = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -78,7 +78,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { let (drained_tx, drained_rx) = futures::channel::oneshot::channel(); let (go_tx, go_rx) = futures::channel::oneshot::channel::<()>(); - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = moq_net::track::Subscription::default().with_range(0..); let mut sub = remote .track("video") @@ -109,7 +109,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { } }); - moq_clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::wanted(track.demand())) .await .expect("no subscriber appeared") .unwrap(); @@ -119,7 +119,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { head.write_frame(Timestamp::ZERO, payload).unwrap(); } head.finish().unwrap(); - moq_clock::timeout(TIMEOUT, drained_rx) + kio::clock::timeout(TIMEOUT, drained_rx) .await .expect("the head group never arrived") .expect("reader gone"); @@ -148,7 +148,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { // merely slower than the network. settle().await; let _ = go_tx.send(()); - let result = moq_clock::timeout(TIMEOUT, reader) + let result = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); @@ -158,7 +158,7 @@ async fn round(drop_session: bool) -> (Vec>, Option) { /// The session closes with the final group in flight: the subscription ends with an /// error, or delivers every frame. -#[moq_clock::test] +#[kio::test] async fn a_subscription_cut_by_the_session_close_does_not_end_clean() { let (got, err) = round(true).await; assert!( @@ -174,7 +174,7 @@ async fn a_subscription_cut_by_the_session_close_does_not_end_clean() { } /// With the session kept alive the same track arrives whole and ends `Ok(None)`. -#[moq_clock::test] +#[kio::test] async fn a_finished_track_ends_clean_while_its_session_lives() { let (got, err) = round(false).await; assert!( @@ -232,7 +232,7 @@ async fn killed(version: &str, kill: Kill) -> (Option, Option (Option, Option| { @@ -335,7 +335,7 @@ async fn fetch_killed(version: &str, kill: Kill) -> moq_net::Error { .available() .await .expect("broadcast resolves"); - let mut fetching = moq_clock::sim::spawn(async move { remote.track("video").unwrap().fetch_group(0, None).await }); + let mut fetching = kio::clock::sim::spawn(async move { remote.track("video").unwrap().fetch_group(0, None).await }); let request = dynamic.requested_track().await.expect("the track request arrives"); let groups = request.requests(); @@ -357,11 +357,11 @@ async fn fetch_killed(version: &str, kill: Kill) -> moq_net::Error { } /// A FETCH cut off by a clean close ends as a cancelled session, whichever side closed. -#[moq_clock::test] +#[kio::test] async fn a_session_close_cancels_a_pending_fetch_from_either_side() { for version in ["moq-lite-05", "moq-lite-07-wip"] { for kill in [Kill::RemoteClose, Kill::LocalClose] { - let err = moq_clock::timeout(TIMEOUT, fetch_killed(version, kill)) + let err = kio::clock::timeout(TIMEOUT, fetch_killed(version, kill)) .await .unwrap_or_else(|_| panic!("{version}: the fetch never ended")); assert!( diff --git a/rs/moq-net/tests/integration/support/harness.rs b/rs/moq-net/tests/integration/support/harness.rs index 52cac7f185a..bcfb15d6d45 100644 --- a/rs/moq-net/tests/integration/support/harness.rs +++ b/rs/moq-net/tests/integration/support/harness.rs @@ -19,14 +19,14 @@ use super::mock::{MockSession, MockStats, create_mock_session_pair}; /// The current ambient instant. pub fn now() -> moq_net::time::Instant { - moq_clock::now() + kio::clock::now() } -/// Run a protocol driver in the background: on `moq-clock`'s sim in tests, on tokio in +/// Run a protocol driver in the background: on `kio::clock`'s sim in tests, on tokio in /// the benches. pub fn spawn(mut driver: D) { - match moq_clock::sim::is_running() { - true => drop(moq_clock::sim::spawn(moq_clock::drive(move |now, waiter| { + match kio::clock::sim::is_running() { + true => drop(kio::clock::sim::spawn(kio::clock::drive(move |now, waiter| { moq_net::time::Driver::poll(&mut driver, now, waiter) }))), false => drop(tokio::spawn(moq_net::time::run(driver))), diff --git a/rs/moq-net/tests/integration/support/mock.rs b/rs/moq-net/tests/integration/support/mock.rs index 1b96c550eae..6de72cea5b9 100644 --- a/rs/moq-net/tests/integration/support/mock.rs +++ b/rs/moq-net/tests/integration/support/mock.rs @@ -361,8 +361,8 @@ impl MockChunks { if self.landing != Some(arrival) { self.landing = Some(arrival); let waker = waiter.waker().clone(); - drop(moq_clock::sim::spawn(async move { - moq_clock::sleep_until(arrival).await; + drop(kio::clock::sim::spawn(async move { + kio::clock::sleep_until(arrival).await; waker.wake(); })); } @@ -386,8 +386,8 @@ impl MockChunks { poll::RecvStream::stop(&mut inner, code); return; } - drop(moq_clock::sim::spawn(async move { - moq_clock::sleep(latency).await; + drop(kio::clock::sim::spawn(async move { + kio::clock::sleep(latency).await; poll::RecvStream::stop(&mut inner, code); })); } diff --git a/rs/moq-net/tests/integration/synced.rs b/rs/moq-net/tests/integration/synced.rs index 679dc6b473b..e623627de9c 100644 --- a/rs/moq-net/tests/integration/synced.rs +++ b/rs/moq-net/tests/integration/synced.rs @@ -25,7 +25,7 @@ fn produce_origin(hop: u64) -> origin::Producer { async fn read_until_synced(announced: &mut announce::Consumer) -> BTreeSet { let mut seen = BTreeSet::new(); while !announced.poll_synced(&moq_net::kio::Waiter::noop()).is_ready() { - let event = moq_clock::timeout(SETTLE, announced.next()) + let event = kio::clock::timeout(SETTLE, announced.next()) .await .expect("synced in time") .expect("the cursor stays open"); @@ -68,7 +68,7 @@ fn both() -> BTreeSet { } /// Every version that marks the boundary syncs with the whole initial set. -#[moq_clock::test] +#[kio::test] async fn an_exact_boundary_catches_up_with_the_initial_set() { for version in [ "moq-lite-05", @@ -82,7 +82,7 @@ async fn an_exact_boundary_catches_up_with_the_initial_set() { } /// Versions without a boundary still sync, so nothing waiting on it hangs. -#[moq_clock::test] +#[kio::test] async fn a_best_effort_boundary_still_catches_up() { for version in ["moq-lite-03", "moq-lite-04"] { synced(version).await; @@ -91,7 +91,7 @@ async fn a_best_effort_boundary_still_catches_up() { /// A second session into the same origin, as a reconnect makes, syncs too: the /// consumer waits on every current session. -#[moq_clock::test] +#[kio::test] async fn a_second_session_catches_up() { let publisher = produce_origin(1); let a = publisher.create_broadcast("a").unwrap(); @@ -113,13 +113,13 @@ async fn a_second_session_catches_up() { let second = connect().await; drop(first); - moq_clock::sleep(SETTLE).await; + kio::clock::sleep(SETTLE).await; read_until_synced(&mut announced).await; drop(second); } /// A cold relay's empty set is complete before an upstream joins it. -#[moq_clock::test] +#[kio::test] async fn a_cold_relay_syncs_then_forwards_upstream_routes_as_live() { let relay = produce_origin(2); let subscriber = produce_origin(3); diff --git a/rs/moq-net/tests/integration/track_abort_over_session.rs b/rs/moq-net/tests/integration/track_abort_over_session.rs index b94dbd47d7f..f2bc00bc5e9 100644 --- a/rs/moq-net/tests/integration/track_abort_over_session.rs +++ b/rs/moq-net/tests/integration/track_abort_over_session.rs @@ -47,7 +47,7 @@ async fn after_abort(version: &str, hops: u32) { track.abort(moq_net::Error::Cancel).unwrap(); drop(open); assert!( - moq_clock::timeout(Duration::from_secs(2), group.read_frame()) + kio::clock::timeout(Duration::from_secs(2), group.read_frame()) .await .expect("group-only read hung") .is_err() @@ -56,7 +56,7 @@ async fn after_abort(version: &str, hops: u32) { macro_rules! abort_test { ($name:ident, $version:literal, $hops:literal) => { - #[moq_clock::test] + #[kio::test] async fn $name() { after_abort($version, $hops).await; } @@ -94,7 +94,7 @@ async fn recreate(finish: bool) { next.write_frame(Timestamp::from_millis(1).unwrap(), b"next".as_ref()) .unwrap(); drop(open); - let result = moq_clock::timeout(Duration::from_secs(2), async { + let result = kio::clock::timeout(Duration::from_secs(2), async { if finish { group.finished().await.map(|_| ()) } else { @@ -108,12 +108,12 @@ async fn recreate(finish: bool) { assert_eq!(next.sequence, 3); } -#[moq_clock::test] +#[kio::test] async fn recreated_track_skips_old_group() { recreate(false).await; } -#[moq_clock::test] +#[kio::test] async fn recreated_track_finishes_old_group() { recreate(true).await; } diff --git a/rs/moq-net/tests/integration/track_info_cancel.rs b/rs/moq-net/tests/integration/track_info_cancel.rs index 089b5df834d..5d68ab98e9f 100644 --- a/rs/moq-net/tests/integration/track_info_cancel.rs +++ b/rs/moq-net/tests/integration/track_info_cancel.rs @@ -33,7 +33,7 @@ async fn abandoned_request_reaches_the_publisher(version: &str, relays: u64) { let broadcast = nodes[0].create_broadcast("room").unwrap(); let mut dynamic = broadcast.requests(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let consumer = nodes[relays as usize].consume().request("room", None).await.unwrap(); let mut waiting = Box::pin(consumer.track("video").unwrap().subscribe(None)); @@ -44,20 +44,20 @@ async fn abandoned_request_reaches_the_publisher(version: &str, relays: u64) { // The publisher never answers; the reader gives up. drop(waiting); - moq_clock::timeout(Duration::from_secs(5), crate::support::unwanted(request.demand())) + kio::clock::timeout(Duration::from_secs(5), crate::support::unwanted(request.demand())) .await .unwrap_or_else(|_| panic!("{version:?} over {relays} relays: the publisher's request is still wanted")) .expect("the pending request is still open"); } -#[moq_clock::test] +#[kio::test] async fn abandoned_request_reaches_the_publisher_lite05() { for relays in [1, 2] { abandoned_request_reaches_the_publisher("moq-lite-05", relays).await; } } -#[moq_clock::test] +#[kio::test] async fn abandoned_request_reaches_the_publisher_lite06() { for relays in [1, 2] { abandoned_request_reaches_the_publisher("moq-lite-06", relays).await; @@ -105,7 +105,7 @@ async fn withdrawn_broadcast_releases_track_info(version: &str, answered: bool, }; let finished = pair.client_transport.finished_streams(); broadcast.close(); - moq_clock::timeout(Duration::from_secs(5), crate::support::unwanted(demand)) + kio::clock::timeout(Duration::from_secs(5), crate::support::unwanted(demand)) .await .unwrap_or_else(|_| panic!("{version}, answered={answered}, explicit={explicit}: TRACK outlived its broadcast")) .expect("the publisher still owns its track"); @@ -121,7 +121,7 @@ async fn withdrawn_broadcast_releases_track_info(version: &str, answered: bool, drop(query); } -#[moq_clock::test] +#[kio::test] async fn a_pending_track_info_ends_with_its_broadcast() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { for explicit in [false, true] { @@ -130,7 +130,7 @@ async fn a_pending_track_info_ends_with_its_broadcast() { } } -#[moq_clock::test] +#[kio::test] async fn an_answered_track_info_ends_with_its_broadcast() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { for explicit in [false, true] { diff --git a/rs/moq-net/tests/integration/track_stream_demand.rs b/rs/moq-net/tests/integration/track_stream_demand.rs index 167d876b39c..4af2c4c0143 100644 --- a/rs/moq-net/tests/integration/track_stream_demand.rs +++ b/rs/moq-net/tests/integration/track_stream_demand.rs @@ -50,7 +50,7 @@ macro_rules! record_track { let edges = Rc::new(RefCell::new(Vec::new())); let log = edges.clone(); let mut demand = $demand; - drop(moq_clock::sim::spawn(async move { + drop(kio::clock::sim::spawn(async move { let mut was = false; while let Ok(wanted) = demand.wanted_changed().await { if wanted.is_some() != was { @@ -88,13 +88,13 @@ async fn one_used_edge(version: &str, relays: usize, reorder: bool) { let requests = Rc::new(RefCell::new(Vec::new())); let track_edges = Rc::new(RefCell::new(None)); let served = (requests.clone(), track_edges.clone()); - let publisher = moq_clock::sim::spawn(async move { + let publisher = kio::clock::sim::spawn(async move { while let Ok(request) = dynamic.requested_track().await { served .1 .borrow_mut() .get_or_insert_with(|| record_track!(request.demand())); - moq_clock::sleep(STARTUP).await; + kio::clock::sleep(STARTUP).await; let track = request.accept(timed()); let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, b"key".as_ref()).unwrap(); @@ -108,19 +108,19 @@ async fn one_used_edge(version: &str, relays: usize, reorder: bool) { let subscribing = remote.track("video").unwrap().subscribe(None); if reorder { // The TRACK stream opens at once; the SUBSCRIBE only once TRACK_INFO is back. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; reader.hold_bidis(); } - let mut subscriber = moq_clock::timeout(TIMEOUT, subscribing) + let mut subscriber = kio::clock::timeout(TIMEOUT, subscribing) .await .unwrap_or_else(|_| panic!("{label}: subscribe stalled")) .unwrap_or_else(|err| panic!("{label}: subscribe failed: {err}")); if reorder { - moq_clock::sleep(LATENCY * 20).await; + kio::clock::sleep(LATENCY * 20).await; reader.release_bidis(); } - let mut received = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let mut received = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .unwrap_or_else(|_| panic!("{label}: no group arrived")) .unwrap() @@ -128,7 +128,7 @@ async fn one_used_edge(version: &str, relays: usize, reorder: bool) { received.read_frame().await.unwrap().expect("the group has a frame"); // Stay subscribed while every hop settles. - moq_clock::sleep(Duration::from_secs(2)).await; + kio::clock::sleep(Duration::from_secs(2)).await; assert_eq!(requests.borrow().len(), 1, "{label}: asked for the track again"); let track_edges = track_edges.borrow().clone().expect("the track was requested"); assert_eq!(*track_edges.borrow(), [true], "{label}: track demand"); @@ -137,16 +137,16 @@ async fn one_used_edge(version: &str, relays: usize, reorder: bool) { drop(received); drop(subscriber); let track = requests.borrow()[0].0.clone(); - moq_clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) .await .unwrap_or_else(|_| panic!("{label}: demand outlived the reader")) .unwrap(); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; assert_eq!(*track_edges.borrow(), [true, false], "{label}: track demand"); publisher.abort(); } -#[moq_clock::test] +#[kio::test] async fn direct() { for version in VERSIONS { one_used_edge(version, 0, false).await; @@ -154,7 +154,7 @@ async fn direct() { } } -#[moq_clock::test] +#[kio::test] async fn through_a_relay() { for version in VERSIONS { one_used_edge(version, 1, false).await; @@ -180,7 +180,7 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { broadcast.announce(Default::default()).unwrap(); let requests = Rc::new(RefCell::new(Vec::new())); let served = requests.clone(); - let publisher = moq_clock::sim::spawn(async move { + let publisher = kio::clock::sim::spawn(async move { while let Ok(request) = dynamic.requested_track().await { let track = request.accept(timed()); let mut group = track.append_group().unwrap(); @@ -193,7 +193,7 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { let remote = consumer.follow("room", None).unwrap().available().await.unwrap(); let handle = remote.track("video").unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!( requests.borrow().is_empty(), "{label}: a bare handle asked for the track" @@ -201,11 +201,11 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { // A held query reaches the publisher, and holds the track there until dropped. let mut query = handle.info(); - moq_clock::timeout(TIMEOUT, &mut query) + kio::clock::timeout(TIMEOUT, &mut query) .await .unwrap_or_else(|_| panic!("{label}: query stalled")) .unwrap_or_else(|err| panic!("{label}: query failed: {err}")); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!( requests.borrow().len(), 1, @@ -214,17 +214,17 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { let track = requests.borrow()[0].0.clone(); assert!(track.demand().wanted().is_some(), "{label}: a held query let go"); drop(query); - moq_clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) .await .unwrap_or_else(|_| panic!("{label}: a dropped query is still demand")) .unwrap(); // A subscription ending leaves the held handle unread at both ends. - let mut subscriber = moq_clock::timeout(TIMEOUT, handle.subscribe(None)) + let mut subscriber = kio::clock::timeout(TIMEOUT, handle.subscribe(None)) .await .unwrap_or_else(|_| panic!("{label}: subscribe stalled")) .unwrap_or_else(|err| panic!("{label}: subscribe failed: {err}")); - moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .unwrap_or_else(|_| panic!("{label}: no group arrived")) .unwrap() @@ -234,7 +234,7 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { "{label}: the subscription is not demand" ); drop(subscriber); - moq_clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::support::unwanted(track.demand())) .await .unwrap_or_else(|_| panic!("{label}: the publisher still reads the track as used")) .unwrap(); @@ -242,14 +242,14 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { publisher.abort(); } -#[moq_clock::test] +#[kio::test] async fn bare_handle_is_lazy_direct() { for version in VERSIONS { bare_handle_is_lazy(version, 0).await; } } -#[moq_clock::test] +#[kio::test] async fn bare_handle_is_lazy_through_a_relay() { for version in VERSIONS { bare_handle_is_lazy(version, 1).await; diff --git a/rs/moq-net/tests/integration/track_tail.rs b/rs/moq-net/tests/integration/track_tail.rs index 5603bc57f9a..238a1c46d76 100644 --- a/rs/moq-net/tests/integration/track_tail.rs +++ b/rs/moq-net/tests/integration/track_tail.rs @@ -86,7 +86,7 @@ async fn connect(version: &str) -> Pair { let pair = connect_mock(options).await; let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("bcast", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -110,7 +110,7 @@ async fn round(version: &str, late: Late, final_sequence: u64, max_delay: Option _keep, } = connect(version).await; - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = moq_net::track::Subscription::default() .with_range(0..) .with_max_delay(max_delay); @@ -135,17 +135,17 @@ async fn round(version: &str, late: Late, final_sequence: u64, max_delay: Option } } }; - (frames, err, moq_clock::now()) + (frames, err, kio::clock::now()) }); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); // Let the publisher answer while the track is still empty. Before draft 22, a group // written first sits below SUBSCRIBE_OK's Largest Object, so it would arrive as a // joining FETCH, which the track ending first refuses, not as the subscription's own // late stream. Paused time advances only once every task is idle. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; pair.server_transport.hold_unis(); if final_sequence > 0 { @@ -161,20 +161,20 @@ async fn round(version: &str, late: Late, final_sequence: u64, max_delay: Option if final_sequence > 0 { // Paused time advances only when every task is idle, after the publisher and // subscriber have processed the subscription's end. - moq_clock::sleep(GRACE / 10).await; + kio::clock::sleep(GRACE / 10).await; assert!( !reader.is_finished(), "{version}: the track ended before its group arrived" ); } - let released = moq_clock::now(); + let released = kio::clock::now(); match late { Late::Delivered => pair.server_transport.release_unis(), Late::Lost => pair.server_transport.drop_unis(), } - let (frames, err, ended) = moq_clock::timeout(TIMEOUT, reader) + let (frames, err, ended) = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); @@ -188,7 +188,7 @@ async fn round(version: &str, late: Late, final_sequence: u64, max_delay: Option /// A group whose header arrives after the subscription's end is delivered, then the track /// ends cleanly. An unbounded max delay waits for it too: its grace never runs out. -#[moq_clock::test] +#[kio::test] async fn a_group_after_the_end_is_delivered() { for version in VERSIONS { // moq-lite-03 declares no end, so an unbounded subscription there waits forever. @@ -220,7 +220,7 @@ async fn a_group_after_the_end_is_delivered() { /// A group that never arrives is given up on after the grace, and the track still ends /// cleanly without it. -#[moq_clock::test] +#[kio::test] async fn a_lost_group_ends_the_track_after_the_grace() { for version in VERSIONS { let outcome = round(version, Late::Lost, 1, Some(Duration::ZERO)).await; @@ -239,7 +239,7 @@ async fn a_lost_group_ends_the_track_after_the_grace() { } /// Skipped sequences have no stream, so lite-05+ publishers name them with SUBSCRIBE_DROP. -#[moq_clock::test] +#[kio::test] async fn skipped_groups_end_without_the_grace() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let outcome = round(version, Late::Delivered, 3, Some(Duration::ZERO)).await; @@ -254,7 +254,7 @@ async fn skipped_groups_end_without_the_grace() { } /// An empty track leaves no tail to wait for. -#[moq_clock::test] +#[kio::test] async fn lite07_empty_track_ends_without_the_grace() { let outcome = round("moq-lite-07-wip", Late::Delivered, 0, Some(Duration::ZERO)).await; assert!(outcome.err.is_none()); @@ -267,7 +267,7 @@ const IETF: &[&str] = &["moq-transport-18", "moq-transport-22"]; /// A subscriber that leaves while END_OF_TRACK waits for stream credit ends the publisher's /// request, instead of parking it until credit that may never come. -#[moq_clock::test] +#[kio::test] async fn ietf_leaving_cancels_a_blocked_end_of_track() { for version in IETF { let Pair { @@ -284,14 +284,14 @@ async fn ietf_leaving_cancels_a_blocked_end_of_track() { .subscribe(subscription) .await .expect("subscribe"); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); let mut group = track.append_group().unwrap(); group.write_frame(Timestamp::ZERO, PAYLOAD).unwrap(); group.finish().unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() @@ -301,7 +301,7 @@ async fn ietf_leaving_cancels_a_blocked_end_of_track() { // Out of stream credit, so the marker cannot open. pair.server_transport.withhold_unis(); track.finish().unwrap(); - moq_clock::sleep(GRACE / 10).await; + kio::clock::sleep(GRACE / 10).await; assert!( track.subscription().is_some(), "{version}: the publisher is still ending the request" @@ -309,9 +309,9 @@ async fn ietf_leaving_cancels_a_blocked_end_of_track() { // The request task holds the publisher's subscription until it ends. drop((group, sub)); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while track.subscription().is_some() { - moq_clock::sleep(GRACE / 100).await; + kio::clock::sleep(GRACE / 100).await; } }) .await @@ -322,7 +322,7 @@ async fn ietf_leaving_cancels_a_blocked_end_of_track() { /// A lost datagram is indistinguishable from a reordered stream header, so its hole /// waits out the tail grace on every lite version. -#[moq_clock::test] +#[kio::test] async fn a_lost_datagram_delays_the_end() { for version in ["moq-lite-05", "moq-lite-07-wip"] { let Pair { @@ -332,7 +332,7 @@ async fn a_lost_datagram_delays_the_end() { _keep, } = connect(version).await; - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = moq_net::track::Subscription::default().with_range(0..); let mut sub = remote .track("video") @@ -344,9 +344,9 @@ async fn a_lost_datagram_delays_the_end() { while let Some(group) = sub.recv_group().await.expect("track aborted") { groups.push(group.sequence); } - (groups, moq_clock::now()) + (groups, kio::clock::now()) }); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); @@ -359,12 +359,12 @@ async fn a_lost_datagram_delays_the_end() { group.write_frame(Timestamp::ZERO, PAYLOAD).unwrap(); group.finish().unwrap(); } - moq_clock::sleep(GRACE / 100).await; + kio::clock::sleep(GRACE / 100).await; } - let finished = moq_clock::now(); + let finished = kio::clock::now(); track.finish().unwrap(); - let (groups, ended) = moq_clock::timeout(TIMEOUT, reader) + let (groups, ended) = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); @@ -381,7 +381,7 @@ async fn a_lost_datagram_delays_the_end() { /// A publisher can declare the end, then open each group's stream before writing its first /// frame. The subscriber withholds a group until that frame lands, and the end waits for /// it: a reader that ended at the boundary would miss every group. -#[moq_clock::test] +#[kio::test] async fn a_group_whose_first_frame_trails_its_header_is_delivered() { for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let Pair { @@ -391,7 +391,7 @@ async fn a_group_whose_first_frame_trails_its_header_is_delivered() { _keep, } = connect(version).await; - let reader = moq_clock::sim::spawn(async move { + let reader = kio::clock::sim::spawn(async move { let subscription = moq_net::track::Subscription::default() .with_range(0..) .with_max_delay(TIMEOUT); @@ -409,7 +409,7 @@ async fn a_group_whose_first_frame_trails_its_header_is_delivered() { } groups }); - moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + kio::clock::timeout(TIMEOUT, support::harness::subscribed(&track)) .await .expect("no subscriber appeared"); @@ -417,7 +417,7 @@ async fn a_group_whose_first_frame_trails_its_header_is_delivered() { let mut groups = [track.append_group().unwrap(), track.append_group().unwrap()]; // Paused time advances only once every task is idle: both headers and the end // have reached the subscriber, ahead of any frame. - moq_clock::sleep(GRACE / 10).await; + kio::clock::sleep(GRACE / 10).await; assert!( !reader.is_finished(), "{version}: the track ended before its groups showed" @@ -427,7 +427,7 @@ async fn a_group_whose_first_frame_trails_its_header_is_delivered() { group.write_frame(Timestamp::ZERO, PAYLOAD).unwrap(); group.finish().unwrap(); } - let mut groups = moq_clock::timeout(TIMEOUT, reader) + let mut groups = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); diff --git a/rs/moq-net/tests/integration/tracks.rs b/rs/moq-net/tests/integration/tracks.rs index 365a4dd8ac8..1f1b34fa060 100644 --- a/rs/moq-net/tests/integration/tracks.rs +++ b/rs/moq-net/tests/integration/tracks.rs @@ -25,7 +25,7 @@ fn lite07() -> Version { /// The next event as `+name`, `-name`, `synced`, `end`, or `error: ..`. async fn next(tracks: &mut moq_net::broadcast::Tracks) -> String { - match moq_clock::timeout(TIMEOUT, tracks.next()) + match kio::clock::timeout(TIMEOUT, tracks.next()) .await .expect("listing stalled") { @@ -53,7 +53,7 @@ async fn connect( } async fn resolve(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Consumer { - moq_clock::timeout(TIMEOUT, origin.consume().follow("bcast", None).unwrap().available()) + kio::clock::timeout(TIMEOUT, origin.consume().follow("bcast", None).unwrap().available()) .await .expect("announce timeout") .expect("routed") @@ -61,7 +61,7 @@ async fn resolve(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Cons /// A session syncs at once, then lists the peer's tracks and their changes until the /// broadcast ends. -#[moq_clock::test] +#[kio::test] async fn a_session_lists_its_peers_tracks() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -91,7 +91,7 @@ async fn a_session_lists_its_peers_tracks() { } /// TRACKS_ADD carries the track's whole TRACK_INFO, Refresh included. -#[moq_clock::test] +#[kio::test] async fn a_listing_carries_track_info() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -107,7 +107,7 @@ async fn a_listing_carries_track_info() { let (subscriber, _pair) = connect(&publisher, 2, lite07()).await; let mut tracks = resolve(&subscriber).await.tracks().unwrap(); assert_eq!(next(&mut tracks).await, "synced"); - let event = moq_clock::timeout(TIMEOUT, tracks.next()) + let event = kio::clock::timeout(TIMEOUT, tracks.next()) .await .expect("listing stalled") .unwrap(); @@ -124,7 +124,7 @@ async fn a_listing_carries_track_info() { /// A listed track is a track like any other: a SUBSCRIBE from the listing reads the /// group it already holds from the cache. -#[moq_clock::test] +#[kio::test] async fn a_listed_track_serves_its_cached_group() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -141,11 +141,11 @@ async fn a_listed_track_serves_its_cached_group() { group.finish().unwrap(); assert_eq!(next(&mut tracks).await, "+late"); - let mut sub = moq_clock::timeout(TIMEOUT, remote.track("late").unwrap().subscribe(None)) + let mut sub = kio::clock::timeout(TIMEOUT, remote.track("late").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() @@ -157,7 +157,7 @@ async fn a_listed_track_serves_its_cached_group() { /// Through a relay: the relay answers each downstream listing at once from the one /// upstream listing it keeps, a cold relay's upstream tracks follow as live adds, and a /// removal reaches each downstream as its upstream reported it. -#[moq_clock::test] +#[kio::test] async fn a_relay_shares_its_upstream_listing() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -191,7 +191,7 @@ async fn a_relay_shares_its_upstream_listing() { } /// A version without the Tracks Stream refuses the listing rather than answer it empty. -#[moq_clock::test] +#[kio::test] async fn lite06_cannot_list() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -208,7 +208,7 @@ async fn lite06_cannot_list() { /// Each listed track counts against the session's `announces` cap: past it, the listing /// is reset rather than held, and the session stays. -#[moq_clock::test] +#[kio::test] async fn a_listing_past_the_announces_cap_is_reset() { let publisher = produce_origin(1); let broadcast = publisher.create_broadcast("bcast").unwrap(); @@ -242,7 +242,7 @@ async fn a_listing_past_the_announces_cap_is_reset() { assert_eq!(end, format!("error: {}", moq_net::Error::TooManyRequests)); assert!( - moq_clock::timeout(Duration::from_millis(100), pair.server.closed()) + kio::clock::timeout(Duration::from_millis(100), pair.server.closed()) .await .is_err(), "the session closed" diff --git a/rs/moq-net/tests/integration/tracks_ietf.rs b/rs/moq-net/tests/integration/tracks_ietf.rs index 188258f6193..6d437b3f8e8 100644 --- a/rs/moq-net/tests/integration/tracks_ietf.rs +++ b/rs/moq-net/tests/integration/tracks_ietf.rs @@ -34,7 +34,7 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { /// The next event as `+name`, `-name`, `synced`, `end`, or `error: ..`. async fn next(tracks: &mut moq_net::broadcast::Tracks) -> String { - match moq_clock::timeout(TIMEOUT, tracks.next()) + match kio::clock::timeout(TIMEOUT, tracks.next()) .await .expect("listing stalled") { @@ -58,7 +58,7 @@ async fn connect(publisher: &moq_net::origin::Producer, version: &str) -> (moq_n } async fn resolve(origin: &moq_net::origin::Producer, path: &str) -> moq_net::broadcast::Consumer { - moq_clock::timeout(TIMEOUT, origin.consume().follow(path, None).unwrap().available()) + kio::clock::timeout(TIMEOUT, origin.consume().follow(path, None).unwrap().available()) .await .expect("announce timeout") .expect("routed") @@ -80,11 +80,11 @@ fn subscribes(pair: &MockPair) -> usize { /// Read one frame of the next group, or `None` once the subscription ends. async fn read(sub: &mut moq_net::track::Subscriber) -> Option<(u64, Vec)> { - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .ok()??; - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("frame timeout") .ok()??; @@ -94,7 +94,7 @@ async fn read(sub: &mut moq_net::track::Subscriber) -> Option<(u64, Vec)> { /// SUBSCRIBE_TRACKS goes out only for a listing, since many peers do not answer it: /// connecting, an announce, and a reader's SUBSCRIBE send none. Our own publisher refuses /// it, which fails only that listing, and the SUBSCRIBE keeps delivering. -#[moq_clock::test] +#[kio::test] async fn a_listing_of_our_own_peer_fails_alone() { for version in DRAFTS { let publisher = produce_origin(1); @@ -104,11 +104,11 @@ async fn a_listing_of_our_own_peer_fails_alone() { let (subscriber, pair) = connect(&publisher, version).await; let remote = resolve(&subscriber, "bcast").await; - let mut sub = moq_clock::timeout(TIMEOUT, remote.track("video").unwrap().subscribe(None)) + let mut sub = kio::clock::timeout(TIMEOUT, remote.track("video").unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe"); - moq_clock::timeout(TIMEOUT, support::wanted(video.demand())) + kio::clock::timeout(TIMEOUT, support::wanted(video.demand())) .await .expect("never subscribed") .unwrap(); diff --git a/rs/moq-net/tests/integration/unannounce_release.rs b/rs/moq-net/tests/integration/unannounce_release.rs index e982824b905..bd660de8e49 100644 --- a/rs/moq-net/tests/integration/unannounce_release.rs +++ b/rs/moq-net/tests/integration/unannounce_release.rs @@ -38,17 +38,17 @@ async fn release(version: Version) { crate::support::wanted(track.demand()).await.unwrap(); broadcast.unannounce(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; drop(sub); drop(remote); - moq_clock::timeout(Duration::from_secs(600), crate::support::unwanted(track.demand())) + kio::clock::timeout(Duration::from_secs(600), crate::support::unwanted(track.demand())) .await .unwrap_or_else(|_| panic!("{version}: the relay kept its upstream subscription")) .unwrap(); } -#[moq_clock::test] +#[kio::test] async fn unannounced_remote_track_releases_demand() { for version in support::every_version() { release(version).await; diff --git a/rs/moq-net/tests/integration/untimed.rs b/rs/moq-net/tests/integration/untimed.rs index e49141cb56e..2cf8e5d08a5 100644 --- a/rs/moq-net/tests/integration/untimed.rs +++ b/rs/moq-net/tests/integration/untimed.rs @@ -81,11 +81,11 @@ impl Chain { async fn subscribe(&self, track: &str) -> track::Subscriber { let consumer = self.nodes.last().unwrap().consume(); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("room", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("room", None)) .await .expect("resolve timeout") .expect("broadcast resolves"); - moq_clock::timeout(TIMEOUT, broadcast.track(track).unwrap().subscribe(None)) + kio::clock::timeout(TIMEOUT, broadcast.track(track).unwrap().subscribe(None)) .await .expect("subscribe timeout") .expect("subscribe") @@ -94,7 +94,7 @@ impl Chain { /// The first frame's timestamp of the next group. async fn next_frame(subscriber: &mut track::Subscriber) -> Option { - let mut group = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .expect("group timeout") .unwrap() @@ -110,7 +110,7 @@ async fn frame_through(hops: &[&str], info: track::Info) -> (Option, let broadcast = chain.nodes[0].create_broadcast("room").unwrap(); let mut producer = broadcast.create_track("data", info).unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let mut subscriber = chain.subscribe("data").await; producer.write_frame(timestamp, &b"frame"[..]).unwrap(); @@ -119,7 +119,7 @@ async fn frame_through(hops: &[&str], info: track::Info) -> (Option, (received, subscriber.info().clone()) } -#[moq_clock::test] +#[kio::test] async fn frames_arrive_as_published() { for version in VERSIONS { let (timed, timed_info) = frame_through(&[version], timed()).await; @@ -141,7 +141,7 @@ async fn frames_arrive_as_published() { /// A relay forwards an untimed track untimed, and a track it received without a timeline /// does not gain one downstream. -#[moq_clock::test] +#[kio::test] async fn a_relay_forwards_an_untimed_track_untimed() { for hops in [ &["moq-transport-18", "moq-transport-22"][..], @@ -164,7 +164,7 @@ async fn a_relay_forwards_an_untimed_track_untimed() { /// The subscription asks for history the way a resume does, with a budget covering it. /// moq-transport before draft 22 can only join a past group through a joining FETCH, /// which our publisher refuses for groups before the live one, so draft 22 stands in for it. -#[moq_clock::test] +#[kio::test] async fn an_explicit_start_holds_on_an_untimed_track() { for version in ["moq-lite-03", "moq-lite-06", "moq-lite-07-wip", "moq-transport-22"] { let chain = Chain::new(&[version]).await; @@ -174,20 +174,20 @@ async fn an_explicit_start_holds_on_an_untimed_track() { for _ in 0..5 { producer.write_frame(None, &b"untimed"[..]).unwrap(); } - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let consumer = chain.nodes[1].consume().request("room", None).await.unwrap(); let subscription = track::Subscription::default() .with_range(2..) .with_max_delay(Duration::from_secs(30)); - let mut subscriber = moq_clock::timeout(TIMEOUT, consumer.track("data").unwrap().subscribe(subscription)) + let mut subscriber = kio::clock::timeout(TIMEOUT, consumer.track("data").unwrap().subscribe(subscription)) .await .expect("subscribe timeout") .expect("subscribe"); let mut got = Vec::new(); while got.len() < 3 { - let Ok(next) = moq_clock::timeout(TIMEOUT, subscriber.recv_group()).await else { + let Ok(next) = kio::clock::timeout(TIMEOUT, subscriber.recv_group()).await else { break; }; got.push(next.unwrap().expect("a group").sequence); @@ -199,14 +199,14 @@ async fn an_explicit_start_holds_on_an_untimed_track() { /// An untimed track's datagram arrives untimed, though lite-05 and lite-06 carry a send /// time that the receiver drops. -#[moq_clock::test] +#[kio::test] async fn datagrams_arrive_as_published() { for version in ["moq-lite-05", "moq-lite-07-wip", "moq-transport-22"] { let chain = Chain::new(&[version]).await; let broadcast = chain.nodes[0].create_broadcast("room").unwrap(); let mut producer = broadcast.create_track("data", untimed()).unwrap(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let mut subscriber = chain.subscribe("data").await; // A group first, so the subscription is bound before any datagram lands. @@ -214,7 +214,7 @@ async fn datagrams_arrive_as_published() { next_frame(&mut subscriber).await; producer.append_datagram(None, &b"untimed"[..]).unwrap(); - let datagram = moq_clock::timeout(TIMEOUT, subscriber.recv_datagram()) + let datagram = kio::clock::timeout(TIMEOUT, subscriber.recv_datagram()) .await .expect("datagram timeout") .unwrap() @@ -224,14 +224,14 @@ async fn datagrams_arrive_as_published() { } /// A standalone FETCH of an untimed track answers with untimed objects. -#[moq_clock::test] +#[kio::test] async fn a_fetched_untimed_frame_arrives_untimed() { for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18"] { let chain = Chain::new(&[version]).await; let broadcast = chain.nodes[0].create_broadcast("room").unwrap(); let mut dynamic = broadcast.requests(); broadcast.announce(Default::default()).unwrap(); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let consumer = chain.nodes[1].consume().request("room", None).await.unwrap(); let mut waiting = Box::pin(consumer.track("video").unwrap().fetch_group(0, None)); diff --git a/rs/moq-net/tests/integration/warm_backfill.rs b/rs/moq-net/tests/integration/warm_backfill.rs index 63f282064bd..4d3bc725e74 100644 --- a/rs/moq-net/tests/integration/warm_backfill.rs +++ b/rs/moq-net/tests/integration/warm_backfill.rs @@ -47,14 +47,14 @@ async fn subscribe(relay: &origin::Producer) -> track::Subscriber { /// Every group `subscriber` receives until it goes quiet. async fn received(subscriber: &mut track::Subscriber) -> BTreeSet { let mut got = BTreeSet::new(); - while let Ok(group) = moq_clock::timeout(Duration::from_secs(1), subscriber.recv_group()).await { + while let Ok(group) = kio::clock::timeout(Duration::from_secs(1), subscriber.recv_group()).await { let group = group.unwrap().expect("the track is live"); assert!(got.insert(group.sequence), "group {} delivered twice", group.sequence); } got } -#[moq_clock::test] +#[kio::test] async fn a_newcomer_on_a_warm_relay_gets_the_backfill() { for &version in VERSIONS { let publisher = origin(1); @@ -73,19 +73,19 @@ async fn a_newcomer_on_a_warm_relay_gets_the_backfill() { } broadcast.announce(Default::default()).unwrap(); - let mut first = moq_clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); - let cold = moq_clock::timeout(TIMEOUT, received(&mut first)).await.unwrap(); + let mut first = kio::clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); + let cold = kio::clock::timeout(TIMEOUT, received(&mut first)).await.unwrap(); assert_eq!(cold, (0..GROUPS).collect(), "{version}: cold"); // The same subscription changes nothing upstream, so only the cache can serve it. - let mut second = moq_clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); - let warm = moq_clock::timeout(TIMEOUT, received(&mut second)).await.unwrap(); + let mut second = kio::clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); + let warm = kio::clock::timeout(TIMEOUT, received(&mut second)).await.unwrap(); assert_eq!(warm, cold, "{version}: warm"); } } /// A refused history fill or FETCH never ends its live subscription. -#[moq_clock::test] +#[kio::test] async fn a_refused_transport_backfill_keeps_delivering_live() { for version in ["moq-transport-18", "moq-transport-22"] { let publisher = origin(1); @@ -103,15 +103,15 @@ async fn a_refused_transport_backfill_keeps_delivering_live() { group.finish().unwrap(); } broadcast.announce(Default::default()).unwrap(); - let mut subscriber = moq_clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); - let got = moq_clock::timeout(TIMEOUT, received(&mut subscriber)).await.unwrap(); + let mut subscriber = kio::clock::timeout(TIMEOUT, subscribe(&relay)).await.unwrap(); + let got = kio::clock::timeout(TIMEOUT, received(&mut subscriber)).await.unwrap(); assert_eq!(got, BTreeSet::from([GROUPS - 1]), "{version}: only the live edge"); let mut group = source.create_group(GROUPS.into()).unwrap(); group .write_frame(Timestamp::from_millis(GROUPS * 1000).unwrap(), &b"live"[..]) .unwrap(); group.finish().unwrap(); - let got = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let got = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .unwrap() .unwrap() diff --git a/rs/moq-net/tests/integration/wide_hop.rs b/rs/moq-net/tests/integration/wide_hop.rs index 43eb0e30e0c..ed449b3eb19 100644 --- a/rs/moq-net/tests/integration/wide_hop.rs +++ b/rs/moq-net/tests/integration/wide_hop.rs @@ -19,7 +19,7 @@ fn produce(hop: u64) -> origin::Producer { /// A draft-18 peer declaring `u64::MAX` keeps its session and its place in the path. /// Forwarded on, the hop survives lite-07's leading-ones varint and becomes 0 on /// lite-06's QUIC varint, while the relay's own hop still follows it. -#[moq_clock::test] +#[kio::test] async fn widest_hop_crosses_each_varint_form() { for (downstream, forwarded) in [("moq-lite-06", Hop::UNKNOWN.id()), ("moq-lite-07-wip", u64::MAX)] { let source = produce(u64::MAX); @@ -29,7 +29,7 @@ async fn widest_hop_crosses_each_varint_form() { let _upstream = peer(upstream, &source, &relay).await; let _downstream = peer(downstream.parse().unwrap(), &relay, &sink).await; let _route = source.requests("room").unwrap(); - moq_clock::sim::idle().await; + kio::clock::sim::idle().await; let ids = |route: origin::Route| route.hops.iter().map(|hop| hop.id()).collect::>(); let at_relay = crate::support::announced(&relay.consume(), "room").await; diff --git a/rs/moq-net/tests/integration/wide_sequence.rs b/rs/moq-net/tests/integration/wide_sequence.rs index 8fcca1083bc..730498cf4ec 100644 --- a/rs/moq-net/tests/integration/wide_sequence.rs +++ b/rs/moq-net/tests/integration/wide_sequence.rs @@ -11,7 +11,7 @@ use support::harness::{MockConnectOptions, connect_mock}; /// Published QUIC-varint sequences keep all their bits on the live feed, directly /// and through a forwarding origin, even beyond JavaScript's exact number range. -#[moq_clock::test] +#[kio::test] async fn largest_quic_sequence_reaches_the_subscriber() { for alpn in ["moq-lite-02", "moq-lite-06", "moq-transport-18"] { for relayed in [false, true] { @@ -49,7 +49,7 @@ async fn largest_quic_sequence_reaches_the_subscriber() { let mut group = track.create_group(moq_net::group::Info { sequence }).unwrap(); group.write_frame(timestamp, b"ladder".as_ref()).unwrap(); group.finish().unwrap(); - let mut got = moq_clock::timeout(Duration::from_secs(5), sub.recv_group()) + let mut got = kio::clock::timeout(Duration::from_secs(5), sub.recv_group()) .await .unwrap_or_else(|_| panic!("{alpn} relayed={relayed} sequence={sequence} hung")) .unwrap() @@ -78,7 +78,7 @@ fn produce_origin(hop: u64) -> moq_net::origin::Producer { /// The relay accepts the wide sequence from lite-07, refuses that subscription to the /// lite-06 reader that cannot encode it, and keeps the session serving other tracks. -#[moq_clock::test] +#[kio::test] async fn wide_sequence_fails_only_its_subscription() { const WIDE: u64 = 1 << 62; @@ -118,7 +118,7 @@ async fn wide_sequence_fails_only_its_subscription() { let consumer = client.consume(); let remote = consumer.follow("bench", None).unwrap().available().await.unwrap(); - let result = moq_clock::timeout(Duration::from_secs(5), async { + let result = kio::clock::timeout(Duration::from_secs(5), async { let mut sub = remote.track("wide").unwrap().subscribe(None).await?; sub.recv_group().await.map(|group| group.map(|group| group.sequence)) }) @@ -138,7 +138,7 @@ async fn wide_sequence_fails_only_its_subscription() { /// A subscription that starts inside the QUIC range and later receives a group of /// `1 << 62` fails only that subscription. The session and the other track continue. -#[moq_clock::test] +#[kio::test] async fn a_later_wide_group_fails_only_that_subscription() { const WIDE: u64 = 1 << 62; @@ -175,7 +175,7 @@ async fn a_later_wide_group_fails_only_that_subscription() { let mut group = wide.create_group(moq_net::group::Info { sequence: WIDE }).unwrap(); group.write_frame(Timestamp::ZERO, b"wide".as_ref()).unwrap(); - let result = moq_clock::timeout(Duration::from_secs(5), sub.recv_group()) + let result = kio::clock::timeout(Duration::from_secs(5), sub.recv_group()) .await .expect("the wide group hung the subscription instead of failing it"); match result { diff --git a/rs/moq-net/tests/integration/widened_max_age.rs b/rs/moq-net/tests/integration/widened_max_age.rs index b2df58aaa21..64667869119 100644 --- a/rs/moq-net/tests/integration/widened_max_age.rs +++ b/rs/moq-net/tests/integration/widened_max_age.rs @@ -107,7 +107,7 @@ impl Chain { /// Every group `subscriber` receives until it goes quiet. async fn received(subscriber: &mut track::Subscriber) -> BTreeSet { let mut got = BTreeSet::new(); - while let Ok(group) = moq_clock::timeout(Duration::from_secs(1), subscriber.recv_group()).await { + while let Ok(group) = kio::clock::timeout(Duration::from_secs(1), subscriber.recv_group()).await { let group = group.unwrap().expect("the track is live"); assert!(got.insert(group.sequence), "group {} delivered twice", group.sequence); } @@ -117,7 +117,7 @@ async fn received(subscriber: &mut track::Subscriber) -> BTreeSet { /// A fresh reader asks no fill for the history below where its feed starts, through a relay /// or not: below a start resolved from a budget no tighter than its own, every group is /// stale, and below a live edge start it names no floor under, none was asked for. -#[moq_clock::test] +#[kio::test] async fn a_fresh_reader_fills_nothing_below_its_start() { for (version, want) in [ ("moq-lite-04", 6..GROUPS), @@ -130,8 +130,8 @@ async fn a_fresh_reader_fills_nothing_below_its_start() { ] { for relay in [false, true] { let chain = Chain::new(version, relay).await; - let mut reader = moq_clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); - let got = moq_clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); + let mut reader = kio::clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); + let got = kio::clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); assert_eq!(got, want.clone().collect(), "{version} relay={relay}"); if version.starts_with("moq-lite") { assert_eq!(chain.fetches(), 0, "{version} relay={relay}: fetched below the start"); @@ -141,20 +141,20 @@ async fn a_fresh_reader_fills_nothing_below_its_start() { } /// What the subscriber reads after widening its own max age, through a relay or not. -#[moq_clock::test] +#[kio::test] async fn a_widened_reader_gets_what_was_skipped() { for &version in VERSIONS { for relay in [false, true] { let chain = Chain::new(version, relay).await; - let mut reader = moq_clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); - let first = moq_clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); + let mut reader = kio::clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); + let first = kio::clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); assert_eq!(first, (6..GROUPS).collect(), "{version} relay={relay}"); let wide = Subscription::default() .with_max_delay(WIDE) .with_ranges([Range::oldest()]); reader.update(wide).unwrap(); - let widened = moq_clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); + let widened = kio::clock::timeout(TIMEOUT, received(&mut reader)).await.unwrap(); assert_eq!( widened, (2..6).collect(), @@ -164,17 +164,17 @@ async fn a_widened_reader_gets_what_was_skipped() { } } -#[moq_clock::test] +#[kio::test] async fn a_warm_relay_serves_a_wider_newcomer_what_a_cold_one_would() { for &version in VERSIONS { let cold = Chain::new(version, true).await; - let mut wide = moq_clock::timeout(TIMEOUT, cold.subscribe(WIDE)).await.unwrap(); - let want = moq_clock::timeout(TIMEOUT, received(&mut wide)).await.unwrap(); + let mut wide = kio::clock::timeout(TIMEOUT, cold.subscribe(WIDE)).await.unwrap(); + let want = kio::clock::timeout(TIMEOUT, received(&mut wide)).await.unwrap(); assert_eq!(want, (2..GROUPS).collect(), "{version}: cold"); let warm = Chain::new(version, true).await; - let mut narrow = moq_clock::timeout(TIMEOUT, warm.subscribe(NARROW)).await.unwrap(); - let first = moq_clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); + let mut narrow = kio::clock::timeout(TIMEOUT, warm.subscribe(NARROW)).await.unwrap(); + let first = kio::clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); assert_eq!( first, (6..GROUPS).collect(), @@ -183,12 +183,12 @@ async fn a_warm_relay_serves_a_wider_newcomer_what_a_cold_one_would() { // The widened max age lowers the start the publisher resolved, and its re-offer // serves what lies between. - let mut wide = moq_clock::timeout(TIMEOUT, warm.subscribe(WIDE)).await.unwrap(); - let got = moq_clock::timeout(TIMEOUT, received(&mut wide)).await.unwrap(); + let mut wide = kio::clock::timeout(TIMEOUT, warm.subscribe(WIDE)).await.unwrap(); + let got = kio::clock::timeout(TIMEOUT, received(&mut wide)).await.unwrap(); assert_eq!(got, want, "{version}: warm"); // A lite-06 copy has no media time to find the re-offer stale by, and each group in // it arrives just now, so the narrow reader takes it too, once per widening. - let late = moq_clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); + let late = kio::clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); let reoffered = match version { "moq-lite-06" => (2..6).collect(), _ => BTreeSet::new(), @@ -198,22 +198,22 @@ async fn a_warm_relay_serves_a_wider_newcomer_what_a_cold_one_would() { } /// A reader joining with the max age the relay already asks for changes nothing upstream. -#[moq_clock::test] +#[kio::test] async fn the_same_max_age_sends_no_update() { let mut chain = Chain::new(VERSION, true).await; - let mut narrow = moq_clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); - moq_clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); - while moq_clock::timeout(Duration::from_secs(1), chain.source.subscription_changed()) + let mut narrow = kio::clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); + kio::clock::timeout(TIMEOUT, received(&mut narrow)).await.unwrap(); + while kio::clock::timeout(Duration::from_secs(1), chain.source.subscription_changed()) .await .is_ok() {} - let mut same = moq_clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); + let mut same = kio::clock::timeout(TIMEOUT, chain.subscribe(NARROW)).await.unwrap(); assert_eq!( - moq_clock::timeout(TIMEOUT, received(&mut same)).await.unwrap(), + kio::clock::timeout(TIMEOUT, received(&mut same)).await.unwrap(), (6..GROUPS).collect() ); - let changed = moq_clock::timeout(Duration::from_secs(1), chain.source.subscription_changed()).await; + let changed = kio::clock::timeout(Duration::from_secs(1), chain.source.subscription_changed()).await; assert!(changed.is_err(), "the publisher saw {changed:?}"); } @@ -230,7 +230,7 @@ fn sent_groups(registry: &moq_net::stats::Registry) -> u64 { /// Only the newcomer that widens the relay's max age pulls a re-offer upstream; the ones /// after it are served from what the relay cached, however many there are. -#[moq_clock::test] +#[kio::test] async fn wider_newcomers_after_the_first_pull_nothing_upstream() { let version: Version = VERSION.parse().unwrap(); let publisher = origin(1); @@ -274,13 +274,13 @@ async fn wider_newcomers_after_the_first_pull_nothing_upstream() { readers.push((viewer, reader)); got }; - let narrow = moq_clock::timeout(TIMEOUT, join(NARROW)).await.unwrap(); + let narrow = kio::clock::timeout(TIMEOUT, join(NARROW)).await.unwrap(); assert_eq!(narrow, (6..GROUPS).collect()); - let wide = moq_clock::timeout(TIMEOUT, join(WIDE)).await.unwrap(); + let wide = kio::clock::timeout(TIMEOUT, join(WIDE)).await.unwrap(); assert_eq!(wide, (2..GROUPS).collect()); let widened = sent_groups(®istry); for newcomer in 0..3 { - let got = moq_clock::timeout(TIMEOUT, join(WIDE)).await.unwrap(); + let got = kio::clock::timeout(TIMEOUT, join(WIDE)).await.unwrap(); assert_eq!(got, wide, "newcomer {newcomer}"); } assert_eq!(sent_groups(®istry), widened, "later newcomers pull nothing upstream"); diff --git a/rs/moq-net/tests/integration/zero_copy.rs b/rs/moq-net/tests/integration/zero_copy.rs index 34732f0e9e6..b1780917af4 100644 --- a/rs/moq-net/tests/integration/zero_copy.rs +++ b/rs/moq-net/tests/integration/zero_copy.rs @@ -22,7 +22,7 @@ fn produce_origin(hop: u64) -> origin::Producer { producer } -#[moq_clock::test] +#[kio::test] async fn frames_cross_without_a_copy() { for version in VERSIONS { let version: Version = version.parse().unwrap(); @@ -59,7 +59,7 @@ async fn frames_cross_without_a_copy() { broadcast.announce(Default::default()).unwrap(); let consumer = subscriber.consume(); - let remote = moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves"); @@ -71,7 +71,7 @@ async fn frames_cross_without_a_copy() { group.write_frame(Timestamp::ZERO, payload.clone()).unwrap(); group.finish().unwrap(); - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timeout") .unwrap() diff --git a/rs/moq-quic/Cargo.toml b/rs/moq-quic/Cargo.toml index 38f7beb8a2e..31853618bf7 100644 --- a/rs/moq-quic/Cargo.toml +++ b/rs/moq-quic/Cargo.toml @@ -41,11 +41,10 @@ aws-lc-rs = { version = "1.9", default-features = false, optional = true } bytes = { workspace = true } fastbloom = { version = "0.17", default-features = false } indexmap = { workspace = true } -# The waiter every `poll_*` wait registers, owned by the caller. +# The waiter every `poll_*` wait registers, owned by the caller, and the clock +# without the runtime, which is meant for dev-dependencies; a driver brings its own. kio = { workspace = true } lru-slab = "0.1.2" -# Without the runtime, which is meant for dev-dependencies; a driver brings its own. -moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false } moq-congestion = { workspace = true } qlog = { version = "0.18", optional = true } rand = { workspace = true } @@ -64,7 +63,7 @@ cpu-time = "1.0.0" criterion = { package = "bench-harness", path = "../bench-harness" } hex-literal = "1" # The tests and benches read time through the runtime, as the drivers do. -moq-clock = { path = "../moq-clock", features = ["sim"] } +kio = { path = "../kio", features = ["runtime", "sim"] } # The tests seed BBR3's probe phases. moq-congestion = { workspace = true, features = ["testing"] } # The mux module's tests run in the default merge gate. diff --git a/rs/moq-quic/MIGRATE.md b/rs/moq-quic/MIGRATE.md index 11a13e91236..e48541053a2 100644 --- a/rs/moq-quic/MIGRATE.md +++ b/rs/moq-quic/MIGRATE.md @@ -24,7 +24,7 @@ Nothing public decodes a `VarInt` or the other former `Codec` types (`StreamId`, Packet parsers and headers, `HashedConnectionIdGenerator` (with `set_lifetime`), `BloomTokenLog`, `TokenMemoryCache`, token policy traits (`TokenLog`, `TokenStore`, and `TokenReuseError`), `NoneTokenLog`, `NoneTokenStore`, `ClientConfig::token_store`, and `ValidationTokenConfig::log` are internal. Use `Endpoint` to parse incoming datagrams, `RandomConnectionIdGenerator` or a consumer's `ConnectionIdGenerator`, and the default token policy. -`TimeSource`, `StdSystemTime`, and `ServerConfig::time_source` are gone; address validation uses `moq_clock::wall()`, including an installed simulated clock. +`TimeSource`, `StdSystemTime`, and `ServerConfig::time_source` are gone; address validation uses `kio::clock::wall()`, including an installed simulated clock. Unused `Connection::local_ip`, `min_rtt`, `has_pending_retransmits`, `ping`, `force_key_update`, `path_changed`, and `max_concurrent_streams` accessors are no longer public. `Endpoint::set_server_config`, `incoming_buffer_bytes`, and `Incoming::orig_dst_cid` are also internal or removed; configure the endpoint at construction. To rotate TLS certificates on a running endpoint, give the `ServerConfig`'s rustls config a `ResolvesServerCert` that returns the current certificate, as moq-tokio's `tls::Serve` does. diff --git a/rs/moq-quic/README.md b/rs/moq-quic/README.md index 1a2822b39a5..0fcebe1fd53 100644 --- a/rs/moq-quic/README.md +++ b/rs/moq-quic/README.md @@ -65,7 +65,7 @@ Changes on top of the upstream commit, besides the renames: - **Probes on the peer heard again**: a 1-RTT probe that times out with nothing heard from the peer since the packet it probes for went out lets the next packet heard send the next probe at once, rather than leave a path back from an outage idle for the rest of the backoff, which still doubles with each probe (RFC 9002 section 6.2.1), up to 2^16 times its base. A packet acknowledging anything new already resets the backoff; this covers one that does not, as after an outage that began with everything acknowledged. A peer heard while the probes still go unanswered says nothing of their path, so it leaves the backoff alone. Not offered upstream yet. - `transport::Config::handshake_timeout` (default 10s, as msquic's `HandshakeIdleTimeoutMs`) governs the idle timer until the handshake completes, and the negotiated idle timeout takes over once established. A 2s idle timeout otherwise expires 3x the initial PTO in, just before the second Initial probe, leaving a client two flights. A server also drops an Initial left waiting for `accept` past it, and a deadline too far out to represent never fires instead of panicking. Also [moq-dev/noq#34](https://github.com/moq-dev/noq/pull/34), whose third change (the handshake idle timeout picks noq's idle-based PTO interval cap) has nothing to apply to here, since quinn's PTO backoff has no such cap. quinn's `handshake_timeout` test in its async layer expects the handshake to end at the idle timeout, so the driver's copy sets both timeouts. -- **Time on [moq-clock](../moq-clock)**: the crate's `Instant` is `moq_clock::Instant`, so one clock steps every timer, tokio's paused clock and the simulator included. qlog stamps events relative to `QlogConfig::start_time` on that clock rather than the streamer's own `std::time::Instant`. Address-validation tokens and their log read `moq_clock::wall()` instead of quinn's `TimeSource`, for portable 1970-2554 wall times; the simulator steps wall time with its clock, but paused tokio does not, so token expiry there follows the host's wall clock. +- **Time on [`kio::clock`](../kio)**: the crate's `Instant` is `kio::clock::Instant`, so one clock steps every timer, tokio's paused clock and the simulator included. qlog stamps events relative to `QlogConfig::start_time` on that clock rather than the streamer's own `std::time::Instant`. Address-validation tokens and their log read `kio::clock::wall()` instead of quinn's `TimeSource`, for portable 1970-2554 wall times; the simulator steps wall time with its clock, but paused tokio does not, so token expiry there follows the host's wall clock. - **Send groups** (`streams/schedule.rs`, `Connection::send_groups`): streams outside every group go first, in quinn's order; groups are served strictly by priority, with equal priorities sharing bytes by deficit round robin. A stream's priority is an `i64` ordering it only within its group, and `Streams::open` takes a `send::Options { group, priority }` to start it there, like W3C WebTransport's send options. This replaces quinn's single pending-stream heap, so a port touching `PendingStreamsQueue` has to be redone against the schedule. moq-tokio's `quic::driver` and moq-uring's driver wrap a group in a shared `send::Group` handle that closes on drop. - **Scheduled datagrams** (`Datagrams::send`): a datagram is queued by its `send::Options`, in a send group (or ungrouped) at an `i64` priority, and scheduled with the group's streams, winning a tie with a stream of equal priority and spending the group's byte credit, instead of quinn's datagram-first FIFO in `populate_packet`. Sending never blocks: `datagram_send_buffer_size` is shared, and an overflow evicts the oldest datagram of the lowest-priority group. `SendDatagramError::Blocked` and `Event::DatagramsUnblocked` are gone, and a port touching the `// DATAGRAM` loop has to be redone against `StreamsState::write_frames`. - **Sharded connection IDs** (`RandomConnectionIdGenerator::set_shard`): every CID names shard `index` of a `count`-endpoint group in its first byte, modulo `count`, and sets a marker in its fourth byte, so a `SO_REUSEPORT` steering filter delivers a packet to the endpoint that issued its CID. `validate` refuses a CID without this shard's prefix and marker, so a misrouted packet is dropped instead of answered with a stateless reset. Not offered upstream; it serves moq-sock's per-core sharding. diff --git a/rs/moq-quic/benches/common/mod.rs b/rs/moq-quic/benches/common/mod.rs index 87868c1329b..0f4c7f3b4a7 100644 --- a/rs/moq-quic/benches/common/mod.rs +++ b/rs/moq-quic/benches/common/mod.rs @@ -22,7 +22,7 @@ use criterion::{ Criterion, measurement::{Measurement, ValueFormatter, WallTime}, }; -use moq_clock::Instant; +use kio::clock::Instant; use moq_congestion::{Ack, Ce, Controller, ControllerFactory, ControllerMetrics, Init, Loss, Packet, Sent}; use moq_quic::{ ConnectionId, ConnectionIdGenerator, Event, RandomConnectionIdGenerator, StreamEvent, VarInt, client, diff --git a/rs/moq-quic/src/config/transport/qlog.rs b/rs/moq-quic/src/config/transport/qlog.rs index 4663a60bf5e..9b3e951310c 100644 --- a/rs/moq-quic/src/config/transport/qlog.rs +++ b/rs/moq-quic/src/config/transport/qlog.rs @@ -46,7 +46,7 @@ impl Config { let mut streamer = QlogStreamer::new( self.title, self.description, - moq_clock::now().into_std(), + kio::clock::now().into_std(), trace, qlog::events::EventImportance::Core, // `Instant` should have sub-microsecond precision on most platforms diff --git a/rs/moq-quic/src/connection/mod.rs b/rs/moq-quic/src/connection/mod.rs index ccb699437b4..642786f7d83 100644 --- a/rs/moq-quic/src/connection/mod.rs +++ b/rs/moq-quic/src/connection/mod.rs @@ -3588,7 +3588,7 @@ impl Connection { let token = Token::new( TokenPayload::Validation { ip: remote_addr.ip(), - issued: moq_clock::wall(), + issued: kio::clock::wall(), }, &mut self.rng, ); diff --git a/rs/moq-quic/src/endpoint.rs b/rs/moq-quic/src/endpoint.rs index 3eb6781a695..818673aeefb 100644 --- a/rs/moq-quic/src/endpoint.rs +++ b/rs/moq-quic/src/endpoint.rs @@ -817,7 +817,7 @@ impl Endpoint { let payload = TokenPayload::Retry { address: incoming.addresses.remote, orig_dst_cid: incoming.packet.header.dst_cid, - issued: moq_clock::wall(), + issued: kio::clock::wall(), }; let token = Token::new(payload, &mut self.rng).encode(&*server_config.token_key); diff --git a/rs/moq-quic/src/lib.rs b/rs/moq-quic/src/lib.rs index ad6cd94fa8a..681ec51159b 100644 --- a/rs/moq-quic/src/lib.rs +++ b/rs/moq-quic/src/lib.rs @@ -1,7 +1,7 @@ //! Low-level protocol logic for the QUIC protocol //! //! moq-quic has no networking code: the caller supplies transport timestamps, and address -//! validation reads the ambient `moq-clock` wall time. Most applications use the Tokio driver +//! validation reads the ambient `kio::clock` wall time. Most applications use the Tokio driver //! in `moq_tokio::quic::driver` instead. //! //! Use `moq_tokio::quic::driver` for Tokio, or drive this state machine from another runtime. @@ -89,7 +89,7 @@ use token_memory_cache::TokenMemoryCache; // Deal with time // MoQ's clock, so a caller-driven clock (a test's or the simulator's) reaches the state machine. -pub(crate) use moq_clock::{Instant, Wall}; +pub(crate) use kio::clock::{Instant, Wall}; pub(crate) use std::time::Duration; pub(crate) const UNIX_EPOCH: Wall = Wall::UNIX_EPOCH; diff --git a/rs/moq-quic/src/tests/token.rs b/rs/moq-quic/src/tests/token.rs index 34e30a61da2..c184ec5c5ba 100644 --- a/rs/moq-quic/src/tests/token.rs +++ b/rs/moq-quic/src/tests/token.rs @@ -150,7 +150,7 @@ fn stateless_retry() { assert_eq!(pair.server.known_cids(), 0); } -#[moq_clock::test] +#[kio::test] async fn retry_token_expired() { let _guard = subscribe(); @@ -169,7 +169,7 @@ async fn retry_token_expired() { pair.drive_client(); // to expire retry token - moq_clock::sleep(retry_token_lifetime + Duration::from_millis(1)).await; + kio::clock::sleep(retry_token_lifetime + Duration::from_millis(1)).await; pair.drive(); assert_matches!( @@ -373,7 +373,7 @@ fn use_same_token_twice() { assert_eq!(pair.server.known_cids(), 0); } -#[moq_clock::test] +#[kio::test] async fn use_token_expired() { let _guard = subscribe(); let lifetime = Duration::from_secs(10000); @@ -410,7 +410,7 @@ async fn use_token_expired() { assert_eq!(pair.server.known_connections(), 0); assert_eq!(pair.server.known_cids(), 0); - moq_clock::sleep(lifetime + Duration::from_secs(1)).await; + kio::clock::sleep(lifetime + Duration::from_secs(1)).await; pair.server.handle_incoming = Box::new(|incoming| { assert!(!incoming.remote_address_validated()); diff --git a/rs/moq-quic/src/token.rs b/rs/moq-quic/src/token.rs index b0ecf647abe..d88fb7e8167 100644 --- a/rs/moq-quic/src/token.rs +++ b/rs/moq-quic/src/token.rs @@ -142,7 +142,7 @@ impl IncomingToken { } if issued .checked_add(server_config.retry_token_lifetime) - .is_none_or(|expires| expires < moq_clock::wall()) + .is_none_or(|expires| expires < kio::clock::wall()) { return Err(InvalidRetryTokenError); } @@ -159,7 +159,7 @@ impl IncomingToken { } if issued .checked_add(server_config.validation_token.lifetime) - .is_none_or(|expires| expires < moq_clock::wall()) + .is_none_or(|expires| expires < kio::clock::wall()) { return Ok(unvalidated); } diff --git a/rs/moq-relay/Cargo.toml b/rs/moq-relay/Cargo.toml index e7c2da7957b..6686a771484 100644 --- a/rs/moq-relay/Cargo.toml +++ b/rs/moq-relay/Cargo.toml @@ -69,8 +69,8 @@ http-body = "1.0.1" http-cache-reqwest = { version = "1.0.0-alpha.6", features = ["manager-moka", "reqwest-middleware", "url-standard"], default-features = false } humantime = { workspace = true } hyper-util = { workspace = true } +kio = { workspace = true, features = ["runtime", "serde"] } moq-auth = { workspace = true, features = ["client"] } -moq-clock = { workspace = true, features = ["serde"] } moq-net = { workspace = true } # The flow-control limits both QUIC runtimes take, for widening a peer's connection. moq-quic = { workspace = true } @@ -109,10 +109,9 @@ sd-notify = { workspace = true } criterion = { package = "bench-harness", path = "../bench-harness" } # An HTTP/2 client, so the admission bench can hold many requests on one connection. h2 = { workspace = true } -kio = { path = "../kio" } -moq-auth = { path = "../moq-auth", features = ["client", "serve"] } # Clocks only the test moves, wall time included, so a grant's life is exact. -moq-clock = { path = "../moq-clock", features = ["manual", "sim"] } +kio = { path = "../kio", features = ["manual", "sim"] } +moq-auth = { path = "../moq-auth", features = ["client", "serve"] } moq-congestion = { path = "../moq-congestion" } # The shared session bench fills FETCH runs through the hidden `fuzz` module. moq-net = { path = "../moq-net", features = ["fuzz"] } diff --git a/rs/moq-relay/src/acme/client.rs b/rs/moq-relay/src/acme/client.rs index 31a857f09ac..aafdf9c6fa0 100644 --- a/rs/moq-relay/src/acme/client.rs +++ b/rs/moq-relay/src/acme/client.rs @@ -5,7 +5,7 @@ //! that resolver to every TLS listener, so QUIC, HTTPS, and every worker serve //! the same certificate and pick up a renewal on their next handshake. -use moq_clock::Wall; +use kio::clock::Wall; use std::{ io, net::SocketAddr, @@ -161,8 +161,8 @@ impl Acme { let health = moq_tokio::accept::Health::new("acme"); // Readiness waits on issuance, so keep extending systemd's start timeout // rather than letting the unit's default kill the relay inside the budget. - let mut extend = moq_clock::interval(EXTEND_INTERVAL); - let deadline = moq_clock::sleep(self.timeout); + let mut extend = kio::clock::interval(EXTEND_INTERVAL); + let deadline = kio::clock::sleep(self.timeout); tokio::pin!(deadline); let mut last = None; let mut issued = false; @@ -211,13 +211,13 @@ impl Acme { let handshake = challenge.accept(stream); // The validator only needs the handshake, then closes. handshakes.spawn(async move { - let _ = moq_clock::timeout(CHALLENGE_TIMEOUT, handshake).await; + let _ = kio::clock::timeout(CHALLENGE_TIMEOUT, handshake).await; }); } } Err(err) => { if let Some(pause) = health.failed(&err) { - moq_clock::sleep(pause).await; + kio::clock::sleep(pause).await; } } }, @@ -265,7 +265,7 @@ async fn renew( // An unknown budget counts as spent, rather than risk the directory's limit. Err(err) => { tracing::error!(err = format!("{err:#}"), %domains, "failed to read the ACME failure record"); - Some(moq_clock::wall().saturating_add(FAILURE_WINDOW)) + Some(kio::clock::wall().saturating_add(FAILURE_WINDOW)) } }; if let Some(resume) = resume { @@ -274,7 +274,7 @@ async fn renew( resume = %humantime::format_rfc3339_seconds(resume.into()), "ACME renewal paused after {FAILURE_LIMIT} failed validations within the hour, short of the directory's limit; still serving the previous certificate" ); - moq_clock::sleep(resume.saturating_duration_since(moq_clock::wall())).await; + kio::clock::sleep(resume.saturating_duration_since(kio::clock::wall())).await; continue; } @@ -298,7 +298,7 @@ async fn renew( // Unrecorded, it would never count, so assume the budget is spent. Err(record) => { tracing::error!(%err, record = format!("{record:#}"), %domains, "ACME renewal validation failed and could not be recorded; pausing renewal for an hour"); - moq_clock::sleep(FAILURE_WINDOW).await; + kio::clock::sleep(FAILURE_WINDOW).await; } } } @@ -335,7 +335,7 @@ impl Failures { let Some(contents) = Cache::read(&self.path)? else { return Ok(Vec::new()); }; - let cutoff = moq_clock::wall() + let cutoff = kio::clock::wall() .checked_sub(FAILURE_WINDOW) .unwrap_or(Wall::UNIX_EPOCH); let mut recent = Vec::new(); @@ -357,7 +357,7 @@ impl Failures { /// Record a failure now, returning the recent ones including it. fn record(&self) -> anyhow::Result> { let mut recent = self.recent()?; - recent.push(moq_clock::wall()); + recent.push(kio::clock::wall()); let lines: String = recent .iter() .map(|at| format!("{}\n", at.saturating_duration_since(Wall::UNIX_EPOCH).as_secs())) @@ -377,7 +377,7 @@ impl Failures { fn refuse(&self, failed: &[Wall], domains: &str, addr: SocketAddr, last: Option<&str>) -> anyhow::Error { let retry = failed .first() - .map_or(Some(moq_clock::wall()), |oldest| oldest.checked_add(FAILURE_WINDOW)) + .map_or(Some(kio::clock::wall()), |oldest| oldest.checked_add(FAILURE_WINDOW)) .map(|retry| humantime::format_rfc3339_seconds(retry.into()).to_string()) .unwrap_or_else(|| "the supported wall-time range".to_string()); let last = last.map(|last| format!("; last error: {last}")).unwrap_or_default(); diff --git a/rs/moq-relay/src/acme/tests.rs b/rs/moq-relay/src/acme/tests.rs index 43cbed360a0..4bac1b68347 100644 --- a/rs/moq-relay/src/acme/tests.rs +++ b/rs/moq-relay/src/acme/tests.rs @@ -128,7 +128,7 @@ impl Directory { #[cfg(all(target_os = "linux", feature = "_quic"))] async fn wait_issued(&self, count: usize) -> Vec> { let mut issued = self.state.issued.subscribe(); - moq_clock::timeout(TIMEOUT, issued.wait_for(|issued| issued.len() >= count)) + kio::clock::timeout(TIMEOUT, issued.wait_for(|issued| issued.len() >= count)) .await .expect("the directory never issued") .unwrap() @@ -390,7 +390,7 @@ impl Running { let ready = relay.ready(); let trigger = relay.shutdown_trigger().clone(); let task = tokio::spawn(relay.run()); - moq_clock::timeout(TIMEOUT, ready.wait()) + kio::clock::timeout(TIMEOUT, ready.wait()) .await .expect("the relay never became ready") .unwrap(); @@ -428,9 +428,9 @@ impl Running { /// Wait for HTTPS to serve `leaf`, which deploys just after the directory hands it out. #[cfg(all(target_os = "linux", feature = "_quic"))] async fn wait_served(&self, directory: &Directory, leaf: &CertificateDer<'static>) { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while self.served(directory, DOMAIN).await != *leaf { - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } }) .await @@ -444,7 +444,7 @@ impl Running { config.bind = Some("127.0.0.1:0".parse().unwrap()); let client = config.init(Default::default()).unwrap().with_reconnect(false); let url: Url = format!("moql://127.0.0.1:{}/", self.quic.port()).parse().unwrap(); - let _session = moq_clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) + let _session = kio::clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) .await .expect("QUIC connect timed out") .expect("QUIC must serve the same certificate as HTTPS"); @@ -557,8 +557,8 @@ async fn unreachable_directory_fails_inside_the_budget() { let relay = Relay::load(config).await.unwrap().with_signals(false); let https = relay.web_addrs().https.unwrap(); let ready = relay.ready(); - let started = moq_clock::now(); - let err = moq_clock::timeout(TIMEOUT, relay.run()) + let started = kio::clock::now(); + let err = kio::clock::timeout(TIMEOUT, relay.run()) .await .expect("the budget must bound the first issuance") .expect_err("no certificate means no relay"); @@ -591,7 +591,7 @@ async fn a_signal_during_issuance_stops_startup() { // Nothing awaits before issuance, so one poll leaves `run` waiting on it. assert!(futures::FutureExt::now_or_never(run.as_mut()).is_none()); crate::shutdown::raise(libc::SIGTERM).await; - let started = moq_clock::now(); + let started = kio::clock::now(); run.await.expect("a stop during issuance is not a failure"); assert_eq!(started.elapsed(), Duration::ZERO, "waited out the issuance"); assert!(ready.wait().await.is_err(), "reported ready without a certificate"); @@ -610,7 +610,7 @@ async fn failed_validations_stop_short_of_the_rate_limit() { let mut config = relay_config(&directory.url, dir.path(), &[DOMAIN]); config.acme.timeout = Some((TIMEOUT).into()); let relay = Relay::load(config).await.unwrap().with_signals(false); - let err = moq_clock::timeout(TIMEOUT, relay.run()) + let err = kio::clock::timeout(TIMEOUT, relay.run()) .await .expect("failed validations must end startup before the budget") .expect_err("no certificate means no relay"); @@ -668,7 +668,7 @@ async fn failed_renewal_keeps_serving() { let relay = Running::start(relay_config(&directory.url, dir.path(), &[DOMAIN]), &directory).await; let mut refused = directory.state.refused.subscribe(); - moq_clock::timeout(TIMEOUT, refused.wait_for(|refused| *refused >= 1)) + kio::clock::timeout(TIMEOUT, refused.wait_for(|refused| *refused >= 1)) .await .expect("the relay never tried to renew") .unwrap(); @@ -736,7 +736,7 @@ fn bad_auth() -> rustls_acme::EventError { /// Failed renewal validations stop ordering at the startup budget, which a start /// inside the window honors too, and renewal resumes once the oldest leaves it. -#[moq_clock::test] +#[kio::test] async fn renewal_pauses_once_failed_validations_spend_the_budget() { let dir = tempfile::tempdir().unwrap(); let mut acme = uncontacted(dir.path()); @@ -755,15 +755,15 @@ async fn renewal_pauses_once_failed_validations_spend_the_budget() { .chain(futures::stream::pending()) .inspect({ let polled = polled.clone(); - move |_| polled.borrow_mut().push(moq_clock::wall()) + move |_| polled.borrow_mut().push(kio::clock::wall()) }); - let start = moq_clock::wall(); + let start = kio::clock::wall(); let failures = Failures { path: acme.failures.path.clone(), }; - let renewal = moq_clock::sim::spawn(renew(events, failures, DOMAIN.into())); + let renewal = kio::clock::sim::spawn(renew(events, failures, DOMAIN.into())); - moq_clock::sleep(FAILURE_WINDOW - Duration::from_secs(1)).await; + kio::clock::sleep(FAILURE_WINDOW - Duration::from_secs(1)).await; assert_eq!( *polled.borrow(), [start; FAILURE_LIMIT], @@ -780,8 +780,8 @@ async fn renewal_pauses_once_failed_validations_spend_the_budget() { "{message}" ); - moq_clock::sleep(Duration::from_secs(1)).await; - moq_clock::sim::idle().await; + kio::clock::sleep(Duration::from_secs(1)).await; + kio::clock::sim::idle().await; let resumed = start + FAILURE_WINDOW; assert_eq!(*polled.borrow(), [start, start, start, resumed, resumed]); assert!( @@ -806,7 +806,7 @@ async fn a_spent_budget_still_serves_the_cached_certificate() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); - moq_clock::timeout(TIMEOUT, acme.issue(&listener)) + kio::clock::timeout(TIMEOUT, acme.issue(&listener)) .await .expect("the cached certificate deploys at once") .expect("a valid cached certificate serves despite a spent budget"); @@ -816,7 +816,7 @@ async fn a_spent_budget_still_serves_the_cached_certificate() { let leaf = &pem[pem.find("-----BEGIN CERTIFICATE-----").unwrap()..]; Cache::write(&acme.cert, leaf.as_bytes()).unwrap(); let mut acme = uncontacted(dir.path()); - let err = moq_clock::timeout(TIMEOUT, acme.issue(&listener)) + let err = kio::clock::timeout(TIMEOUT, acme.issue(&listener)) .await .expect("an undeployable cached certificate must not order past the budget") .expect_err("an undeployable cached certificate is no certificate"); diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index d09bec5f15d..ac55012c12d 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -523,7 +523,7 @@ pub struct Lease { /// grant has no driver, and an auth server's may be mid-outage. Fixed on the ambient /// clock when the grant arrives, so re-polling [`ended`](Self::ended) never /// restarts the countdown. - expires: Option, + expires: Option, /// The session's stats context, moved to a re-checked tier. stats: moq_net::stats::Session, } @@ -626,7 +626,7 @@ impl Lease { loop { let expire = async { match self.expires { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } }; @@ -1398,7 +1398,7 @@ mod tests { let clone = auth.clone(); drop(auth); assert!( - moq_clock::timeout(std::time::Duration::ZERO, admissions.next()) + kio::clock::timeout(std::time::Duration::ZERO, admissions.next()) .await .is_err() ); @@ -1415,37 +1415,41 @@ mod tests { /// The session supervisor re-polls `ended` on every nudge; that must not /// restart the countdown to `expires`. - #[moq_clock::test] + #[kio::test] async fn re_polling_keeps_the_expiry_deadline() { use std::time::Duration; - let start = moq_clock::now(); + let start = kio::clock::now(); let mut grant = Grant::new(patterns(&["**"]), patterns(&["**"])); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(10)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(10)); let mut lease = Lease::new("/room", lease::Consumer::fixed(grant)).unwrap(); for _ in 0..9 { - assert!(moq_clock::timeout(Duration::from_secs(1), lease.ended()).await.is_err()); + assert!( + kio::clock::timeout(Duration::from_secs(1), lease.ended()) + .await + .is_err() + ); } assert_eq!(lease.ended().await, lease::Reason::Expired); assert_eq!( - moq_clock::now(), + kio::clock::now(), start + Duration::from_secs(10), "expired at the deadline despite re-polling" ); } - #[moq_clock::test] + #[kio::test] async fn an_expired_grant_ends_at_once() { use std::time::Duration; let mut grant = Grant::new(patterns(&["**"]), patterns(&["**"])); - grant.expires = Some(moq_clock::wall() - Duration::from_secs(1)); + grant.expires = Some(kio::clock::wall() - Duration::from_secs(1)); assert!(matches!(grant.validate(), Err(moq_auth::Error::GrantExpired))); - let start = moq_clock::now(); + let start = kio::clock::now(); let mut lease = Lease::new("/room", lease::Consumer::fixed(grant)).unwrap(); assert_eq!(lease.ended().await, lease::Reason::Expired); - assert_eq!(moq_clock::now(), start, "no grace after expiry"); + assert_eq!(kio::clock::now(), start, "no grace after expiry"); } #[test] diff --git a/rs/moq-relay/src/auth/admission_tests.rs b/rs/moq-relay/src/auth/admission_tests.rs index ccc97f86bb3..0a4a869344a 100644 --- a/rs/moq-relay/src/auth/admission_tests.rs +++ b/rs/moq-relay/src/auth/admission_tests.rs @@ -137,7 +137,7 @@ async fn a_moved_gateway_tier_retags_its_stats() { let work = tokio::spawn(auth::hold(admitted.lease, std::future::pending::<()>())); grant.tier = Some("moved".into()); producer.update(grant); - moq_clock::timeout(std::time::Duration::from_secs(5), async { + kio::clock::timeout(std::time::Duration::from_secs(5), async { while active("moved") != 1 { tokio::task::yield_now().await; } diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 6e6e3ed2653..02da98ed8d6 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -41,7 +41,7 @@ struct Waiting { request: auth::Request, facts: moq_auth::Request, /// When its admission times out, counted from its arrival. - deadline: moq_clock::Instant, + deadline: kio::clock::Instant, } impl Waiting { @@ -53,7 +53,7 @@ impl Waiting { struct Credential { consumer: lease::Consumer, grant: Grant, - expires: Option, + expires: Option, issued: Option, initial: bool, } @@ -217,7 +217,7 @@ impl Refresh { self.waiting.push_back(Waiting { request, facts, - deadline: moq_clock::now() + super::ATTACH_TIMEOUT, + deadline: kio::clock::now() + super::ATTACH_TIMEOUT, }); self.dispatch(); } @@ -240,7 +240,7 @@ impl Refresh { facts, deadline, } = waiting; - if deadline <= moq_clock::now() { + if deadline <= kio::clock::now() { refuse(request, super::timed_out()); continue; } @@ -257,7 +257,7 @@ impl Refresh { let answered = tokio::select! { biased; answered = &mut answer => Some(answered), - () = moq_clock::sleep_until(deadline) => None, + () = kio::clock::sleep_until(deadline) => None, }; let (result, settling) = match answered { Some(answered) => (super::answered_with(answered).map(|(consumer, _)| consumer), None), @@ -276,7 +276,7 @@ impl Refresh { /// Refuse the waiting tokens whose admission timed out before a slot freed. fn expire(&mut self) { - let now = moq_clock::now(); + let now = kio::clock::now(); while let Some(waiting) = self.waiting.front() && (waiting.deadline <= now || waiting.withdrawn()) { @@ -308,7 +308,7 @@ impl Refresh { let expiry = self.waiting.front().map(|waiting| waiting.deadline); let expired = async { match expiry { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } }; @@ -414,10 +414,10 @@ impl Refresh { } /// A credential's grant changed, expired, or was revoked by the decider. -async fn changed(consumer: &mut lease::Consumer, expires: Option) -> Change { +async fn changed(consumer: &mut lease::Consumer, expires: Option) -> Change { let expire = async { match expires { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } }; @@ -480,14 +480,14 @@ mod tests { fn grant(prefix: &str, seconds: u64) -> Grant { let mut grant = Grant::new(prefix.parse::().unwrap(), moq_auth::Patterns::new()); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(seconds)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(seconds)); grant } /// Make the test runtime's clock one that only the test moves, wall time included, /// so a grant's life is measured exactly. Call it before anything reads the clock. - fn manual() -> moq_clock::Installed { - moq_clock::Manual::new().install(&tokio::runtime::Handle::current()) + fn manual() -> kio::clock::Installed { + kio::clock::Manual::new().install(&tokio::runtime::Handle::current()) } /// Whether `future` is still pending once every task has settled. Paused tokio @@ -755,7 +755,7 @@ mod tests { client.closed().await; drop(client); // The server's driver releases the stats once its transport has closed. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; let presence = registry.snapshot().sessions()[0].1; assert_eq!(presence.sessions_ended, 1, "{reason}"); for kind in Failure::ALL { @@ -858,7 +858,7 @@ mod tests { let third = present(&client, "third"); assert!( - moq_clock::timeout(Duration::from_secs(5), admissions.next()) + kio::clock::timeout(Duration::from_secs(5), admissions.next()) .await .is_err(), "a token past the limit reached the decider" @@ -890,7 +890,7 @@ mod tests { let held = admissions.next().await.unwrap(); let waiting = present(&client, "waiting"); // Past the ten-second admission timeout, and the retries that follow it. - moq_clock::sleep(Duration::from_secs(30)).await; + kio::clock::sleep(Duration::from_secs(30)).await; assert!( !waiting.is_finished() && !slow.is_finished(), "a transient refusal ended a token" @@ -941,7 +941,7 @@ mod tests { /// replacement token granted on `replacement` and its owner's grant expired, so only /// the in-band credential holds it. Returns the owner, which hears how the lease ended. async fn renewed( - clock: &moq_clock::Installed, + clock: &kio::clock::Installed, replacement: lease::Consumer, ) -> ( lease::Producer, @@ -1140,12 +1140,12 @@ mod tests { let _ = sent.await; let withdrawn = present(&client, "withdrawn"); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; withdrawn.abort(); let _ = withdrawn.await; let next = present(&client, "next"); assert!( - moq_clock::timeout(Duration::from_secs(1), admissions.next()) + kio::clock::timeout(Duration::from_secs(1), admissions.next()) .await .is_err(), "withdrawing a sent check released its slot" diff --git a/rs/moq-relay/src/cache.rs b/rs/moq-relay/src/cache.rs index deab5256d8f..381a2cec0f8 100644 --- a/rs/moq-relay/src/cache.rs +++ b/rs/moq-relay/src/cache.rs @@ -168,8 +168,8 @@ fn total_memory() -> u64 { /// relay's construction shapes. Returns on the first tick after that. async fn governor(pool: cache::PoolWeak, capacity: Option, headroom: u64) { let mut sys = sysinfo::System::new(); - let mut interval = moq_clock::interval(GOVERNOR_INTERVAL); - interval.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); + let mut interval = kio::clock::interval(GOVERNOR_INTERVAL); + interval.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Delay); loop { interval.tick().await; diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index af211bd30d2..6f5c4e7195a 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -1850,10 +1850,10 @@ impl Cluster { dialed: DialMap, http: ClientWithMiddleware, ) { - let mut tick = moq_clock::interval(CONNECT_API_POLL_INTERVAL); + let mut tick = kio::clock::interval(CONNECT_API_POLL_INTERVAL); // A slow fetch must not bank missed ticks into a catch-up burst; just resume // the cadence from the next whole interval. - tick.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Skip); + tick.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Skip); loop { tick.tick().await; @@ -1981,7 +1981,7 @@ impl Cluster { let mut redial = Redial::default(); loop { - let started = moq_clock::now(); + let started = kio::clock::now(); let result = self.run_remote_once(&addrs, target).await; let elapsed = started.elapsed(); @@ -1992,7 +1992,7 @@ impl Cluster { } let wait = redial.next(&mut rand::rng()); - moq_clock::sleep(wait).await; + kio::clock::sleep(wait).await; } } @@ -2499,7 +2499,7 @@ mod tests { let path = moq_net::Path::from_static(".stats/node/test"); let consumer = cluster.origin.consume(); - let broadcast = moq_clock::timeout( + let broadcast = kio::clock::timeout( std::time::Duration::from_secs(5), consumer.follow(&path, None).unwrap().available(), ) @@ -2511,7 +2511,7 @@ mod tests { // Several publish intervals (1s each by default) after the handle went out // of scope, the task is still running and its broadcast still announced: a // request refuses a front whose route retracted. - moq_clock::sleep(std::time::Duration::from_millis(2500)).await; + kio::clock::sleep(std::time::Duration::from_millis(2500)).await; let still_live = consumer.request(&path, None).await; assert!( still_live.is_ok(), @@ -3108,13 +3108,13 @@ mod tests { assert!(pool.used() > 0, "writes charge the constructed cache pool"); let consumer = cluster.origin.consume(); - moq_clock::timeout(Duration::from_secs(2), consumer.request("cam", None)) + kio::clock::timeout(Duration::from_secs(2), consumer.request("cam", None)) .await .expect("broadcast resolves") .expect("broadcast present"); let stats_path = moq_net::Path::from_static(".stats/node/test"); - moq_clock::timeout( + kio::clock::timeout( Duration::from_secs(5), consumer.follow(&stats_path, None).unwrap().available(), ) @@ -3616,7 +3616,7 @@ mod tests { let _dial = fingerprint.dial_lan_target(&target).expect("dial"); let mut announced = fingerprint.origin.consume().announced(); - let (update, _) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, _) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("timed out waiting for from-node") .expect("origin closed"); @@ -3628,7 +3628,7 @@ mod tests { _from_fp.announce(Default::default()).expect("announce"); let mut announced = node.origin.consume().announced(); loop { - let (update, _) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, _) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("timed out waiting for from-fingerprint") .expect("origin closed"); @@ -3751,7 +3751,7 @@ mod tests { let started = cluster.clone().start().await.expect("start"); let running = tokio::spawn(started.run()); - let _conn = moq_clock::timeout(TIMEOUT, server.accept()) + let _conn = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("dial timeout") .expect("incoming") @@ -3762,7 +3762,7 @@ mod tests { running.abort(); let _ = running.await; // Each dial holds a stop receiver until its task ends. - moq_clock::timeout(TIMEOUT, cluster.dialers.stop.closed()) + kio::clock::timeout(TIMEOUT, cluster.dialers.stop.closed()) .await .expect("a peer-list dial outlived its cancelled run"); } @@ -3804,7 +3804,7 @@ mod tests { .await .expect("dialer task"); - let conn = moq_clock::timeout(TIMEOUT, server.accept()) + let conn = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("dial timeout") .expect("incoming") @@ -3815,14 +3815,14 @@ mod tests { cluster .critical .spawn("injected", async { panic!("injected critical failure") }); - let result = moq_clock::timeout(TIMEOUT, running) + let result = kio::clock::timeout(TIMEOUT, running) .await .expect("run returns on a critical failure") .expect("run task"); assert!(result.is_err(), "a critical failure fails run"); runtime.shutdown_background(); - let err = moq_clock::timeout(TIMEOUT, conn.closed()) + let err = kio::clock::timeout(TIMEOUT, conn.closed()) .await .expect("the peer heard no close before its idle timeout"); match err { @@ -3854,7 +3854,7 @@ mod tests { first.abort(); let _ = first.await; drop(background); - moq_clock::timeout(std::time::Duration::from_secs(5), second) + kio::clock::timeout(std::time::Duration::from_secs(5), second) .await .expect("the second close finishes the shutdown"); } @@ -3926,7 +3926,7 @@ mod tests { let mut announced = node.origin.consume().announced(); loop { - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("timed out waiting for from-dialer") .expect("origin closed"); @@ -3941,7 +3941,7 @@ mod tests { let _broadcast = broadcast; loop { - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("the peer kept the dialer's route past the close") .expect("origin closed"); diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index 69cf274bc08..9e10538b342 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -1165,7 +1165,7 @@ mod tests { let internal = Internal::new(Config::default(), moq_net::stats::Registry::disabled()); let app = internal.routes(); - let elapsed = moq_clock::timeout(std::time::Duration::from_secs(60), internal.serve(app)).await; + let elapsed = kio::clock::timeout(std::time::Duration::from_secs(60), internal.serve(app)).await; assert!(elapsed.is_err(), "serve resolved with no listen address configured"); } @@ -1371,8 +1371,8 @@ mod tests { sub_source.announce(Default::default()).unwrap(); let sub_track = sub_source.create_track("audio", timed()).unwrap(); - moq_clock::sleep(std::time::Duration::from_millis(1)).await; - moq_clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; + kio::clock::sleep(std::time::Duration::from_millis(1)).await; // Leave 46 bytes across two frames behind the live edge, then read 1234 // egress bytes out of the default-tier broadcast. diff --git a/rs/moq-relay/src/listener.rs b/rs/moq-relay/src/listener.rs index 88f4258c31e..75e2b0c90bb 100644 --- a/rs/moq-relay/src/listener.rs +++ b/rs/moq-relay/src/listener.rs @@ -189,7 +189,7 @@ impl AddrListener for Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; } } } diff --git a/rs/moq-relay/src/listener/idle.rs b/rs/moq-relay/src/listener/idle.rs index aac4834d81c..4f98e763527 100644 --- a/rs/moq-relay/src/listener/idle.rs +++ b/rs/moq-relay/src/listener/idle.rs @@ -7,7 +7,7 @@ use axum::{ use axum_server::accept::Accept; use futures::{future::BoxFuture, task::AtomicWaker}; use http_body::Body as _; -use moq_clock::{Instant, Sleep}; +use kio::clock::{Instant, Sleep}; use std::{ io, pin::Pin, @@ -56,7 +56,7 @@ where let since = Instant::now(); Box::pin(async move { let (inner, service) = match timeout.and_then(|timeout| since.checked_add(timeout)) { - Some(deadline) => moq_clock::timeout_at(deadline, accepted) + Some(deadline) => kio::clock::timeout_at(deadline, accepted) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "HTTP connection idle deadline"))??, None => accepted.await?, @@ -70,7 +70,7 @@ where }), wake: AtomicWaker::new(), }); - let timer = Box::pin(moq_clock::sleep(Duration::ZERO)); + let timer = Box::pin(kio::clock::sleep(Duration::ZERO)); Ok(( Io { inner, @@ -266,7 +266,7 @@ mod tests { timeout: Some(TIMEOUT), }; let start = Instant::now(); - let result = moq_clock::timeout(TIMEOUT * 2, acceptor.accept(server, ())) + let result = kio::clock::timeout(TIMEOUT * 2, acceptor.accept(server, ())) .await .expect("stalled handshake survived its deadline"); assert_eq!(result.err().unwrap().kind(), io::ErrorKind::TimedOut); @@ -415,7 +415,7 @@ mod tests { continue; } let start = Instant::now(); - let result = moq_clock::timeout(TIMEOUT * 2, serving) + let result = kio::clock::timeout(TIMEOUT * 2, serving) .await .expect("idle HTTP/2 connection survived its deadline") .unwrap(); diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index 1fb34d2ed3d..44a90d1e2d2 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -888,7 +888,7 @@ mod tests { let request = Message::builder_request(BINDING, MessageWriteVec::new()).finish(); client.send_to(&request, addr).await.unwrap(); let mut reply = [0; 44]; - let (len, sender) = moq_clock::timeout(std::time::Duration::from_secs(5), client.recv_from(&mut reply)) + let (len, sender) = kio::clock::timeout(std::time::Duration::from_secs(5), client.recv_from(&mut reply)) .await .unwrap() .unwrap(); @@ -928,7 +928,7 @@ mod tests { trigger.start(); let mut signals = crate::shutdown::Signals::new().unwrap(); crate::shutdown::raise(libc::SIGTERM).await; - let started = moq_clock::now(); + let started = kio::clock::now(); super::drain(trigger, shutdown, Some(&mut signals)).await; assert_eq!(started.elapsed(), std::time::Duration::ZERO, "waited out the drain"); } diff --git a/rs/moq-relay/src/session.rs b/rs/moq-relay/src/session.rs index bd49b784273..433a04fc4b8 100644 --- a/rs/moq-relay/src/session.rs +++ b/rs/moq-relay/src/session.rs @@ -5,7 +5,7 @@ //! a push asks the lease to re-check now, and the server's reply is the verdict. //! One-shot HTTP and LAN peers are not sessions and stay out. -use moq_clock::Wall; +use kio::clock::Wall; use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -98,7 +98,7 @@ impl Registry { id.clone(), Entry { request, - started: moq_clock::wall(), + started: kio::clock::wall(), handle: handle.clone(), }, ); @@ -439,7 +439,7 @@ pub struct View { /// The verified client certificate, when one was presented. pub tls: Option, /// When the session was admitted, as unix seconds. - #[serde_as(as = "moq_clock::serde::UnixSeconds")] + #[serde_as(as = "kio::clock::serde::UnixSeconds")] pub started: Wall, } @@ -582,11 +582,11 @@ mod tests { let reg = registry.register(request); let ids = registry.revalidate(&Filter::from_query(Some("id=abc")).unwrap()); assert_eq!(ids, ["abc"]); - moq_clock::timeout(Duration::from_secs(1), reg.nudged()) + kio::clock::timeout(Duration::from_secs(1), reg.nudged()) .await .expect("the registration woke"); assert!( - moq_clock::timeout(std::time::Duration::from_millis(20), reg.nudged()) + kio::clock::timeout(std::time::Duration::from_millis(20), reg.nudged()) .await .is_err(), "a single push wakes once" diff --git a/rs/moq-relay/src/shutdown.rs b/rs/moq-relay/src/shutdown.rs index f6c1d3a237b..5af7feab077 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -14,7 +14,7 @@ use std::{sync::Arc, time::Duration}; -use moq_clock::Instant; +use kio::clock::Instant; use tokio::sync::watch; /// Fires the relay-wide shutdown broadcast. Held by `Relay::run` for the OS @@ -198,7 +198,7 @@ impl Observer { Err(_) => None, }; match deadline { - Some(deadline) => moq_clock::sleep_until(deadline).await, + Some(deadline) => kio::clock::sleep_until(deadline).await, None => std::future::pending().await, } } @@ -324,7 +324,7 @@ impl Observer { tokio::select! { biased; _ = session.closed() => return, - () = moq_clock::sleep_until(deadline) => {} + () = kio::clock::sleep_until(deadline) => {} } tracing::debug!("peer did not leave before the drain deadline; closing"); session.abort(moq_net::Error::GoawayTimeout); @@ -464,7 +464,7 @@ mod tests { // Only timers decide what follows. tokio::time::pause(); trigger.start(); - moq_clock::timeout(window + Duration::from_secs(1), activity.close()) + kio::clock::timeout(window + Duration::from_secs(1), activity.close()) .await .expect("a withheld SETUP outlived the drain deadline"); running.await.unwrap().unwrap(); @@ -482,7 +482,7 @@ mod tests { let trigger = relay.shutdown_trigger().clone(); let running = tokio::spawn(relay.run()); trigger.start(); - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; assert!(!running.is_finished(), "drain ended under an embedder's admission"); drop(active); running.await.unwrap().unwrap(); @@ -533,7 +533,7 @@ mod tests { // is well past the drain window. tokio::time::pause(); trigger.start(); - moq_clock::timeout(window + Duration::from_secs(1), admission.abandoned()) + kio::clock::timeout(window + Duration::from_secs(1), admission.abandoned()) .await .expect("the admission outlived the drain deadline"); running.await.unwrap().unwrap(); @@ -627,13 +627,13 @@ mod tests { async move { shutdown.drained().await } }); - moq_clock::sleep(window).await; + kio::clock::sleep(window).await; let late = shutdown.serve(); tokio::task::yield_now().await; assert!(!drained.is_finished(), "drained under a session still cleaning up"); drop(established); - moq_clock::timeout(Duration::from_secs(1), drained) + kio::clock::timeout(Duration::from_secs(1), drained) .await .expect("a session served after the deadline held the drain") .unwrap(); @@ -653,7 +653,7 @@ mod tests { assert_eq!(shutdown.tally().draining, 2); drop(left); - moq_clock::sleep(window).await; + kio::clock::sleep(window).await; drop(straggler); let tally = shutdown.tally(); diff --git a/rs/moq-relay/src/stun.rs b/rs/moq-relay/src/stun.rs index 5b86aada003..91daaa8dcd1 100644 --- a/rs/moq-relay/src/stun.rs +++ b/rs/moq-relay/src/stun.rs @@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use anyhow::Context; -use moq_clock::Instant; +use kio::clock::Instant; use serde::{Deserialize, Serialize}; use stun_types::attribute::XorMappedAddress; use stun_types::message::{BINDING, Message, MessageClass, MessageHeader, MessageWriteMutSlice}; @@ -454,7 +454,7 @@ mod tests { let client = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); client.send_to(&request(), addr).await.unwrap(); let mut output = [0; 44]; - let (len, sender) = moq_clock::timeout(Duration::from_secs(5), client.recv_from(&mut output)) + let (len, sender) = kio::clock::timeout(Duration::from_secs(5), client.recv_from(&mut output)) .await .unwrap() .unwrap(); diff --git a/rs/moq-relay/src/uring.rs b/rs/moq-relay/src/uring.rs index 21af4060be0..217e2432788 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -1146,7 +1146,7 @@ mod tests { // is well past the drain window. tokio::time::pause(); trigger.start(); - moq_clock::timeout(window + std::time::Duration::from_secs(1), admission.abandoned()) + kio::clock::timeout(window + std::time::Duration::from_secs(1), admission.abandoned()) .await .expect("the admission outlived the drain deadline"); running.await.unwrap().unwrap(); @@ -1202,7 +1202,7 @@ mod tests { // The handshake deadline is an io_uring timer, which a paused tokio clock cannot // advance, so this waits out the real second with nobody answering. - moq_clock::timeout(timeout * 5, admission.abandoned()) + kio::clock::timeout(timeout * 5, admission.abandoned()) .await .expect("the admission outlived the handshake deadline"); trigger.start(); diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index 2d1a12d2c86..0939fb59acb 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -366,7 +366,7 @@ impl Web { let state = Arc::get_mut(&mut self.state).expect("with_timeout called after routes were built"); // hyper adds the header timeout to the clock unchecked, so an unreachable // one would panic on every connection. - state.timeout = timeout.filter(|timeout| moq_clock::now().checked_add(*timeout).is_some()); + state.timeout = timeout.filter(|timeout| kio::clock::now().checked_add(*timeout).is_some()); self } @@ -1012,7 +1012,7 @@ async fn admit_http( // HTTP read has no handshake deadline to inherit, so the bound starts here. let admit = state.auth.admit(request); let lease = match state.timeout { - Some(timeout) => moq_clock::timeout(timeout, admit) + Some(timeout) => kio::clock::timeout(timeout, admit) .await .unwrap_or_else(|_| Err(auth::Error::Unavailable("the admission timed out".into()))), None => admit.await, @@ -1094,11 +1094,11 @@ async fn serve_fetch( tracing::info!(%broadcast, %track, "fetching track"); - let deadline = moq_clock::now() + tokio::time::Duration::from_secs(30); + let deadline = kio::clock::now() + tokio::time::Duration::from_secs(30); // The lease outlives this handler: the body streams after it returns, so the // response holds the lease and ends it when the last frame is served. - let result = moq_clock::timeout_at(deadline, async { + let result = kio::clock::timeout_at(deadline, async { // NOTE: The auth token is already scoped to the broadcast. // Block until a route covers the broadcast (within the fetch deadline) so // freshly-connected subscribers don't get a spurious 404 before the announce arrives. @@ -1154,7 +1154,7 @@ async fn serve_fetch( /// `end` event carries the outcome. struct ServeGroup { group: moq_net::group::Consumer, - deadline: moq_clock::Instant, + deadline: kio::clock::Instant, /// Taken when the body ends, so the reason is reported once. lease: Option, } @@ -1165,7 +1165,7 @@ impl ServeGroup { return Ok(None); }; tokio::select! { - res = moq_clock::timeout_at(self.deadline, self.group.read_frame()) => match res { + res = kio::clock::timeout_at(self.deadline, self.group.read_frame()) => match res { Ok(res) => Ok(res?.map(|frame| frame.payload)), Err(_) => Err(moq_net::Error::Timeout), }, @@ -2095,11 +2095,11 @@ mod tests { let serving = tokio::spawn(web.serve(Router::new())); let mut tcp = tokio::net::TcpStream::connect(http).await.unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n").await.unwrap(); let mut rest = Vec::new(); - moq_clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut rest)) + kio::clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut rest)) .await .expect("slow headers held the connection open") .ok(); @@ -2133,13 +2133,13 @@ mod tests { let serving = tokio::spawn(web.serve(routes)); let mut tcp = tokio::net::TcpStream::connect(http).await.unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); tcp.write_all(b"GET /announced HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") .await .unwrap(); let mut response = Vec::new(); - moq_clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut response)) + kio::clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut response)) .await .expect("the unanswered admission held the request open") .ok(); @@ -2251,7 +2251,7 @@ mod tests { tcp.write_all(&frame).await.unwrap(); let mut rest = Vec::new(); - moq_clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut rest)) + kio::clock::timeout(std::time::Duration::from_secs(10), tcp.read_to_end(&mut rest)) .await .expect("the socket waited to buffer a frame larger than a record") .ok(); diff --git a/rs/moq-relay/src/websocket.rs b/rs/moq-relay/src/websocket.rs index d7167934b9c..88c551952ef 100644 --- a/rs/moq-relay/src/websocket.rs +++ b/rs/moq-relay/src/websocket.rs @@ -510,7 +510,7 @@ mod tests { // past it, so the headers and body stay in the socket. let mut stream = BufReader::new(stream); let mut status = Vec::new(); - moq_clock::timeout(Duration::from_secs(5), stream.read_until(b'\n', &mut status)) + kio::clock::timeout(Duration::from_secs(5), stream.read_until(b'\n', &mut status)) .await .expect("server did not respond") .expect("read response"); @@ -599,7 +599,7 @@ mod tests { } async fn next_observed(rx: &mut mpsc::UnboundedReceiver) -> Observed { - moq_clock::timeout(Duration::from_secs(5), rx.recv()) + kio::clock::timeout(Duration::from_secs(5), rx.recv()) .await .expect("server did not report a connection") .expect("server channel closed") @@ -801,11 +801,11 @@ mod tests { // Paused time only advances once every task is idle, so this resolves // exactly when both ends have settled. - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; frozen.store(true, Ordering::Relaxed); // Generous versus the 30s deadline: this asserts termination, not timing. - moq_clock::timeout(Duration::from_secs(300), server) + kio::clock::timeout(Duration::from_secs(300), server) .await .expect("a silent WebSocket peer must be reaped by the keep-alive") .expect("server task panicked") @@ -834,7 +834,7 @@ mod tests { ); options.link.alpn = Some(alpn.clone()); options.timeout = Some(timeout); - let start = moq_clock::now(); + let start = kio::clock::now(); let server = tokio::spawn(moq_tokio::websocket::accept( Pipe::new(server_incoming, server_to_client, Arc::new(AtomicBool::new(false))), options, diff --git a/rs/moq-relay/tests/drills.rs b/rs/moq-relay/tests/drills.rs index 56ab47079ac..dc3e973393b 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -240,7 +240,7 @@ impl RelayHost { } }); - let addr = moq_clock::timeout(TIMEOUT, bound) + let addr = kio::clock::timeout(TIMEOUT, bound) .await .expect("relay startup timed out") .expect("relay task vanished during startup") @@ -354,7 +354,7 @@ fn write_group(track: &mut moq_net::track::Producer, payload: &[u8]) { /// Read the next group's first frame, failing the drill on a timeout, a clean /// finish, or an empty group. async fn read_group(reader: &mut Reader, what: &str) -> (u64, Vec) { - let group = moq_clock::timeout(TIMEOUT, reader.groups.recv_group()) + let group = kio::clock::timeout(TIMEOUT, reader.groups.recv_group()) .await .unwrap_or_else(|_| panic!("{what}: no group within {TIMEOUT:?}")) .unwrap_or_else(|err| panic!("{what}: track aborted: {err}")) @@ -362,7 +362,7 @@ async fn read_group(reader: &mut Reader, what: &str) -> (u64, Vec) { let sequence = group.sequence; let mut group = group; - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("{what}: no frame within {TIMEOUT:?}")) .unwrap_or_else(|err| panic!("{what}: group aborted: {err}")) @@ -378,7 +378,7 @@ async fn read_group(reader: &mut Reader, what: &str) -> (u64, Vec) { /// the old session is skipped here. A track-level failure is still fatal: that /// says the subscription itself did not survive. async fn read_until(reader: &mut Reader, want: &[u8], what: &str) { - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { let mut group = match reader.groups.recv_group().await { Ok(Some(group)) => group, @@ -411,13 +411,13 @@ struct Reader { async fn subscribe(origin: &moq_net::origin::Consumer, path: &str) -> Reader { // Following parks until a route covers the path, where a request could find the // discovery synced before the announcement reaches this relay. - let broadcast = moq_clock::timeout(TIMEOUT, origin.follow(path, None).unwrap().available()) + let broadcast = kio::clock::timeout(TIMEOUT, origin.follow(path, None).unwrap().available()) .await .expect("announcement timed out") .expect("origin closed before announcing"); let track = broadcast.track(TRACK).expect("track"); - let groups = moq_clock::timeout(TIMEOUT, track.subscribe(None)) + let groups = kio::clock::timeout(TIMEOUT, track.subscribe(None)) .await .expect("subscribe timed out") .expect("subscribe rejected"); @@ -451,7 +451,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { let broadcast = publisher.create_broadcast("live").expect("create broadcast"); broadcast.announce(Default::default()).expect("announce broadcast"); let mut track = broadcast.create_track(TRACK, timed()).expect("create track"); - let publish_session = moq_clock::timeout( + let publish_session = kio::clock::timeout( TIMEOUT, client(&url) .with_publisher(&publisher) @@ -465,7 +465,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { let subscriber = moq_tokio::origin::spawn(); let subscribed = subscriber.consume(); - let subscribe_session = moq_clock::timeout( + let subscribe_session = kio::clock::timeout( TIMEOUT, client(&url) .with_subscriber(subscriber) @@ -485,7 +485,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { // The stall: the reader stops asking while the publisher runs ahead of it. for i in 0..STALL_GROUPS { write_group(&mut track, format!("stalled {i}").as_bytes()); - moq_clock::sleep(STALL / STALL_GROUPS as u32).await; + kio::clock::sleep(STALL / STALL_GROUPS as u32).await; } // Fault activation: the groups reached the subscriber and stacked up behind a @@ -495,7 +495,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { // far behind is shed rather than waited for), so an unread backlog is what // backpressure looks like from here. let mut behind = None; - let backlog = moq_clock::timeout(TIMEOUT, async { + let backlog = kio::clock::timeout(TIMEOUT, async { while let Some(largest) = reader.track.largest().await { behind = Some(largest.group - first); if largest.group >= first + STALL_GROUPS as u64 { @@ -526,7 +526,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { // Resource release: everything that session was feeding is closed, rather // than left parked on a subscription nobody will ever serve again. - moq_clock::timeout(TIMEOUT, cancelled.closed()) + kio::clock::timeout(TIMEOUT, cancelled.closed()) .await .expect("the cancelled subscriber's broadcast never closed"); println!("resource released: the cancelled broadcast closed"); @@ -535,7 +535,7 @@ async fn cancel_under_backpressure_releases_the_reader(lane: Lane) { // upstream subscription the cancel left in place. let rejoin = moq_tokio::origin::spawn(); let rejoined = rejoin.consume(); - let rejoin_session = moq_clock::timeout( + let rejoin_session = kio::clock::timeout( TIMEOUT, client(&url) .with_subscriber(rejoin) @@ -601,12 +601,12 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { let mut open = track.append_group().expect("append group"); open.write_frame(moq_net::Timestamp::ZERO, b"read".as_ref()) .expect("write frame"); - let mut open_reader = moq_clock::timeout(TIMEOUT, reader.groups.recv_group()) + let mut open_reader = kio::clock::timeout(TIMEOUT, reader.groups.recv_group()) .await .expect("open group timed out") .expect("track aborted") .expect("track finished"); - moq_clock::timeout(TIMEOUT, open_reader.read_frame()) + kio::clock::timeout(TIMEOUT, open_reader.read_frame()) .await .expect("open frame timed out") .expect("open group aborted") @@ -619,7 +619,7 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { // Terminal result: the unread half of the open group fails. `Ok(None)` here // would be the relay's death passing for the publisher finishing. - let err = moq_clock::timeout(TIMEOUT, open_reader.read_frame()) + let err = kio::clock::timeout(TIMEOUT, open_reader.read_frame()) .await .expect("the interrupted group never resolved") .expect_err("the interrupted group reported a clean finish"); @@ -637,7 +637,7 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { // The outage is observed, not hidden: the broadcast the dead session fed closed // with it, so the old subscription ends rather than reading from a stale route. - let err = match moq_clock::timeout(TIMEOUT, reader.groups.recv_group()) + let err = match kio::clock::timeout(TIMEOUT, reader.groups.recv_group()) .await .expect("the interrupted subscription never resolved") { @@ -666,7 +666,7 @@ lanes!(relay_killed_mid_group_aborts_then_resumes); /// Wait for a reconnect loop to report `want`, failing with what it said instead. async fn expect_status(reconnect: &mut moq_tokio::Connection, want: moq_tokio::Status, who: &str) { loop { - let status = moq_clock::timeout(TIMEOUT, reconnect.status()) + let status = kio::clock::timeout(TIMEOUT, reconnect.status()) .await .unwrap_or_else(|_| panic!("{who}: no status change within {TIMEOUT:?}, wanted {want:?}")) .unwrap_or_else(|err| panic!("{who}: reconnect loop gave up: {err}")); @@ -689,7 +689,7 @@ async fn interrupted_publisher_republishes_new_content(lane: Lane) { let subscriber = moq_tokio::origin::spawn(); let subscribed = subscriber.consume(); - let subscribe_session = moq_clock::timeout( + let subscribe_session = kio::clock::timeout( TIMEOUT, client(&url) .with_subscriber(subscriber) @@ -706,7 +706,7 @@ async fn interrupted_publisher_republishes_new_content(lane: Lane) { let broadcast = first.create_broadcast("live").expect("create broadcast"); broadcast.announce(Default::default()).expect("announce broadcast"); let mut track = broadcast.create_track(TRACK, timed()).expect("create track"); - let first_session = moq_clock::timeout( + let first_session = kio::clock::timeout( TIMEOUT, client(&url) .with_publisher(&first) @@ -744,7 +744,7 @@ async fn interrupted_publisher_republishes_new_content(lane: Lane) { let broadcast = second.create_broadcast("live").expect("re-create broadcast"); broadcast.announce(Default::default()).expect("announce broadcast"); let mut track = broadcast.create_track(TRACK, timed()).expect("re-create track"); - let second_session = moq_clock::timeout( + let second_session = kio::clock::timeout( TIMEOUT, client(&url) .with_publisher(&second) @@ -779,7 +779,7 @@ lanes!(interrupted_publisher_republishes_new_content); /// Wait for `path` to be announced (`want`) or unannounced (`!want`). async fn expect_announce(announced: &mut moq_net::announce::Consumer, path: &str, want: bool, who: &str) { loop { - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(announced)) .await .unwrap_or_else(|_| panic!("{who}: no announcement change within {TIMEOUT:?}")) .unwrap_or_else(|| panic!("{who}: the announcement stream closed")); @@ -964,7 +964,7 @@ enum Flap { /// Cut at `at`, with the route over it still announced. Cut { outage: moq_shaper::Outage, - at: moq_clock::Instant, + at: kio::clock::Instant, }, /// The edge withdrew the route after the link was down for `cut`. The link /// is back and the edge redials. @@ -1025,7 +1025,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { broadcast.announce(Default::default()).expect("announce broadcast"); let mut track = broadcast.create_track(TRACK, timed()).expect("create track"); let url = publish_path.url.clone(); - let publish_session = moq_clock::timeout( + let publish_session = kio::clock::timeout( TIMEOUT, client_over(&url, credit(lane, quic())) .with_publisher(&publisher) @@ -1041,7 +1041,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { let subscribed = subscriber.consume(); let mut announced = subscribed.announced(); let url = subscribe_path.url.clone(); - let subscribe_session = moq_clock::timeout( + let subscribe_session = kio::clock::timeout( TIMEOUT, client_over(&url, credit(lane, quic())) .with_subscriber(subscriber) @@ -1060,7 +1060,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { // ingress burst holds every publisher datagram, including the replies and // credit the origin needs before it subscribes, so arming it any earlier // starves the publisher's session until it idles out. - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while track.subscription().is_none() { track.subscription_changed().await.expect("track aborted"); } @@ -1089,18 +1089,18 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { // Write the next burst, cutting a flapping link just before the flap burst. // A burst is written without yielding, so a cut partway through it would // still land before any of it left the publisher. - let burst = |track: &mut moq_net::track::Producer, written: &mut Vec, flap: &mut Flap| { + let burst = |track: &mut moq_net::track::Producer, written: &mut Vec, flap: &mut Flap| { if link == PeerLink::Flapping && written.len() as u64 == FLAP_BURST * BURST_GROUPS { let outage = peer.shaper.as_ref().expect("a flapping link has a shaper").cut(); *flap = Flap::Cut { outage, - at: moq_clock::now(), + at: kio::clock::now(), }; } for _ in 0..BURST_GROUPS { let sequence = written.len() as u64; write_group(track, &payload(sequence)); - written.push(moq_clock::now()); + written.push(kio::clock::now()); } }; burst(&mut track, &mut written, &mut flap); @@ -1132,7 +1132,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { |pending: &mut tokio::task::JoinSet<_>, track: &moq_net::track::Consumer, sequence: u64, generation: u64| { let fetching = track.fetch_group(sequence, None); pending.spawn(async move { - let fetched = moq_clock::timeout(wait, async { + let fetched = kio::clock::timeout(wait, async { let group = fetching.await.map_err(|err| err.to_string())?; read_payload(group, sequence).await }); @@ -1149,7 +1149,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { // reported by name rather than as a generic stall. let step_timeout = wait + Duration::from_secs(1); while (outcomes.len() as u64) < total { - let step = moq_clock::timeout(step_timeout, async { + let step = kio::clock::timeout(step_timeout, async { tokio::select! { group = reader.groups.recv_group(), if subscription_up => Step::Group(Box::new(group)), Some(settled) = pending.join_next() => { @@ -1208,7 +1208,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { } (false, _) => panic!("the route was withdrawn while the peer link was up"), (true, Flap::Withdrawn { cut }) => { - restored_at = Some(moq_clock::now()); + restored_at = Some(kio::clock::now()); reader = subscribe(&subscribed, "live").await; generation += 1; subscription_up = true; @@ -1241,7 +1241,7 @@ async fn cross_cluster(lane: Lane, link: PeerLink) { if claimed.insert(sequence) { live.insert(sequence); pending.spawn(async move { - let outcome = match moq_clock::timeout(wait, read_payload(group, sequence)).await { + let outcome = match kio::clock::timeout(wait, read_payload(group, sequence)).await { Ok(Ok(())) => Outcome::Live, Ok(Err(err)) => Outcome::Failed(err), Err(_) => Outcome::Stalled, @@ -1333,7 +1333,7 @@ async fn no_publisher_never_delivers(lane: Lane) { let subscriber = moq_tokio::origin::spawn(); let subscribed = subscriber.consume(); - let session = moq_clock::timeout( + let session = kio::clock::timeout( TIMEOUT, client(&url) .with_subscriber(subscriber) @@ -1356,8 +1356,8 @@ async fn no_publisher_never_delivers(lane: Lane) { let mut announced = subscribed.announced(); let mut following = subscribed.follow("live", None).unwrap(); let (update, resolved) = tokio::join!( - moq_clock::timeout(quiet, next_update(&mut announced)), - moq_clock::timeout(quiet, following.available()), + kio::clock::timeout(quiet, next_update(&mut announced)), + kio::clock::timeout(quiet, following.available()), ); if let Ok(update) = update { let path = update.map(|(update, _)| update.prefix.to_string()); @@ -1444,7 +1444,7 @@ async fn subscriber_max_age_skips_bufferbloat(version: &str) { .await .unwrap(); write_group(&mut track, b"warmup"); - let remote = moq_clock::timeout(TIMEOUT, consumed.follow("live", None).unwrap().available()) + let remote = kio::clock::timeout(TIMEOUT, consumed.follow("live", None).unwrap().available()) .await .unwrap() .unwrap(); @@ -1459,7 +1459,7 @@ async fn subscriber_max_age_skips_bufferbloat(version: &str) { warmup.read_frame().await.unwrap().unwrap().payload, b"warmup".as_slice() ); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { if track .subscription() @@ -1483,7 +1483,7 @@ async fn subscriber_max_age_skips_bufferbloat(version: &str) { .unwrap(); let payload = vec![42u8; 32_000]; write_group(&mut track, &payload); - moq_clock::timeout(TIMEOUT, burst.completed()) + kio::clock::timeout(TIMEOUT, burst.completed()) .await .expect("rate-limit queue never filled") .unwrap(); @@ -1495,7 +1495,7 @@ async fn subscriber_max_age_skips_bufferbloat(version: &str) { .write_frame(moq_net::Timestamp::from_millis(sequence * 50).unwrap(), payload.clone()) .unwrap(); group.finish().unwrap(); - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } let mut newest = track.append_group().unwrap(); newest @@ -1503,8 +1503,8 @@ async fn subscriber_max_age_skips_bufferbloat(version: &str) { .unwrap(); newest.finish().unwrap(); // No successor means this snapshot must survive even after its budget elapsed. - moq_clock::sleep(Duration::from_millis(500)).await; - let sequence = moq_clock::timeout(TIMEOUT, async { + kio::clock::sleep(Duration::from_millis(500)).await; + let sequence = kio::clock::timeout(TIMEOUT, async { loop { let mut group = groups.recv_group().await.unwrap().expect("subscription ended"); if let Ok(Some(frame)) = group.read_frame().await diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index 245e74f5743..b15ca3a0c09 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -149,7 +149,7 @@ fn all() -> Patterns { /// Everything under the dialed path, re-checked every second, good for `expires_in`. fn grant(expires_in: Duration) -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(moq_clock::wall() + expires_in); + grant.expires = Some(kio::clock::wall() + expires_in); grant.revalidate = Some(Duration::from_secs(1)); grant } @@ -274,7 +274,7 @@ async fn connect_and_round_trip(url: &url::Url) -> (moq_tokio::Connection, moq_t .expect("write frame"); group.finish().expect("finish group"); - let pub_session = moq_clock::timeout( + let pub_session = kio::clock::timeout( TIMEOUT, client() .with_publisher(pub_origin.consume()) @@ -289,7 +289,7 @@ async fn connect_and_round_trip(url: &url::Url) -> (moq_tokio::Connection, moq_t let sub_origin = moq_tokio::origin::spawn(); let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); - let sub_session = moq_clock::timeout( + let sub_session = kio::clock::timeout( TIMEOUT, client() .with_subscriber(sub_origin) @@ -301,7 +301,7 @@ async fn connect_and_round_trip(url: &url::Url) -> (moq_tokio::Connection, moq_t .expect("subscriber connect timeout") .expect("subscriber connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -313,12 +313,12 @@ async fn connect_and_round_trip(url: &url::Url) -> (moq_tokio::Connection, moq_t .expect("announced broadcast resolves"); let mut track_sub = bc.track("video").unwrap().subscribe(None).await.expect("consume_track"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -340,7 +340,7 @@ async fn assert_refused(url: &url::Url) { async fn assert_refused_with(client: moq_tokio::Client, url: &url::Url) { let origin = moq_tokio::origin::spawn(); - let result = moq_clock::timeout( + let result = kio::clock::timeout( TIMEOUT, client .with_subscriber(origin) @@ -351,7 +351,7 @@ async fn assert_refused_with(client: moq_tokio::Client, url: &url::Url) { .await .expect("connect timeout"); if let Ok(session) = result { - let closed = moq_clock::timeout(Duration::from_secs(3), session.closed()) + let closed = kio::clock::timeout(Duration::from_secs(3), session.closed()) .await .expect("the relay admitted a session the server refused"); assert!(closed.is_err(), "a refused session closed cleanly"); @@ -393,7 +393,7 @@ async fn spawn_quic_relay_with( } async fn assert_closed(session: moq_tokio::Connection, within: Duration, what: &str) { - let _ = moq_clock::timeout(within, session.closed()) + let _ = kio::clock::timeout(within, session.closed()) .await .unwrap_or_else(|_| panic!("relay should close the {what} session")); } @@ -475,11 +475,11 @@ async fn forwards_the_setup_token() { .await .expect("open the setup stream"); write_all(&mut send, &setup).await; - let mut recv = moq_clock::timeout(TIMEOUT, session.accept_uni()) + let mut recv = kio::clock::timeout(TIMEOUT, session.accept_uni()) .await .expect("SETUP timeout") .expect("the server's setup stream"); - let reply = moq_clock::timeout(TIMEOUT, recv.read_chunk(1)) + let reply = kio::clock::timeout(TIMEOUT, recv.read_chunk(1)) .await .expect("SETUP timeout") .expect("SETUP"); @@ -527,7 +527,7 @@ async fn a_configured_token_is_the_connection_credential() { config.tokens = vec!["credential".parse().unwrap()]; let client = config.init(Default::default()).unwrap(); let url: url::Url = format!("tcp://127.0.0.1:{port}/room").parse().unwrap(); - let session = moq_clock::timeout( + let session = kio::clock::timeout( TIMEOUT, client .with_reconnect(false) @@ -541,7 +541,7 @@ async fn a_configured_token_is_the_connection_credential() { if setup.is_some() { // Lite-07 answers the SETUP token over AUTH, so its grant proves admission. let mut grant = session.auth().grant(); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while grant.peek().is_none() { grant.changed().await.expect("the relay refused the configured token"); } @@ -552,7 +552,7 @@ async fn a_configured_token_is_the_connection_credential() { // Lite-06 has no AUTH answer and a client is live before admission, so give a // refusal time to land. assert!( - moq_clock::timeout(Duration::from_millis(500), session.closed()) + kio::clock::timeout(Duration::from_millis(500), session.closed()) .await .is_err(), "{versions:?}: the relay refused the configured token" @@ -637,7 +637,7 @@ async fn a_moved_tier_retags_the_live_session() { let broadcast = pub_origin.create_broadcast("test").expect("create broadcast"); broadcast.announce(Default::default()).expect("announce broadcast"); let track = broadcast.create_track("video", timed()).expect("create track"); - let pub_session = moq_clock::timeout( + let pub_session = kio::clock::timeout( TIMEOUT, client() .with_publisher(pub_origin.consume()) @@ -652,7 +652,7 @@ async fn a_moved_tier_retags_the_live_session() { let sub_origin = moq_tokio::origin::spawn(); let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); - let sub_session = moq_clock::timeout( + let sub_session = kio::clock::timeout( TIMEOUT, client() .with_subscriber(sub_origin) @@ -663,7 +663,7 @@ async fn a_moved_tier_retags_the_live_session() { .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); - let (update, announced) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, announced) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -681,12 +681,12 @@ async fn a_moved_tier_retags_the_live_session() { .write_frame(moq_net::Timestamp::ZERO, payload) .expect("write frame"); group.finish().expect("finish group"); - let mut group = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -708,10 +708,10 @@ async fn a_moved_tier_retags_the_live_session() { moved_grant.label = Some("project/key/2".into()); script.on_revalidate(Answer::Grant(moved_grant)); - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; while active(&moved) < 2 { - assert!(moq_clock::now() < deadline, "the re-checked tier never applied"); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "the re-checked tier never applied"); + kio::clock::sleep(Duration::from_millis(50)).await; } assert_eq!(active(&stats::Tier::default()), 0, "presence left the old tier"); @@ -743,13 +743,13 @@ async fn a_moved_tier_retags_the_live_session() { ); assert!( - moq_clock::timeout(Duration::from_millis(200), pub_session.closed()) + kio::clock::timeout(Duration::from_millis(200), pub_session.closed()) .await .is_err(), "a tier change must not close the publisher" ); assert!( - moq_clock::timeout(Duration::from_millis(200), sub_session.closed()) + kio::clock::timeout(Duration::from_millis(200), sub_session.closed()) .await .is_err(), "a tier change must not close the subscriber" @@ -781,7 +781,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { broadcast.announce(Default::default()).expect("announce broadcast"); tracks.push((broadcast, track)); } - let pub_session = moq_clock::timeout( + let pub_session = kio::clock::timeout( TIMEOUT, client() .with_publisher(pub_origin.consume()) @@ -795,7 +795,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { let sub_origin = moq_tokio::origin::spawn(); let sub_consumer = sub_origin.consume(); - let sub_session = moq_clock::timeout( + let sub_session = kio::clock::timeout( TIMEOUT, client() .with_subscriber(sub_origin) @@ -809,7 +809,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { let mut subs = Vec::new(); for path in ["alice/audio", "alice/video"] { - let broadcast = moq_clock::timeout(TIMEOUT, sub_consumer.follow(path, None).unwrap().available()) + let broadcast = kio::clock::timeout(TIMEOUT, sub_consumer.follow(path, None).unwrap().available()) .await .expect("announcement timeout") .expect("announced broadcast resolves"); @@ -832,7 +832,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { }; for (index, sub) in subs.iter_mut().enumerate() { send(index, 0); - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") @@ -845,7 +845,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { script.on_revalidate(Answer::Grant(narrow)); let err = loop { - match moq_clock::timeout(TIMEOUT, subs[0].recv_group()) + match kio::clock::timeout(TIMEOUT, subs[0].recv_group()) .await .expect("the deafened track never ended") { @@ -863,7 +863,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { ); send(1, 1); - let group = moq_clock::timeout(TIMEOUT, subs[1].recv_group()) + let group = kio::clock::timeout(TIMEOUT, subs[1].recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") @@ -872,7 +872,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { // Undeafen: the path is announced again and a new subscription flows. script.on_revalidate(Answer::Grant(grant(Duration::from_secs(3600)))); - let broadcast = moq_clock::timeout(TIMEOUT, sub_consumer.follow("alice/audio", None).unwrap().available()) + let broadcast = kio::clock::timeout(TIMEOUT, sub_consumer.follow("alice/audio", None).unwrap().available()) .await .expect("the undeafened path was never announced again") .expect("announced broadcast resolves"); @@ -883,7 +883,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { .await .expect("subscribe"); send(0, 1); - let group = moq_clock::timeout(TIMEOUT, audio.recv_group()) + let group = kio::clock::timeout(TIMEOUT, audio.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") @@ -892,7 +892,7 @@ async fn a_rechecked_grant_resizes_live_sessions() { for (session, what) in [(pub_session, "publisher"), (sub_session, "subscriber")] { assert!( - moq_clock::timeout(Duration::from_millis(200), session.closed()) + kio::clock::timeout(Duration::from_millis(200), session.closed()) .await .is_err(), "{scheme}: a resize must not close the {what}" @@ -940,7 +940,7 @@ async fn a_refusal_closes_live_sessions() { assert_closed(pub_session, Duration::from_secs(5), &format!("{label} publisher")).await; assert_closed(sub_session, Duration::from_secs(5), &format!("{label} subscriber")).await; - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; let ends = script.ends(); assert!(ends.len() >= 2, "{label}: an end per session, got {}", ends.len()); for end in &ends { @@ -973,7 +973,7 @@ async fn http_routes_hold_a_lease() { group .write_frame(moq_net::Timestamp::ZERO, b"hello".as_ref()) .expect("write frame"); - let pub_session = moq_clock::timeout( + let pub_session = kio::clock::timeout( TIMEOUT, client() .with_publisher(pub_origin.consume()) @@ -989,7 +989,7 @@ async fn http_routes_hold_a_lease() { // the /announced handler only reports what has arrived so far. let sub_origin = moq_tokio::origin::spawn(); let mut announcements = sub_origin.consume().announced(); - let _sub_session = moq_clock::timeout( + let _sub_session = kio::clock::timeout( TIMEOUT, client() .with_subscriber(sub_origin) @@ -1000,7 +1000,7 @@ async fn http_routes_hold_a_lease() { .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -1039,7 +1039,7 @@ async fn http_routes_hold_a_lease() { Event::End { reason, .. } => reason.clone(), _ => unreachable!(), }; - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; let done = ends(&script); assert_eq!(done.len(), 1, "the announced session ended"); assert_eq!(end_reason(&done[0]), "done".into()); @@ -1050,7 +1050,7 @@ async fn http_routes_hold_a_lease() { .await .expect("fetch request"); assert_eq!(fetch.status(), 200); - let first = moq_clock::timeout(TIMEOUT, fetch.chunk()) + let first = kio::clock::timeout(TIMEOUT, fetch.chunk()) .await .expect("first frame timeout") .expect("first frame") @@ -1058,12 +1058,12 @@ async fn http_routes_hold_a_lease() { assert_eq!(&first[..], b"hello"); // The body is still streaming, so the fetch's lease is still held. - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; assert_eq!(ends(&script).len(), 1, "the fetch must not end while its body streams"); // A refusal on the fetch's re-check cuts the transfer; the publisher is untouched. script.on_revalidate_http(Answer::Status(403)); - let cut = moq_clock::timeout(Duration::from_secs(5), async { + let cut = kio::clock::timeout(Duration::from_secs(5), async { loop { match fetch.chunk().await { Ok(Some(_)) => continue, @@ -1075,12 +1075,12 @@ async fn http_routes_hold_a_lease() { .expect("the refused fetch kept streaming"); assert!(cut.is_err(), "a refused fetch must not end cleanly: {cut:?}"); - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; let ended = ends(&script); assert_eq!(ended.len(), 2, "the fetch session ended"); assert_eq!(end_reason(&ended[1]), moq_auth::lease::Reason::Refused); assert!( - moq_clock::timeout(Duration::from_millis(200), pub_session.closed()) + kio::clock::timeout(Duration::from_millis(200), pub_session.closed()) .await .is_err(), "refusing the fetch must not close the publisher" @@ -1103,18 +1103,18 @@ async fn the_end_carries_duration_and_bytes() { .unwrap(); let (pub_session, sub_session) = connect_and_round_trip(&url).await; - moq_clock::sleep(Duration::from_millis(300)).await; + kio::clock::sleep(Duration::from_millis(300)).await; drop(pub_session); drop(sub_session); - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); let ends = loop { let ends = script.ends(); if ends.len() >= 2 { break ends; } - assert!(moq_clock::now() < deadline, "ends never arrived: {}", ends.len()); - moq_clock::sleep(Duration::from_millis(50)).await; + assert!(kio::clock::now() < deadline, "ends never arrived: {}", ends.len()); + kio::clock::sleep(Duration::from_millis(50)).await; }; for end in &ends { let Event::End { duration, bytes, .. } = &end.event else { @@ -1148,7 +1148,7 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { // Keep the deadline from racing the client receiving GOAWAY under load. tokio::time::pause(); trigger.start(); - moq_clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| client.draining().poll(waiter))) + kio::clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| client.draining().poll(waiter))) .await .expect("GOAWAY timeout") .expect("a GOAWAY"); @@ -1160,7 +1160,7 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { tokio::time::advance(drain_timeout).await; // The end report crosses HTTP, so resume real time after forcing the close. tokio::time::resume(); - moq_clock::timeout(TIMEOUT, script.end_arrived.notified()) + kio::clock::timeout(TIMEOUT, script.end_arrived.notified()) .await .expect("the end never reached the server"); tokio::task::yield_now().await; @@ -1170,7 +1170,7 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { ); gate.add_permits(1); - moq_clock::timeout(TIMEOUT, drained) + kio::clock::timeout(TIMEOUT, drained) .await .expect("the drain outlived the end") .unwrap(); @@ -1244,7 +1244,7 @@ async fn a_certificate_admits_only_what_the_server_grants() { let (addr, relay) = spawn_quic_relay(build_auth(narrow), Some(root.clone())).await; let url: url::Url = format!("moql://127.0.0.1:{}/mine", addr.port()).parse().unwrap(); let origin = moq_tokio::origin::spawn(); - let session = moq_clock::timeout( + let session = kio::clock::timeout( TIMEOUT, mtls_client() .with_publisher(origin.consume()) @@ -1256,7 +1256,7 @@ async fn a_certificate_admits_only_what_the_server_grants() { .expect("connect timeout") .expect("a scoped certificate is admitted"); assert!( - moq_clock::timeout(Duration::from_secs(2), session.closed()) + kio::clock::timeout(Duration::from_secs(2), session.closed()) .await .is_err(), "the scoped publisher stays admitted" @@ -1314,7 +1314,7 @@ async fn mtls_route_source(mtls_peer: bool) -> moq_net::origin::Source { let _forwarded = peer.create_broadcast("forwarded").expect("create"); _forwarded.announce(Default::default()).expect("announce"); let url: url::Url = format!("moql://127.0.0.1:{}/", addr.port()).parse().unwrap(); - let _session = moq_clock::timeout( + let _session = kio::clock::timeout( TIMEOUT, config .init(Default::default()) @@ -1329,7 +1329,7 @@ async fn mtls_route_source(mtls_peer: bool) -> moq_net::origin::Source { .expect("the peer is admitted"); let mut announced = cluster.origin.consume().announced(); - let (update, _) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, _) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("timed out waiting for forwarded") .expect("origin closed"); @@ -1412,7 +1412,7 @@ async fn an_embedded_decider_admits_and_revokes() { publisher.revoke(moq_auth::lease::Reason::Refused); assert_closed(pub_session, Duration::from_secs(5), "publisher").await; assert!( - moq_clock::timeout(Duration::from_millis(200), sub_session.closed()) + kio::clock::timeout(Duration::from_millis(200), sub_session.closed()) .await .is_err(), "revoking one lease must not close the other session" @@ -1494,20 +1494,20 @@ const EXPIRES: Duration = Duration::from_secs(3); /// Make the test runtime's clock one that only the test moves, wall time included, /// so a grant's life is measured exactly. Call it before anything reads the clock. -fn manual() -> moq_clock::Installed { - moq_clock::Manual::new().install(&tokio::runtime::Handle::current()) +fn manual() -> kio::clock::Installed { + kio::clock::Manual::new().install(&tokio::runtime::Handle::current()) } /// Everything under the dialed path, until [`EXPIRES`] from now on the ambient clock. fn expiring() -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(moq_clock::wall() + EXPIRES); + grant.expires = Some(kio::clock::wall() + EXPIRES); grant } /// Supervise an in-memory session admitted on `consumer`, whose grant nobody renews, /// and assert it closes at exactly [`EXPIRES`] on `clock`. -async fn closes_at_expires(clock: &moq_clock::Installed, consumer: moq_auth::lease::Consumer) { +async fn closes_at_expires(clock: &kio::clock::Installed, consumer: moq_auth::lease::Consumer) { let (auth, mut admissions) = moq_relay::auth::Auth::embedded("test-relay"); let (lease, ()) = tokio::join!(auth.admit(auth.request(moq_auth::Transport::Tcp, "/room")), async { admissions.next().await.expect("an admission").grant(consumer); @@ -1575,7 +1575,7 @@ async fn a_relay_without_an_auth_source_is_decided_by_the_embedder() { drop(sub_session); trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("run returned after the trigger") .expect("relay task panicked") @@ -1619,12 +1619,12 @@ async fn an_unanswered_admission_closes_at_the_handshake_deadline() { tokio::time::resume(); // The close reaches the client over loopback within moments; the old fixed cap // would have held the connection for another eight seconds. - let connecting = moq_clock::timeout(TIMEOUT, connecting) + let connecting = kio::clock::timeout(TIMEOUT, connecting) .await .expect("the client never settled") .expect("client task"); if let Ok(connection) = connecting { - moq_clock::timeout(Duration::from_secs(3), connection.closed()) + kio::clock::timeout(Duration::from_secs(3), connection.closed()) .await .expect("the connection outlived the handshake deadline") .expect_err("closed as refused, not cleanly"); @@ -1633,7 +1633,7 @@ async fn an_unanswered_admission_closes_at_the_handshake_deadline() { drop(admission); trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("run returned after the trigger") .expect("relay task panicked") @@ -1657,14 +1657,14 @@ async fn a_late_decision_within_the_deadline_admits() { tokio::time::advance(wait).await; tokio::time::resume(); admission.grant(moq_auth::lease::Consumer::fixed(grant(Duration::from_secs(3600)))); - let connection = moq_clock::timeout(TIMEOUT, connecting) + let connection = kio::clock::timeout(TIMEOUT, connecting) .await .expect("the late decision never reached the client") .expect("client task") .unwrap_or_else(|err| panic!("{timeout:?}: refused after {wait:?}: {err}")); // Admitted, so the session stays up; a refusal would have closed it by now. assert!( - moq_clock::timeout(Duration::from_secs(1), connection.closed()) + kio::clock::timeout(Duration::from_secs(1), connection.closed()) .await .is_err(), "{timeout:?}: closed after the decision {wait:?} in" @@ -1672,7 +1672,7 @@ async fn a_late_decision_within_the_deadline_admits() { drop(connection); trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("run returned after the trigger") .expect("relay task panicked") @@ -1722,7 +1722,7 @@ async fn quic_and_webtransport_report_distinct_auth_transports() { async fn in_band_tokens_widen_and_withdraw_live_prefixes() { for scheme in ["tcp", "ws"] { let mut initial = Grant::new(all(), "a/**".parse::().unwrap()); - initial.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); + initial.expires = Some(kio::clock::wall() + Duration::from_secs(3600)); let script = Script::new(initial); let auth = build_auth(script.spawn().await); let (port, relay) = if scheme == "tcp" { @@ -1746,7 +1746,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { let b = origin.create_broadcast("b/cam").unwrap(); let b_track = b.create_track("video", timed()).unwrap(); b.announce(Default::default()).unwrap(); - let publisher = moq_clock::timeout( + let publisher = kio::clock::timeout( TIMEOUT, client() .with_publisher(origin.consume()) @@ -1758,7 +1758,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { .unwrap(); let received = moq_tokio::origin::spawn(); let read = received.consume(); - let subscriber = moq_clock::timeout( + let subscriber = kio::clock::timeout( TIMEOUT, client() .with_subscriber(received) @@ -1768,19 +1768,19 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { .await .unwrap() .unwrap(); - let a_read = moq_clock::timeout(TIMEOUT, read.follow("a/cam", None).unwrap().available()) + let a_read = kio::clock::timeout(TIMEOUT, read.follow("a/cam", None).unwrap().available()) .await .unwrap() .unwrap(); let mut a_sub = a_read.track("video").unwrap().subscribe(None).await.unwrap(); let mut replacement = Grant::new(all(), "b/**".parse::().unwrap()); - replacement.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); + replacement.expires = Some(kio::clock::wall() + Duration::from_secs(3600)); script.on_connect(Answer::Grant(replacement)); - let token = moq_clock::timeout(TIMEOUT, subscriber.auth().add("replacement")) + let token = kio::clock::timeout(TIMEOUT, subscriber.auth().add("replacement")) .await .unwrap() .unwrap(); - let b_read = moq_clock::timeout(TIMEOUT, read.follow("b/cam", None).unwrap().available()) + let b_read = kio::clock::timeout(TIMEOUT, read.follow("b/cam", None).unwrap().available()) .await .expect("new prefix not announced") .unwrap(); @@ -1791,14 +1791,14 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { .unwrap(); group.finish().unwrap(); assert!( - moq_clock::timeout(TIMEOUT, b_sub.recv_group()) + kio::clock::timeout(TIMEOUT, b_sub.recv_group()) .await .unwrap() .unwrap() .is_some() ); drop(token); - let ended = moq_clock::timeout(TIMEOUT, b_sub.recv_group()) + let ended = kio::clock::timeout(TIMEOUT, b_sub.recv_group()) .await .expect("withdrawn prefix stayed authorized"); assert!( @@ -1815,7 +1815,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { .unwrap(); group.finish().unwrap(); assert!( - moq_clock::timeout(TIMEOUT, a_sub.recv_group()) + kio::clock::timeout(TIMEOUT, a_sub.recv_group()) .await .unwrap() .unwrap() @@ -1857,20 +1857,20 @@ async fn relay_request_limits_distinguish_clients_and_peers() { .unwrap(); let first = origin.create_broadcast("one").unwrap(); first.announce(Default::default()).unwrap(); - moq_clock::timeout(TIMEOUT, next_update(&mut observed)) + kio::clock::timeout(TIMEOUT, next_update(&mut observed)) .await .unwrap() .unwrap(); let second = origin.create_broadcast("two").unwrap(); second.announce(Default::default()).unwrap(); if peer { - let (route, active) = moq_clock::timeout(TIMEOUT, next_update(&mut observed)) + let (route, active) = kio::clock::timeout(TIMEOUT, next_update(&mut observed)) .await .unwrap() .unwrap(); assert!(active, "the peer must retain its second announcement: {route:?}"); } else { - let error = moq_clock::timeout(TIMEOUT, session.closed()) + let error = kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("the second client announcement exceeds the cap"); assert!( @@ -1920,7 +1920,7 @@ async fn websocket_refusal_is_in_band() { let mut send = session.open_uni(Default::default()).await.expect("open SETUP"); write_all(&mut send, &[1, 1, 0]).await; send.finish().expect("finish SETUP"); - let closed = moq_clock::timeout(TIMEOUT, session.closed()) + let closed = kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("refused session stayed open"); assert_eq!(closed.session_error().map(|(code, _)| code), Some(code.to_code())); @@ -1935,7 +1935,7 @@ async fn websocket_publisher_role_is_refused_by_a_subscribe_only_grant() { let (port, relay) = spawn_ws_relay(build_auth(script.spawn().await)).await; let url = room_url("ws", port); let origin = moq_tokio::origin::spawn(); - let result = moq_clock::timeout( + let result = kio::clock::timeout( TIMEOUT, client() .with_publisher(origin.consume()) @@ -1947,7 +1947,7 @@ async fn websocket_publisher_role_is_refused_by_a_subscribe_only_grant() { .expect("publisher handshake timed out"); let error = match result { - Ok(session) => moq_clock::timeout(TIMEOUT, session.closed()) + Ok(session) => kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("mismatched publisher stayed open") .unwrap_err(), @@ -1970,7 +1970,7 @@ async fn websocket_unauthorized_stops_native_reconnect() { script.on_connect(Answer::Status(401)); let (port, relay) = spawn_ws_relay(build_auth(script.spawn().await)).await; let connection = client().with_reconnect(true).connect(room_url("ws", port)); - let error = moq_clock::timeout(TIMEOUT, connection.closed()) + let error = kio::clock::timeout(TIMEOUT, connection.closed()) .await .expect("unauthorized reconnect loop did not stop") .unwrap_err(); diff --git a/rs/moq-relay/tests/integration/cluster_close.rs b/rs/moq-relay/tests/integration/cluster_close.rs index c7f778a32a3..333b9ad6452 100644 --- a/rs/moq-relay/tests/integration/cluster_close.rs +++ b/rs/moq-relay/tests/integration/cluster_close.rs @@ -37,7 +37,7 @@ fn peer_url(server: &driver::endpoint::Endpoint) -> String { } async fn accept(server: &driver::endpoint::Endpoint) -> driver::connection::Connection { - moq_clock::timeout(TIMEOUT, server.accept()) + kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("dial timeout") .expect("incoming") @@ -49,7 +49,7 @@ async fn accept(server: &driver::endpoint::Endpoint) -> driver::connection::Conn /// The link ends with the dialer's own shutdown close, not a timeout or a SETUP error. async fn assert_closed_by_shutdown(conn: driver::connection::Connection) { - let err = moq_clock::timeout(TIMEOUT, conn.closed()) + let err = kio::clock::timeout(TIMEOUT, conn.closed()) .await .expect("the peer heard no close before its idle timeout"); match err { @@ -108,18 +108,18 @@ async fn closing_a_cluster_ends_its_websocket_dials() { let running = tokio::spawn(started.run()); // Never answers the upgrade, so the dial holds the socket until stopped. - let (mut socket, _) = moq_clock::timeout(TIMEOUT, listener.accept()) + let (mut socket, _) = kio::clock::timeout(TIMEOUT, listener.accept()) .await .expect("dial timeout") .expect("accept"); - moq_clock::timeout(TIMEOUT, cluster.close()) + kio::clock::timeout(TIMEOUT, cluster.close()) .await .expect("close waits on a stopped dial"); let mut buf = vec![0; 4096]; loop { // Brief: the socket is already closed once `close` returns. - let read = moq_clock::timeout(Duration::from_secs(2), socket.read(&mut buf)) + let read = kio::clock::timeout(Duration::from_secs(2), socket.read(&mut buf)) .await .expect("the dial still holds its socket"); if read.map_or(true, |n| n == 0) { @@ -157,7 +157,7 @@ async fn a_relay_shutdown_closes_its_cluster_dials() { let conn = accept(&server).await; trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("relay drain") .expect("relay task") diff --git a/rs/moq-relay/tests/integration/cluster_drain.rs b/rs/moq-relay/tests/integration/cluster_drain.rs index c6ae1f495a9..372f00cb8a7 100644 --- a/rs/moq-relay/tests/integration/cluster_drain.rs +++ b/rs/moq-relay/tests/integration/cluster_drain.rs @@ -136,7 +136,7 @@ async fn peer(name: &str, forwarder: &Forwarder) -> (cluster::Cluster, moq_net:: } /// Advance the manual clock by `total`, one [`STEP`] at a time. -async fn pass(clock: &moq_clock::Installed, total: Duration) { +async fn pass(clock: &kio::clock::Installed, total: Duration) { let mut passed = Duration::ZERO; while passed < total { clock.advance(STEP); @@ -155,7 +155,7 @@ fn draining_relay_keeps_its_peers_until_it_restarts() { } async fn draining_relay_keeps_its_peers_until_it_restarts_inner() { - let clock = moq_clock::Manual::new().install(&tokio::runtime::Handle::current()); + let clock = kio::clock::Manual::new().install(&tokio::runtime::Handle::current()); let (b, b_addr, _b_broadcast) = relay("b").await; let b_origin = b.cluster().origin.clone(); diff --git a/rs/moq-relay/tests/integration/cluster_idle.rs b/rs/moq-relay/tests/integration/cluster_idle.rs index ca8f1b09923..b8f45590034 100644 --- a/rs/moq-relay/tests/integration/cluster_idle.rs +++ b/rs/moq-relay/tests/integration/cluster_idle.rs @@ -7,7 +7,7 @@ use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_relay::cluster::{self, Peer}; /// The dial's idle timeout. QUIC uses the smaller of both ends', so the peer's @@ -77,7 +77,7 @@ async fn spawn_peer() -> (u16, tokio::runtime::Runtime) { drop(broadcast); }); - let port = moq_clock::timeout(DETECT, port) + let port = kio::clock::timeout(DETECT, port) .await .expect("peer startup timed out") .expect("peer failed to start"); @@ -113,7 +113,7 @@ async fn silent_peer_detected() { let mut announced = cluster.origin.consume().announced(); let run = tokio::spawn(cluster.clone().start().await.expect("cluster start").run()); - moq_clock::timeout(DETECT, async { + kio::clock::timeout(DETECT, async { loop { let event = announced.next().await.expect("origin closed"); if let moq_net::announce::Event::Start(update) | moq_net::announce::Event::Update(update) = event @@ -131,7 +131,7 @@ async fn silent_peer_detected() { .expect("peer shutdown panicked"); let silenced = Instant::now(); - moq_clock::timeout(DETECT, async { + kio::clock::timeout(DETECT, async { loop { let event = announced.next().await.expect("origin closed"); if let moq_net::announce::Event::End(update) = event diff --git a/rs/moq-relay/tests/integration/cluster_unknown.rs b/rs/moq-relay/tests/integration/cluster_unknown.rs index 73f4986cb94..97a27d7ee4f 100644 --- a/rs/moq-relay/tests/integration/cluster_unknown.rs +++ b/rs/moq-relay/tests/integration/cluster_unknown.rs @@ -56,7 +56,7 @@ async fn spawn_relay(id: u64, connect: Vec, cluster_version: Option Publisher { if group.finish().is_err() { break; } - moq_clock::sleep(Duration::from_millis(100)).await; + kio::clock::sleep(Duration::from_millis(100)).await; } }) .abort_handle(); let version = version.parse().expect("parse version"); - let session = moq_clock::timeout( + let session = kio::clock::timeout( TIMEOUT, client(Some(version)).with_publisher(&origin).connect(url).established(), ) @@ -201,7 +201,7 @@ async fn read_first_frame(port: u16) -> Result, String> { let url: Url = format!("tcp://127.0.0.1:{port}").parse().expect("parse url"); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); - let session = moq_clock::timeout(TIMEOUT, client(None).with_subscriber(origin).connect(url).established()) + let session = kio::clock::timeout(TIMEOUT, client(None).with_subscriber(origin).connect(url).established()) .await .map_err(|_| "subscriber connect timeout".to_string())? .map_err(|err| format!("subscriber connect failed: {err}"))?; @@ -220,7 +220,7 @@ async fn read_first_frame(port: u16) -> Result, String> { // every hop enough tolerance for the next 100ms group to arrive while the // selected group's frame is still crossing the redundant mesh. let subscription = moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1)); - let mut track = moq_clock::timeout( + let mut track = kio::clock::timeout( TIMEOUT, broadcast.track("video").expect("track handle").subscribe(subscription), ) @@ -228,13 +228,13 @@ async fn read_first_frame(port: u16) -> Result, String> { .map_err(|_| "subscribe timed out".to_string())? .map_err(|err| format!("subscribe failed: {err}"))?; - let mut group = moq_clock::timeout(TIMEOUT, track.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .map_err(|_| "recv_group timed out".to_string())? .map_err(|err| format!("recv_group failed: {err}"))? .ok_or_else(|| "track closed before a group arrived".to_string())?; - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .map_err(|_| "read_frame timed out".to_string())? .map_err(|err| format!("read_frame failed: {err}"))? @@ -255,7 +255,7 @@ async fn watch_announces( let url: Url = format!("tcp://127.0.0.1:{port}").parse().expect("parse url"); let origin = moq_tokio::origin::spawn(); let mut announced = origin.consume().announced(); - let session = moq_clock::timeout(TIMEOUT, client(None).with_subscriber(origin).connect(url).established()) + let session = kio::clock::timeout(TIMEOUT, client(None).with_subscriber(origin).connect(url).established()) .await .expect("viewer connect timeout") .expect("viewer connect failed"); @@ -287,7 +287,7 @@ async fn assert_unknown_publisher_stays_announced(cluster_version: Option String { loop { - match moq_clock::timeout(TIMEOUT, announced.next()) + match kio::clock::timeout(TIMEOUT, announced.next()) .await .expect("announcement timeout") .expect("origin closed") @@ -111,7 +111,7 @@ async fn next_active(announced: &mut moq_net::announce::Consumer) -> String { /// was answered first. async fn assert_refused(result: Result) { let err = match result { - Ok(session) => moq_clock::timeout(TIMEOUT, session.closed()) + Ok(session) => kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("the relay must close a refused session, not leave it open"), Err(err) => err, @@ -139,7 +139,7 @@ async fn subscribe_only_public_accepts_subscriber_role() { .await .expect("subscriber connects"); assert!( - moq_clock::timeout(TIMEOUT, session.closed()).await.is_err(), + kio::clock::timeout(TIMEOUT, session.closed()).await.is_err(), "subscribe-only relay should keep a subscriber session open" ); } @@ -245,7 +245,7 @@ async fn the_setup_path_reaches_the_decider_and_roots_the_grant() { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, track.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("group timeout") .expect("recv group") @@ -287,7 +287,7 @@ async fn stats_count_admitted_and_refused_sessions() { let session = connect(client, newest(), &cluster, &auth) .await .expect("subscriber connects"); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while presence().active() != 1 { tokio::task::yield_now().await; } @@ -301,7 +301,7 @@ async fn stats_count_admitted_and_refused_sessions() { assert_eq!(presence().sessions_refused.forbidden, 1); drop(session); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { while presence().active() != 0 { tokio::task::yield_now().await; } diff --git a/rs/moq-relay/tests/integration/drain.rs b/rs/moq-relay/tests/integration/drain.rs index d70b07eeea4..ef54ceaba40 100644 --- a/rs/moq-relay/tests/integration/drain.rs +++ b/rs/moq-relay/tests/integration/drain.rs @@ -79,7 +79,7 @@ async fn admit(observer: &shutdown::Observer, version: moq_net::Version, stalled // Paused time advances only once every task is idle, so the relay is // supervising the session by the time this returns. - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert!( lease.closed().now_or_never().is_none(), "the session ended before the drain" @@ -102,10 +102,10 @@ async fn a_session_ignoring_the_goaway_is_closed_at_the_deadline() { for alpn in ["moq-lite-06", "moq-lite-03", "moq-transport-18"] { let (trigger, observer) = shutdown::Observer::new(WINDOW); let session = admit(&observer, alpn.parse().unwrap(), false).await; - let started = moq_clock::now(); + let started = kio::clock::now(); let drained = drain(&trigger, &observer); - moq_clock::timeout(WINDOW + Duration::from_secs(1), drained) + kio::clock::timeout(WINDOW + Duration::from_secs(1), drained) .await .unwrap_or_else(|_| panic!("{alpn}: the drain outlived its deadline")) .unwrap(); @@ -135,7 +135,7 @@ async fn a_stalled_goaway_write_is_still_closed_at_the_deadline() { let session = admit(&observer, "moq-lite-06".parse().unwrap(), true).await; let drained = drain(&trigger, &observer); - moq_clock::timeout(WINDOW + Duration::from_secs(1), drained) + kio::clock::timeout(WINDOW + Duration::from_secs(1), drained) .await .expect("a stalled GOAWAY held the drain past its deadline") .unwrap(); diff --git a/rs/moq-relay/tests/integration/embed.rs b/rs/moq-relay/tests/integration/embed.rs index 1619754bf34..005f8ff41bf 100644 --- a/rs/moq-relay/tests/integration/embed.rs +++ b/rs/moq-relay/tests/integration/embed.rs @@ -56,7 +56,7 @@ async fn assert_owner_stopped(quic: SocketAddr, http: SocketAddr) { // listener answers a loopback handshake well inside it, and on Linux the // socket check before this is what proves the port closed. let url: url::Url = format!("https://{quic}/").parse().expect("parse url"); - let after = moq_clock::timeout( + let after = kio::clock::timeout( Duration::from_millis(500), client().with_reconnect(false).connect(url).established(), ) @@ -139,7 +139,7 @@ fn open_sockets() -> std::collections::HashSet { /// worker thread and listener goes through, as opposed to aborting the task. async fn stop(trigger: moq_relay::shutdown::Trigger, running: tokio::task::JoinHandle>) { trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("run did not return after the shutdown trigger") .expect("run panicked") @@ -275,7 +275,7 @@ async fn embed_and_stop(mut config: Config) { let subscriber_origin = moq_tokio::origin::spawn(); let consumer = subscriber_origin.consume(); let mut announced = consumer.announced(); - let subscriber = moq_clock::timeout( + let subscriber = kio::clock::timeout( TIMEOUT, client() .with_reconnect(false) @@ -287,13 +287,13 @@ async fn embed_and_stop(mut config: Config) { .expect("connect timeout") .expect("connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("announcement timeout") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let announced = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let announced = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .expect("request timeout") .expect("announced broadcast resolves"); @@ -303,12 +303,12 @@ async fn embed_and_stop(mut config: Config) { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, subscription.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscription.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") diff --git a/rs/moq-relay/tests/integration/goaway_cluster.rs b/rs/moq-relay/tests/integration/goaway_cluster.rs index 9717a959997..deeeeb88da6 100644 --- a/rs/moq-relay/tests/integration/goaway_cluster.rs +++ b/rs/moq-relay/tests/integration/goaway_cluster.rs @@ -34,7 +34,7 @@ const HANDOVER: Duration = Duration::from_secs(1); /// Bound `fut` by [`TEST_TIMEOUT`], panicking with `step` so a hang names the /// exact stage that failed instead of a bare "test timed out". async fn within(step: &str, fut: impl std::future::Future) -> T { - moq_clock::timeout(TEST_TIMEOUT, fut) + kio::clock::timeout(TEST_TIMEOUT, fut) .await .unwrap_or_else(|_| panic!("timed out: {step}")) } @@ -286,7 +286,7 @@ async fn spawn_upstream( async fn cluster_migrates_on_upstream_goaway_inner() { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { // ── the shared "live" broadcast both siblings can serve ───────── let upstream_origin = moq_tokio::origin::spawn(); let broadcast = upstream_origin.create_broadcast("cam").expect("create broadcast"); @@ -383,7 +383,7 @@ async fn cluster_migrates_on_upstream_goaway_inner() { // updates (the drain re-pricing, the sibling's route) are expected and // harmless; an inactive event means the path flapped. loop { - match moq_clock::timeout(Duration::from_millis(500), next_update(&mut announcements)).await { + match kio::clock::timeout(Duration::from_millis(500), next_update(&mut announcements)).await { Err(_) => break, Ok(Some((_, true))) => continue, Ok(event) => panic!("migration must not retract the path on the cluster origin: {event:?}"), @@ -612,7 +612,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { .expect("write frame"); } g.finish().expect("finish"); - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } // Hand the track back so the post-drain phase can keep publishing. track @@ -667,7 +667,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { .expect("write frame"); } g.finish().expect("finish"); - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } }); @@ -697,7 +697,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { // The async observer must stay pending too (bounded probe: everything // above already synchronized, so 500ms of silence is decisive). let draining = sub_connection.draining().expect("connected"); - let leaked = moq_clock::timeout( + let leaked = kio::clock::timeout( Duration::from_millis(500), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -710,7 +710,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { // ── announcement stability: the path never retracted under the swap ── // Metadata updates (route re-pricing, the new leg's hops) are expected. loop { - match moq_clock::timeout(Duration::from_millis(500), next_update(&mut announcements)).await { + match kio::clock::timeout(Duration::from_millis(500), next_update(&mut announcements)).await { Err(_) => break, Ok(Some((_, true))) => continue, Ok(event) => panic!("failover must not retract the path under the subscriber: {event:?}"), @@ -823,7 +823,7 @@ async fn goaway_handover_is_enforced_while_the_replacement_dial_hangs_inner() { // Clear the healthy bar, so the GOAWAY continues straight into the replacement // dial rather than sleeping first. - moq_clock::sleep(Duration::from_millis(120)).await; + kio::clock::sleep(Duration::from_millis(120)).await; // Send the client somewhere that will never finish handshaking. No wire timeout: // our own `--connect-goaway-handover` is then the only thing bounding the old session. @@ -837,8 +837,8 @@ async fn goaway_handover_is_enforced_while_the_replacement_dial_hangs_inner() { // The predecessor must close on its own deadline, not whenever that dial gives // up. The bound is generous against a loaded runner but far below the seconds a // hanging handshake takes, which is the gap being measured. - let sent = moq_clock::now(); - let closed = moq_clock::timeout(handover * 10, server_session.closed()).await; + let sent = kio::clock::now(); + let closed = kio::clock::timeout(handover * 10, server_session.closed()).await; let elapsed = sent.elapsed(); assert!( closed.is_ok() && elapsed < handover * 5, diff --git a/rs/moq-relay/tests/integration/hidden_cluster.rs b/rs/moq-relay/tests/integration/hidden_cluster.rs index d75fc333683..de66627b93d 100644 --- a/rs/moq-relay/tests/integration/hidden_cluster.rs +++ b/rs/moq-relay/tests/integration/hidden_cluster.rs @@ -51,7 +51,7 @@ fn old_peers_keep_hidden_paths() { async fn old_peer_keeps_hidden_paths(version: moq_net::Version) { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - moq_clock::timeout(TEST_TIMEOUT, async { + kio::clock::timeout(TEST_TIMEOUT, async { let (port, mut server) = listen_tcp(version).await; let peer_origin = moq_tokio::origin::spawn(); let mut discovered = peer_origin.consume().with_hidden(true).announced(); diff --git a/rs/moq-relay/tests/integration/implementation.rs b/rs/moq-relay/tests/integration/implementation.rs index e8fa32ce38a..07e9e7238b8 100644 --- a/rs/moq-relay/tests/integration/implementation.rs +++ b/rs/moq-relay/tests/integration/implementation.rs @@ -31,7 +31,7 @@ async fn spawn_relay(set: impl FnOnce(&mut Config)) -> (u16, moq_relay::auth::Ad /// Admit the next session, returning the implementation its auth request carried. async fn admit_next(admissions: &mut moq_relay::auth::Admissions) -> Option { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()) + let admission = kio::clock::timeout(TIMEOUT, admissions.next()) .await .expect("admission timeout") .expect("admission"); @@ -75,7 +75,7 @@ async fn the_relay_and_client_exchange_implementations() { Some("app/1 moq-net-rs/9"), "{configured:?}" ); - let seen = moq_clock::timeout(TIMEOUT, session.peer_implementation()) + let seen = kio::clock::timeout(TIMEOUT, session.peer_implementation()) .await .expect("relay SETUP timeout"); assert_eq!(seen, expected, "{configured:?}"); diff --git a/rs/moq-relay/tests/integration/lan_mesh.rs b/rs/moq-relay/tests/integration/lan_mesh.rs index 65c23e5c8c9..c11707d6829 100644 --- a/rs/moq-relay/tests/integration/lan_mesh.rs +++ b/rs/moq-relay/tests/integration/lan_mesh.rs @@ -54,7 +54,7 @@ async fn moq_import_cluster_lan_beside_a_relay() { .with_connect(connect, Default::default()) .with_advertise(cluster::LanAdvertise::new(port).with_fingerprint(fingerprint)); - match moq_clock::timeout(Duration::from_secs(10), cluster.start()).await { + match kio::clock::timeout(Duration::from_secs(10), cluster.start()).await { Ok(Ok(_)) => {} Ok(Err(err)) if format!("{err:#}").contains("no network interface") && std::env::var_os("CI_STRICT").is_none() => diff --git a/rs/moq-relay/tests/integration/peer_limits.rs b/rs/moq-relay/tests/integration/peer_limits.rs index 820f34c9f54..c71d7cdd147 100644 --- a/rs/moq-relay/tests/integration/peer_limits.rs +++ b/rs/moq-relay/tests/integration/peer_limits.rs @@ -80,7 +80,7 @@ async fn probe(port: u16, peer: bool) -> Seen { // The relay widens a peer before it answers SETUP, so its SETUP stream // arrives behind the new credit. - let _setup = moq_clock::timeout(TIMEOUT, conn.accept_uni()) + let _setup = kio::clock::timeout(TIMEOUT, conn.accept_uni()) .await .expect("relay SETUP timeout") .expect("relay SETUP"); @@ -89,7 +89,7 @@ async fn probe(port: u16, peer: bool) -> Seen { while streams.len() < PROBE { let open = conn.open_uni(Default::default()); let stream = match peer { - true => moq_clock::timeout(TIMEOUT, open) + true => kio::clock::timeout(TIMEOUT, open) .await .expect("peer stream credit timeout"), false => match open.now_or_never() { @@ -115,7 +115,7 @@ async fn peer_widens_and_viewer_does_not(mut relay: Relay, port: u16) { let deciding = tokio::spawn(async move { let mut leases = Vec::new(); for peer in [true, false] { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()) + let admission = kio::clock::timeout(TIMEOUT, admissions.next()) .await .expect("admission timeout") .expect("admission"); @@ -265,7 +265,7 @@ async fn static_dial( .expect("cluster init") .with_connect(connect, quic); let running = tokio::spawn(cluster.start().await.expect("cluster start").run()); - let conn = moq_clock::timeout(TIMEOUT, server.accept()) + let conn = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("dial timeout") .expect("incoming") diff --git a/rs/moq-relay/tests/integration/public_rules.rs b/rs/moq-relay/tests/integration/public_rules.rs index 2b0ed692b18..9add0d508dc 100644 --- a/rs/moq-relay/tests/integration/public_rules.rs +++ b/rs/moq-relay/tests/integration/public_rules.rs @@ -77,7 +77,7 @@ async fn publish(url: url::Url, name: &str) -> Box { group .write_frame(moq_net::Timestamp::ZERO, b"hello".as_ref()) .expect("write frame"); - let session = moq_clock::timeout( + let session = kio::clock::timeout( TIMEOUT, client() .with_publisher(origin.consume()) @@ -97,7 +97,7 @@ async fn first_broadcast(url: url::Url) -> String { let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let mut announcements = consumer.announced(); - let _session = moq_clock::timeout( + let _session = kio::clock::timeout( TIMEOUT, client() .with_subscriber(origin) @@ -109,7 +109,7 @@ async fn first_broadcast(url: url::Url) -> String { .expect("subscriber connect timeout") .expect("subscriber connect failed"); - let update = moq_clock::timeout(TIMEOUT, async { + let update = kio::clock::timeout(TIMEOUT, async { match announcements.next().await.expect("origin closed") { moq_net::announce::Event::Start(update) => update, other => panic!("expected announce, got {other:?}"), @@ -126,12 +126,12 @@ async fn first_broadcast(url: url::Url) -> String { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, track.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("group timeout") .expect("group failed") .expect("track closed"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("frame timeout") .expect("frame failed") @@ -144,7 +144,7 @@ async fn first_broadcast(url: url::Url) -> String { /// handshake before the verdict, so an established one has to close right away. async fn assert_refused(url: url::Url) { let origin = moq_tokio::origin::spawn(); - let result = moq_clock::timeout( + let result = kio::clock::timeout( TIMEOUT, client() .with_subscriber(origin) @@ -155,7 +155,7 @@ async fn assert_refused(url: url::Url) { .await .expect("connect timeout"); if let Ok(session) = result { - let closed = moq_clock::timeout(Duration::from_secs(3), session.closed()) + let closed = kio::clock::timeout(Duration::from_secs(3), session.closed()) .await .unwrap_or_else(|_| panic!("the relay admitted {url}")); assert!(closed.is_err(), "a refused session at {url} closed cleanly"); @@ -211,7 +211,7 @@ async fn http_routes_follow_the_anon_rules() { let mut fetch = get("/fetch/anon/bbb/cam/video").await.expect("fetch request"); assert_eq!(fetch.status(), 200); - let first = moq_clock::timeout(TIMEOUT, fetch.chunk()) + let first = kio::clock::timeout(TIMEOUT, fetch.chunk()) .await .expect("fetch timeout") .expect("fetch body") diff --git a/rs/moq-relay/tests/integration/refusals.rs b/rs/moq-relay/tests/integration/refusals.rs index 94eea048f55..79694d2004d 100644 --- a/rs/moq-relay/tests/integration/refusals.rs +++ b/rs/moq-relay/tests/integration/refusals.rs @@ -78,7 +78,7 @@ async fn start(config: Config) -> Running { impl Running { async fn stop(self) { self.trigger.start(); - moq_clock::timeout(TIMEOUT, self.running) + kio::clock::timeout(TIMEOUT, self.running) .await .expect("run did not return after the shutdown trigger") .expect("run panicked") @@ -121,12 +121,12 @@ async fn assert_refused(url: url::Url, publisher: bool) { true => client().with_publisher(origin.consume()), false => client().with_subscriber(origin), }; - let connected = moq_clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) + let connected = kio::clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) .await .expect("connect timeout"); if let Ok(session) = connected { // How it closed does not matter here; /metrics says why. - let _ = moq_clock::timeout(TIMEOUT, session.closed()) + let _ = kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("the relay kept a session it should refuse"); } @@ -244,7 +244,7 @@ async fn refused_only_stats_depth_one_has_root_totals_and_shared_embedder_metric 1, "native admission counts exactly once" ); - let broadcast = moq_clock::timeout( + let broadcast = kio::clock::timeout( TIMEOUT, relay.origin.follow(".stats/node/test", None).unwrap().available(), ) @@ -253,7 +253,7 @@ async fn refused_only_stats_depth_one_has_root_totals_and_shared_embedder_metric .unwrap(); let consumer = moq_stats::Consumer::new(broadcast, Default::default()); let mut totals = consumer.totals().await.unwrap(); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { let frame = totals.next().await.unwrap().unwrap(); if frame @@ -275,7 +275,7 @@ async fn refused_only_stats_depth_one_has_root_totals_and_shared_embedder_metric 1, "embedder stats and metrics share the counter" ); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { let frame = totals.next().await.unwrap().unwrap(); if frame @@ -318,7 +318,7 @@ async fn peer_zero_close_is_clean_and_application_close_counts_once() { .connect(format!("https://{}/", relay.quic).parse::().unwrap()); let session = connection.established().await.unwrap(); session.abort(error); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { let frame = totals.next().await.unwrap().unwrap(); if let Some(total) = frame.get("") @@ -376,7 +376,7 @@ async fn expired_verified_tokens_count_under_the_token_root_and_auth_tier() { let mut claims = moq_auth::Claims::default() .with_root("verified/tenant") .with_subscribe([moq_auth::Pattern::all()]); - claims.expires = Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); + claims.expires = Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); let token = key.sign(&claims).unwrap(); for tier in [None, Some("edge")] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -481,7 +481,7 @@ async fn uri_setup_paths(io_uring: bool) { Some("/admin?jwt=setup-token"), None, ] { - let peer = moq_clock::timeout(TIMEOUT, web_peer(addr, version.alpn())) + let peer = kio::clock::timeout(TIMEOUT, web_peer(addr, version.alpn())) .await .unwrap(); // Minimal SETUP: lite has a parameter count and varint size; IETF has @@ -507,7 +507,7 @@ async fn uri_setup_paths(io_uring: bool) { setup.finish().unwrap(); } if path.is_some() { - let error = moq_clock::timeout(TIMEOUT, async { + let error = kio::clock::timeout(TIMEOUT, async { tokio::select! { error = peer.closed() => error, _ = admissions.next() => panic!("{version} admitted SETUP Path {path:?}"), @@ -520,7 +520,7 @@ async fn uri_setup_paths(io_uring: bool) { "{version}, {path:?}: {error:?}" ); } else { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); + let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); assert_eq!(admission.request.path, "/room", "{version}"); assert_eq!(admission.request.query.as_deref(), Some("jwt=url-token"), "{version}"); // A valid request reached authorization; no session needs to start. @@ -529,7 +529,7 @@ async fn uri_setup_paths(io_uring: bool) { } } trigger.start(); - moq_clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); } #[tokio::test] diff --git a/rs/moq-relay/tests/integration/runtime_uring.rs b/rs/moq-relay/tests/integration/runtime_uring.rs index 988a171ea5a..58402647b82 100644 --- a/rs/moq-relay/tests/integration/runtime_uring.rs +++ b/rs/moq-relay/tests/integration/runtime_uring.rs @@ -99,7 +99,7 @@ fn client() -> moq_tokio::Client { } async fn connect(client: moq_tokio::Client, url: url::Url) -> moq_tokio::Connection { - moq_clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) + kio::clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) .await .expect("connect timeout") .expect("connect failed") @@ -156,13 +156,13 @@ async fn uring_workers_serve_webtransport_and_raw_quic() { } for (index, (_connection, consumer, announced)) in subscribers.iter_mut().enumerate() { - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(announced)) .await .unwrap_or_else(|_| panic!("subscriber {index} announcement timeout")) .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .unwrap_or_else(|_| panic!("subscriber {index} request timeout")) .expect("announced broadcast resolves"); @@ -173,12 +173,12 @@ async fn uring_workers_serve_webtransport_and_raw_quic() { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, subscription.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscription.recv_group()) .await .unwrap_or_else(|_| panic!("subscriber {index} recv_group timeout")) .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("subscriber {index} read_frame timeout")) .expect("read_frame failed") @@ -260,14 +260,14 @@ async fn uring_workers_serve_every_configured_version() { let connection = connect(client.with_subscriber(origin), url).await; assert_eq!(connection.version(), Some(version), "{scheme} {name}"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .unwrap_or_else(|_| panic!("{scheme} {name}: announcement timeout")) .expect("origin closed"); // moq-lite-02 has no in-band path, so a raw QUIC session sits at the root. let path = update.prefix.as_str().to_owned(); assert!(active && path.ends_with("test"), "{scheme} {name}: announced {path}"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request(&path, None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request(&path, None)) .await .unwrap_or_else(|_| panic!("{scheme} {name}: request timeout")) .expect("announced broadcast resolves"); @@ -277,12 +277,12 @@ async fn uring_workers_serve_every_configured_version() { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, subscription.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscription.recv_group()) .await .unwrap_or_else(|_| panic!("{scheme} {name}: recv_group timeout")) .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("{scheme} {name}: read_frame timeout")) .expect("read_frame failed") @@ -330,14 +330,14 @@ async fn uring_workers_report_link_facts() { } // A client can see its session established before the relay lists it. - let deadline = moq_clock::now() + TIMEOUT; + let deadline = kio::clock::now() + TIMEOUT; let views = loop { let views = sessions.list(&Default::default()); if views.len() == 4 { break views; } - assert!(moq_clock::now() < deadline, "expected 4 sessions: {views:?}"); - moq_clock::sleep(Duration::from_millis(25)).await; + assert!(kio::clock::now() < deadline, "expected 4 sessions: {views:?}"); + kio::clock::sleep(Duration::from_millis(25)).await; }; for view in &views { let remote = view.remote.expect("peer address"); @@ -400,12 +400,12 @@ async fn uring_workers_drain_on_the_trigger() { let pending = admissions.next().await.expect("pending admission"); trigger.start(); let draining = established.draining().expect("connected"); - let goaway = moq_clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) + let goaway = kio::clock::timeout(TIMEOUT, moq_net::kio::wait(|waiter| draining.poll(waiter))) .await .expect("no GOAWAY after the trigger") .expect("session closed without a GOAWAY"); assert_eq!(goaway.uri(), "", "expected a reconnect-to-me GOAWAY"); - moq_clock::timeout(TIMEOUT, established.closed()) + kio::clock::timeout(TIMEOUT, established.closed()) .await .expect("the drained session never closed") .expect("a one-shot session leaves cleanly on GOAWAY"); @@ -414,7 +414,7 @@ async fn uring_workers_drain_on_the_trigger() { pending.grant(arrival_consumer); let arrival = arriving.await.expect("arrival task"); let draining = arrival.draining().expect("connected"); - let goaway = moq_clock::timeout( + let goaway = kio::clock::timeout( Duration::from_secs(1), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -422,14 +422,14 @@ async fn uring_workers_drain_on_the_trigger() { .expect("an arrival mid-drain was not sent a GOAWAY") .expect("arrival closed without a GOAWAY"); assert_eq!(goaway.uri(), "", "expected a reconnect-to-me GOAWAY"); - moq_clock::timeout(TIMEOUT, arrival.closed()) + kio::clock::timeout(TIMEOUT, arrival.closed()) .await .expect("the arrival never closed") .expect("a one-shot session leaves cleanly on GOAWAY"); // `run` joins the worker threads before returning, so returning at all is // the clean join; the rebind proves every worker let go of the port. - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("run did not return after the drain window") .expect("run panicked") @@ -475,7 +475,7 @@ async fn workers_publish_their_rotated_certificate_fingerprint() { let routes = relay.web().routes(); let serving = tokio::spawn(async move { axum::serve(listener, routes).await }); let running = tokio::spawn(relay.run()); - let result = moq_clock::timeout(TIMEOUT, async { + let result = kio::clock::timeout(TIMEOUT, async { for rotated in [false, true] { if rotated { let replacement = tempfile::tempdir_in(dir.path()).expect("replacement directory"); @@ -507,7 +507,7 @@ async fn workers_publish_their_rotated_certificate_fingerprint() { }) .await; trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("relay shutdown") .expect("relay task") @@ -552,7 +552,7 @@ async fn workers_share_a_generated_identity() { let connection = connect(dial.init(Default::default()).unwrap().with_reconnect(false), url).await; drop(connection); trigger.start(); - moq_clock::timeout(TIMEOUT, running) + kio::clock::timeout(TIMEOUT, running) .await .expect("relay shutdown") .expect("relay task") @@ -619,13 +619,13 @@ async fn an_mtls_client_authenticates_without_a_token() { let mut announced = consumer.announced(); let subscriber = connect(client().with_subscriber(subscriber_origin), url).await; - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("announcement timeout") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let announced = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let announced = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .expect("request timeout") .expect("announced broadcast resolves"); @@ -635,12 +635,12 @@ async fn an_mtls_client_authenticates_without_a_token() { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, subscription.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscription.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -697,7 +697,7 @@ async fn uring_workers_write_qlog_traces() { let consumer = subscriber_origin.consume(); let mut announced = consumer.announced(); let subscriber = connect(client().with_subscriber(subscriber_origin), url).await; - let (_, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (_, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("announcement timeout") .expect("origin closed"); @@ -713,7 +713,7 @@ async fn uring_workers_write_qlog_traces() { running.abort(); let _ = running.await; - let written = moq_clock::timeout(TIMEOUT, async { + let written = kio::clock::timeout(TIMEOUT, async { loop { let files: Vec<_> = std::fs::read_dir(&traces) .expect("read qlog dir") @@ -723,7 +723,7 @@ async fn uring_workers_write_qlog_traces() { if !files.is_empty() { return files; } - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } }) .await @@ -773,14 +773,14 @@ async fn uring_refusals_reach_metrics() { (2, format!("moql://127.0.0.1:{port}/rooms")), ] { let url: url::Url = url.parse().expect("parse url"); - let connected = moq_clock::timeout( + let connected = kio::clock::timeout( TIMEOUT, client().with_reconnect(false).connect(url.clone()).established(), ) .await .expect("connect timeout"); if let Ok(connection) = connected { - let _ = moq_clock::timeout(TIMEOUT, connection.closed()) + let _ = kio::clock::timeout(TIMEOUT, connection.closed()) .await .expect("the workers kept a session they should refuse"); } @@ -858,7 +858,7 @@ async fn uring_forwards_the_setup_token() { let expected = token.clone(); let deciding = tokio::spawn(async move { for transport in [moq_auth::Transport::Quic, moq_auth::Transport::WebTransport] { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); + let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); assert_eq!(admission.request.token, Some(expected.clone())); assert_eq!(admission.request.transport, transport); if transport == moq_auth::Transport::WebTransport { @@ -908,13 +908,13 @@ async fn uring_forwards_the_setup_token() { let setup = [&[0xaf, 0x00][..], &(params.len() as u16).to_be_bytes(), ¶ms].concat(); let mut send = session.open_uni(Default::default()).await.unwrap(); send.write_all(&setup[..]).await.unwrap(); - let mut recv = moq_clock::timeout(TIMEOUT, session.accept_uni()) + let mut recv = kio::clock::timeout(TIMEOUT, session.accept_uni()) .await .unwrap() .unwrap(); let mut reply = [0u8; 1]; assert_eq!( - moq_clock::timeout(TIMEOUT, recv.read(&mut &mut reply[..])) + kio::clock::timeout(TIMEOUT, recv.read(&mut &mut reply[..])) .await .unwrap() .unwrap(), @@ -945,7 +945,7 @@ async fn uring_auth_reports_distinct_quic_and_webtransport() { let deciding = tokio::spawn(async move { let mut leases = Vec::new(); for expected in ["quic", "webtransport"] { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); + let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); let actual = admission.request.transport.as_str(); assert!( admission @@ -1005,17 +1005,17 @@ async fn uring_workers_offer_the_configured_extensions() { let client = dial.init(Default::default()).unwrap(); let url = format!("moql://127.0.0.1:{port}/extensions").parse().unwrap(); let (connection, ()) = tokio::join!(connect(client, url), async { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); + let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); assert!(!admission.attached(), "offered {offered}: the session arrived attached"); admission.grant(grant()); }); let auth = connection.auth(); - let presented = moq_clock::timeout(TIMEOUT, auth.add("token")); + let presented = kio::clock::timeout(TIMEOUT, auth.add("token")); match offered { true => { let (token, ()) = tokio::join!(presented, async { - let admission = moq_clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); + let admission = kio::clock::timeout(TIMEOUT, admissions.next()).await.unwrap().unwrap(); assert!(admission.attached(), "an AUTH token arrived as a new session"); admission.grant(grant()); }); @@ -1063,7 +1063,7 @@ fn uring_workers_bound_stalled_handshakes() { .enable_all() .build() .expect("runtime"); - let clock = moq_clock::Manual::new().install(runtime.handle()); + let clock = kio::clock::Manual::new().install(runtime.handle()); runtime.block_on(async move { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -1203,7 +1203,7 @@ async fn uring_sessions_log_their_close_under_a_connection_span() { for (id, scheme) in ["moql", "https"].into_iter().enumerate() { let url = format!("{scheme}://127.0.0.1:{port}/logs").parse().unwrap(); connections.push(connect(client(), url).await); - moq_clock::timeout(TIMEOUT, logs.wait_for(&format!("conn{{id={id} "))) + kio::clock::timeout(TIMEOUT, logs.wait_for(&format!("conn{{id={id} "))) .await .expect("negotiated log missing"); } @@ -1213,9 +1213,9 @@ async fn uring_sessions_log_their_close_under_a_connection_span() { for connection in connections { let _ = connection.close().await; } - moq_clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); for id in 0..2 { - moq_clock::timeout(TIMEOUT, logs.wait_for(&format!("connection closed id={id}"))) + kio::clock::timeout(TIMEOUT, logs.wait_for(&format!("connection closed id={id}"))) .await .unwrap_or_else(|_| panic!("conn {id} never logged its close: {}", logs.text())); } diff --git a/rs/moq-relay/tests/integration/runtime_workers.rs b/rs/moq-relay/tests/integration/runtime_workers.rs index 2c32d98c2c0..d37757ac5f8 100644 --- a/rs/moq-relay/tests/integration/runtime_workers.rs +++ b/rs/moq-relay/tests/integration/runtime_workers.rs @@ -58,7 +58,7 @@ fn client() -> moq_tokio::Client { } async fn connect(client: moq_tokio::Client, url: url::Url) -> moq_tokio::Connection { - moq_clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) + kio::clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) .await .expect("connect timeout") .expect("connect failed") @@ -111,13 +111,13 @@ async fn workers_serve_quic_and_share_one_origin() { } for (index, (_connection, consumer, announced)) in subscribers.iter_mut().enumerate() { - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(announced)) .await .unwrap_or_else(|_| panic!("subscriber {index} announcement timeout")) .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .unwrap_or_else(|_| panic!("subscriber {index} request timeout")) .expect("announced broadcast resolves"); @@ -128,12 +128,12 @@ async fn workers_serve_quic_and_share_one_origin() { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, subscription.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, subscription.recv_group()) .await .unwrap_or_else(|_| panic!("subscriber {index} recv_group timeout")) .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("subscriber {index} read_frame timeout")) .expect("read_frame failed") diff --git a/rs/moq-relay/tests/integration/session_revalidate.rs b/rs/moq-relay/tests/integration/session_revalidate.rs index 838f14085cc..838ec78f536 100644 --- a/rs/moq-relay/tests/integration/session_revalidate.rs +++ b/rs/moq-relay/tests/integration/session_revalidate.rs @@ -99,7 +99,7 @@ fn all() -> Patterns { /// A grant that lasts an hour and would not re-check on its own during a test. fn grant() -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); + grant.expires = Some(kio::clock::wall() + Duration::from_secs(3600)); grant.revalidate = Some(Duration::from_secs(3600)); grant } @@ -251,7 +251,7 @@ fn client_at(bind: &str) -> moq_tokio::Client { } async fn connect(url: url::Url, bind: &str) -> moq_tokio::Connection { - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, client_at(bind) .with_subscriber(moq_tokio::origin::spawn()) @@ -265,7 +265,7 @@ async fn connect(url: url::Url, bind: &str) -> moq_tokio::Connection { } async fn wait_listed(fixture: &Fixture, n: usize) -> List { - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); loop { let (status, list) = fixture.list("").await; assert_eq!(status, reqwest::StatusCode::OK); @@ -273,11 +273,11 @@ async fn wait_listed(fixture: &Fixture, n: usize) -> List { return list; } assert!( - moq_clock::now() < deadline, + kio::clock::now() < deadline, "expected {n} sessions, got {}", list.sessions.len() ); - moq_clock::sleep(Duration::from_millis(25)).await; + kio::clock::sleep(Duration::from_millis(25)).await; } } @@ -301,12 +301,12 @@ async fn push_by_id_refuses_inside_the_cadence() { assert_eq!(status, reqwest::StatusCode::ACCEPTED); assert_eq!(nudged.ids.as_slice(), std::slice::from_ref(&id)); - moq_clock::timeout(Duration::from_secs(3), session.closed()) + kio::clock::timeout(Duration::from_secs(3), session.closed()) .await .expect("a push must close the session well inside the cadence") .expect_err("refused as Unauthorized"); - moq_clock::sleep(Duration::from_millis(200)).await; + kio::clock::sleep(Duration::from_millis(200)).await; let ends = script.ends(); assert_eq!(ends.len(), 1); assert_eq!(ends[0].id, id); @@ -352,16 +352,16 @@ async fn path_and_cidr_select_a_subset() { assert_eq!(status, reqwest::StatusCode::ACCEPTED); assert_eq!(nudged.ids.len(), 2); - moq_clock::timeout(Duration::from_secs(3), a.closed()) + kio::clock::timeout(Duration::from_secs(3), a.closed()) .await .expect("path match a") .expect_err("refused"); - moq_clock::timeout(Duration::from_secs(3), b.closed()) + kio::clock::timeout(Duration::from_secs(3), b.closed()) .await .expect("path match b") .expect_err("refused"); assert!( - moq_clock::timeout(Duration::from_millis(200), c.closed()) + kio::clock::timeout(Duration::from_millis(200), c.closed()) .await .is_err(), "the unmatched session must stay" @@ -380,7 +380,7 @@ async fn websocket_is_listed_and_closes_on_a_push() { script.on_revalidate(Answer::Status(403)); let (status, _) = fixture.revalidate(&format!("?id={}", list.sessions[0].id)).await; assert_eq!(status, reqwest::StatusCode::ACCEPTED); - moq_clock::timeout(Duration::from_secs(3), session.closed()) + kio::clock::timeout(Duration::from_secs(3), session.closed()) .await .expect("websocket push") .expect_err("refused"); @@ -399,12 +399,12 @@ async fn empty_filter_reaches_all() { assert_eq!(status, reqwest::StatusCode::ACCEPTED); assert_eq!(nudged.ids.len(), 2); - moq_clock::timeout(Duration::from_secs(3), async { + kio::clock::timeout(Duration::from_secs(3), async { loop { if script.revalidate_ids().len() >= 2 { break; } - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } }) .await @@ -425,18 +425,18 @@ async fn a_pushed_retier_arrives_on_the_next_reply() { let (status, _) = fixture.revalidate("").await; assert_eq!(status, reqwest::StatusCode::ACCEPTED); - moq_clock::timeout(Duration::from_secs(3), async { + kio::clock::timeout(Duration::from_secs(3), async { loop { if script.events().contains(&Event::Revalidate) { break; } - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } }) .await .expect("the push re-checked"); assert!( - moq_clock::timeout(Duration::from_millis(200), session.closed()) + kio::clock::timeout(Duration::from_millis(200), session.closed()) .await .is_err(), "a retier must not close the session" diff --git a/rs/moq-relay/tests/integration/shutdown_signal.rs b/rs/moq-relay/tests/integration/shutdown_signal.rs index de41b213156..48394c87934 100644 --- a/rs/moq-relay/tests/integration/shutdown_signal.rs +++ b/rs/moq-relay/tests/integration/shutdown_signal.rs @@ -148,12 +148,12 @@ async fn sigint_drains_sessions_before_exiting_inner() { // open for its whole window. let _straggler = straggler(port).await; - let signalled = moq_clock::now(); + let signalled = kio::clock::now(); // SAFETY: `raise` is async-signal-safe, and SIGINT's disposition is tokio's // handler, registered above. assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0, "failed to raise SIGINT"); - let goaway = moq_clock::timeout( + let goaway = kio::clock::timeout( Duration::from_secs(5), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -168,7 +168,7 @@ async fn sigint_drains_sessions_before_exiting_inner() { // It exits on its own, cleanly, and not before the window has passed: the point // of the drain is the time it buys, not the notice. This is what the old ctrl-C // race broke. - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after the drain window") .expect("relay task panicked") @@ -195,7 +195,7 @@ async fn a_signal_right_after_ready_drains_inner() { // for SIGTERM, so in a process of its own (nextest) the relay's handler is all // that keeps this from killing the test. assert_eq!(unsafe { libc::raise(libc::SIGTERM) }, 0, "failed to raise SIGTERM"); - let goaway = moq_clock::timeout( + let goaway = kio::clock::timeout( Duration::from_secs(5), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -203,7 +203,7 @@ async fn a_signal_right_after_ready_drains_inner() { .expect("no GOAWAY within 5s of SIGTERM") .expect("session closed without a GOAWAY"); assert_eq!(goaway.uri(), "", "expected a reconnect-to-me GOAWAY"); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after the drain") .expect("relay task panicked") @@ -256,13 +256,13 @@ async fn an_embedder_owns_the_signals_inner() { // SAFETY: `raise` is async-signal-safe, and SIGINT's disposition is tokio's // handler, registered above. assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0, "failed to raise SIGINT"); - moq_clock::timeout(Duration::from_secs(5), interrupt.recv()) + kio::clock::timeout(Duration::from_secs(5), interrupt.recv()) .await .expect("the embedder never saw SIGINT"); // The signal is the embedder's: the relay keeps serving without a GOAWAY. assert!( - moq_clock::timeout(DRAIN_TIMEOUT / 2, moq_net::kio::wait(|waiter| draining.poll(waiter))) + kio::clock::timeout(DRAIN_TIMEOUT / 2, moq_net::kio::wait(|waiter| draining.poll(waiter))) .await .is_err(), "the relay drained on a signal the embedder owns" @@ -270,9 +270,9 @@ async fn an_embedder_owns_the_signals_inner() { assert!(!run.is_finished(), "the relay exited on a signal the embedder owns"); // Until the embedder decides. - let started = moq_clock::now(); + let started = kio::clock::now(); trigger.start(); - let goaway = moq_clock::timeout( + let goaway = kio::clock::timeout( Duration::from_secs(5), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -281,7 +281,7 @@ async fn an_embedder_owns_the_signals_inner() { .expect("session closed without a GOAWAY"); assert_eq!(goaway.uri(), "", "expected a reconnect-to-me GOAWAY"); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after the drain window") .expect("relay task panicked") @@ -312,8 +312,8 @@ async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { // Keeps the relay up for the arrival below once `established` leaves. let _straggler = straggler(port).await; trigger.start(); - let deadline = moq_clock::now() + DRAIN_TIMEOUT; - let goaway = moq_clock::timeout( + let deadline = kio::clock::now() + DRAIN_TIMEOUT; + let goaway = kio::clock::timeout( Duration::from_secs(5), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -329,11 +329,11 @@ async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { // A straggler dialing mid-drain (a cached DNS resolve) is still admitted, // then told to leave at once. - moq_clock::sleep(DRAIN_TIMEOUT / 2).await; - let dialed = moq_clock::now(); + kio::clock::sleep(DRAIN_TIMEOUT / 2).await; + let dialed = kio::clock::now(); let arrival = connect(&client, port).await; let draining = arrival.draining().expect("connected"); - let goaway = moq_clock::timeout( + let goaway = kio::clock::timeout( Duration::from_secs(1), moq_net::kio::wait(|waiter| draining.poll(waiter)), ) @@ -351,7 +351,7 @@ async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { "an arrival mid-drain got {timeout:?}, past the {left:?} left of the window" ); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after the drain window") .expect("relay task panicked") @@ -376,7 +376,7 @@ async fn a_drain_ends_once_every_session_leaves_inner() { trigger.start(); // The one-shot client leaves on its GOAWAY; the straggler is still draining. - moq_clock::timeout(Duration::from_secs(5), left.closed()) + kio::clock::timeout(Duration::from_secs(5), left.closed()) .await .expect("the one-shot client did not leave on the GOAWAY") .expect("the one-shot client failed"); @@ -384,7 +384,7 @@ async fn a_drain_ends_once_every_session_leaves_inner() { assert!(!run.is_finished(), "the relay exited with a session still draining"); drop(straggler); - moq_clock::timeout(Duration::from_secs(5), run) + kio::clock::timeout(Duration::from_secs(5), run) .await .expect("relay kept running after every session left") .expect("relay task panicked") @@ -403,17 +403,17 @@ async fn a_trigger_before_run_keeps_the_deadline_inner() { // Fired while `run` is still starting. The session deadline is this instant; // `drain` must not open a fresh window when it finally observes the watch. trigger.start(); - let deadline = moq_clock::now() + DRAIN_TIMEOUT; - moq_clock::sleep(DRAIN_TIMEOUT / 2).await; + let deadline = kio::clock::now() + DRAIN_TIMEOUT; + kio::clock::sleep(DRAIN_TIMEOUT / 2).await; let run = tokio::spawn(relay.run()); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited") .expect("relay task panicked") .expect("relay exited with an error"); // A fresh window opened by `run` would end half a window past the deadline. - let over = moq_clock::now().saturating_duration_since(deadline); + let over = kio::clock::now().saturating_duration_since(deadline); assert!( over < DRAIN_TIMEOUT / 2, "run returned {over:?} past the recorded deadline, as if it opened a fresh window" @@ -457,7 +457,7 @@ async fn a_reconnecting_client_rides_out_a_restart_inner() { let straggler = straggler(addr.port()).await; trigger.start(); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after the drain window") .expect("relay task panicked") @@ -487,12 +487,12 @@ async fn a_reconnecting_client_rides_out_a_restart_inner() { res.expect("the publisher's broadcast never resolved"); } res = publisher.closed() => panic!("the publisher gave up during the restart: {res:?}"), - _ = moq_clock::sleep(Duration::from_secs(15)) => panic!("the publisher never reached the new relay"), + _ = kio::clock::sleep(Duration::from_secs(15)) => panic!("the publisher never reached the new relay"), } drop((publisher, observer)); trigger.start(); - moq_clock::timeout(Duration::from_secs(15), run) + kio::clock::timeout(Duration::from_secs(15), run) .await .expect("relay never exited after its sessions left") .expect("relay task panicked") @@ -540,7 +540,7 @@ fn relay_config() -> Config { /// Wait until the internal listener on `port` reports `line` at `/metrics`. async fn wait_metric(port: u16, line: &str) { - let deadline = moq_clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now() + Duration::from_secs(5); loop { let metrics = reqwest::get(format!("http://127.0.0.1:{port}/metrics")) .await @@ -551,7 +551,7 @@ async fn wait_metric(port: u16, line: &str) { if metrics.lines().any(|l| l == line) { break; } - assert!(moq_clock::now() < deadline, "never saw {line} in:\n{metrics}"); - moq_clock::sleep(Duration::from_millis(25)).await; + assert!(kio::clock::now() < deadline, "never saw {line} in:\n{metrics}"); + kio::clock::sleep(Duration::from_millis(25)).await; } } diff --git a/rs/moq-relay/tests/integration/smoke.rs b/rs/moq-relay/tests/integration/smoke.rs index 22db7fe2f1c..9a5a40fe7fc 100644 --- a/rs/moq-relay/tests/integration/smoke.rs +++ b/rs/moq-relay/tests/integration/smoke.rs @@ -158,7 +158,7 @@ async fn relay_websocket_round_trip_uses_newest_version() { group.finish().expect("finish group"); let (_client, pub_connection) = - moq_clock::timeout(TIMEOUT, connect_once(client().with_publisher(&pub_origin), url.clone())) + kio::clock::timeout(TIMEOUT, connect_once(client().with_publisher(&pub_origin), url.clone())) .await .expect("publisher connect timeout") .expect("publisher connect failed"); @@ -174,7 +174,7 @@ async fn relay_websocket_round_trip_uses_newest_version() { let mut announcements = sub_consumer.announced(); let (_client, sub_connection) = - moq_clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) + kio::clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); @@ -185,7 +185,7 @@ async fn relay_websocket_round_trip_uses_newest_version() { ); // ── data path ─────────────────────────────────────────────────── - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -199,12 +199,12 @@ async fn relay_websocket_round_trip_uses_newest_version() { .expect("announced broadcast resolves"); let mut track_sub = bc.track("video").unwrap().subscribe(None).await.expect("consume_track"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -239,20 +239,20 @@ async fn relay_websocket_logs_its_close_under_a_cluster_id() { let web_handle = tokio::spawn(async move { web.run().await.expect("relay web server") }); let url: url::Url = format!("ws://127.0.0.1:{port}/smoke").parse().expect("parse url"); - let (client, connection) = moq_clock::timeout( + let (client, connection) = kio::clock::timeout( TIMEOUT, connect_once(client().with_subscriber(moq_tokio::origin::spawn()), url), ) .await .expect("connect timeout") .expect("connect failed"); - moq_clock::timeout(TIMEOUT, logs.wait_for(&format!("conn{{id={id} "))) + kio::clock::timeout(TIMEOUT, logs.wait_for(&format!("conn{{id={id} "))) .await .expect("the WebSocket session was not numbered on the cluster counter"); let _ = connection.close().await; drop(client); - moq_clock::timeout(TIMEOUT, logs.wait_for(&format!("connection closed id={id}"))) + kio::clock::timeout(TIMEOUT, logs.wait_for(&format!("connection closed id={id}"))) .await .expect("the WebSocket session's close was not logged"); @@ -264,7 +264,7 @@ async fn relay_websocket_logs_its_close_under_a_cluster_id() { async fn announced_until(announcements: &mut moq_net::announce::Consumer, until: &str) -> Vec { let mut seen = Vec::new(); while !seen.iter().any(|prefix| prefix == until) { - let event = moq_clock::timeout(TIMEOUT, announcements.next()) + let event = kio::clock::timeout(TIMEOUT, announcements.next()) .await .expect("announcement timeout") .expect("origin closed"); @@ -297,7 +297,7 @@ async fn hidden_broadcasts_need_a_lite07_opt_in() { group.finish().expect("finish group"); // The relay's announce request carries the opt-in only on lite-07, so the publisher // must speak it too for the hidden route to reach the relay. - let (_pub_client, pub_connection) = moq_clock::timeout( + let (_pub_client, pub_connection) = kio::clock::timeout( TIMEOUT, connect_once(client_version(Some(lite07)).with_publisher(&pub_origin), url.clone()), ) @@ -308,7 +308,7 @@ async fn hidden_broadcasts_need_a_lite07_opt_in() { // An opted-in lite-07 client discovers the hidden broadcast. let opted_origin = moq_tokio::origin::spawn(); let mut opted = opted_origin.consume().with_hidden(true).announced(); - let (_opted_client, opted_connection) = moq_clock::timeout( + let (_opted_client, opted_connection) = kio::clock::timeout( TIMEOUT, connect_once(client_version(Some(lite07)).with_subscriber(opted_origin), url.clone()), ) @@ -329,7 +329,7 @@ async fn hidden_broadcasts_need_a_lite07_opt_in() { let origin = moq_tokio::origin::spawn(); let consumer = origin.consume().with_hidden(local_hidden); let mut announcements = consumer.announced(); - let (_client, connection) = moq_clock::timeout( + let (_client, connection) = kio::clock::timeout( TIMEOUT, connect_once(client_version(Some(version)).with_subscriber(origin), url.clone()), ) @@ -351,12 +351,12 @@ async fn hidden_broadcasts_need_a_lite07_opt_in() { } let bc = consumer.request(".x/y", None).await.expect("hidden broadcast resolves"); let mut sub = bc.track("video").unwrap().subscribe(None).await.expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timeout") .expect("read frame") @@ -378,7 +378,7 @@ async fn relay_websocket_honors_server_version() { let (port, web_handle) = spawn_versioned_relay(vec![allowed]).await; let url: url::Url = format!("ws://127.0.0.1:{port}/smoke").parse().expect("parse url"); - let excluded_result = moq_clock::timeout( + let excluded_result = kio::clock::timeout( TIMEOUT, client_version(Some(excluded)).connect(url.clone()).established(), ) @@ -389,7 +389,7 @@ async fn relay_websocket_honors_server_version() { "WebSocket accepted excluded version {excluded} despite --server-version {allowed}" ); - let session = moq_clock::timeout(TIMEOUT, client_version(Some(allowed)).connect(url).established()) + let session = kio::clock::timeout(TIMEOUT, client_version(Some(allowed)).connect(url).established()) .await .expect("allowed client connect timeout") .expect("allowed client connect failed"); @@ -458,7 +458,7 @@ async fn relay_https_terminates_tls() { .add_root_certificate(reqwest::Certificate::from_pem(cert.pem().as_bytes()).expect("parse root")) .build() .expect("build https client"); - let resp = moq_clock::timeout(TIMEOUT, client.get(format!("https://localhost:{port}/health")).send()) + let resp = kio::clock::timeout(TIMEOUT, client.get(format!("https://localhost:{port}/health")).send()) .await .expect("https request timed out") .expect("https request failed"); @@ -494,7 +494,7 @@ async fn relay_websocket_root_path_upgrades() { .expect("write frame"); group.finish().expect("finish group"); - let (_client, pub_connection) = moq_clock::timeout( + let (_client, pub_connection) = kio::clock::timeout( TIMEOUT, connect_once(client().with_publisher(pub_origin.consume()), url.clone()), ) @@ -507,7 +507,7 @@ async fn relay_websocket_root_path_upgrades() { let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); let (_client, sub_connection) = - moq_clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) + kio::clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) .await .expect("subscriber connect timeout") .expect("subscriber connect failed (root-path WS upgrade)"); @@ -515,7 +515,7 @@ async fn relay_websocket_root_path_upgrades() { // ── data path ─────────────────────────────────────────────────── // The root auth scope is the empty path, so the broadcast announces at its // own name with no prefix. - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -528,12 +528,12 @@ async fn relay_websocket_root_path_upgrades() { .expect("announced broadcast resolves"); let mut track_sub = bc.track("video").unwrap().subscribe(None).await.expect("consume_track"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -627,7 +627,7 @@ async fn internal_tcp_round_trip() { .expect("write frame"); group.finish().expect("finish group"); - let (_client, pub_connection) = moq_clock::timeout( + let (_client, pub_connection) = kio::clock::timeout( TIMEOUT, connect_once(client().with_publisher(pub_origin.consume()), url.clone()), ) @@ -645,7 +645,7 @@ async fn internal_tcp_round_trip() { let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); let (_client, sub_connection) = - moq_clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) + kio::clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); @@ -653,7 +653,7 @@ async fn internal_tcp_round_trip() { // ── data path ─────────────────────────────────────────────────── // The internal listener grants the empty root, so the broadcast announces // at its own name with no path prefix. - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -666,12 +666,12 @@ async fn internal_tcp_round_trip() { .expect("announced broadcast resolves"); let mut track_sub = bc.track("video").unwrap().subscribe(None).await.expect("consume_track"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -730,7 +730,7 @@ async fn internal_unix_round_trip() { .expect("write frame"); group.finish().expect("finish group"); - let (_client, pub_connection) = moq_clock::timeout( + let (_client, pub_connection) = kio::clock::timeout( TIMEOUT, connect_once(client().with_publisher(pub_origin.consume()), url.clone()), ) @@ -748,33 +748,33 @@ async fn internal_unix_round_trip() { let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); let (_client, sub_connection) = - moq_clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) + kio::clock::timeout(TIMEOUT, connect_once(client().with_subscriber(sub_origin), url)) .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); // ── data path ─────────────────────────────────────────────────── - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timeout") .expect("announced broadcast resolves"); - let mut track_sub = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().subscribe(None).await }) + let mut track_sub = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().subscribe(None).await }) .await .expect("subscribe timeout") .expect("consume_track"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -815,7 +815,7 @@ async fn path_round_trip(version: moq_net::Version, pub_url: url::Url, sub_url: group.finish().expect("finish group"); let pub_client = client_version(Some(version)).with_publisher(pub_origin.consume()); - let (_client, pub_connection) = moq_clock::timeout(TIMEOUT, connect_once(pub_client, pub_url)) + let (_client, pub_connection) = kio::clock::timeout(TIMEOUT, connect_once(pub_client, pub_url)) .await .expect("publisher connect timeout") .expect("publisher connect failed"); @@ -824,12 +824,12 @@ async fn path_round_trip(version: moq_net::Version, pub_url: url::Url, sub_url: let sub_consumer = sub_origin.consume(); let mut announcements = sub_consumer.announced(); let sub_client = client_version(Some(version)).with_subscriber(sub_origin); - let (_client, sub_connection) = moq_clock::timeout(TIMEOUT, connect_once(sub_client, sub_url)) + let (_client, sub_connection) = kio::clock::timeout(TIMEOUT, connect_once(sub_client, sub_url)) .await .expect("subscriber connect timeout") .expect("subscriber connect failed"); - let (update, _) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, _) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announcement timeout") .expect("origin closed"); @@ -932,7 +932,7 @@ async fn raw_quic_path_reaches_server() { async fn health_endpoint_reports_ok() { let (port, web_handle) = spawn_relay().await; - let resp = moq_clock::timeout(TIMEOUT, reqwest::get(format!("http://127.0.0.1:{port}/health"))) + let resp = kio::clock::timeout(TIMEOUT, reqwest::get(format!("http://127.0.0.1:{port}/health"))) .await .expect("health request timeout") .expect("health request failed"); diff --git a/rs/moq-relay/tests/integration/upstream_links.rs b/rs/moq-relay/tests/integration/upstream_links.rs index daab024ace7..3d2def0ad3c 100644 --- a/rs/moq-relay/tests/integration/upstream_links.rs +++ b/rs/moq-relay/tests/integration/upstream_links.rs @@ -26,7 +26,7 @@ const TIMEOUT: Duration = Duration::from_secs(15); /// Bound `fut` by [`TIMEOUT`], naming the step that hung. async fn within(step: &str, fut: impl std::future::Future) -> T { - moq_clock::timeout(TIMEOUT, fut) + kio::clock::timeout(TIMEOUT, fut) .await .unwrap_or_else(|_| panic!("timed out: {step}")) } @@ -159,7 +159,7 @@ fn publish(origin: &origin::Producer, path: &str) -> Publisher { if group.write_frame(moq_net::Timestamp::ZERO, b"hello".as_ref()).is_err() || group.finish().is_err() { break; } - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } }) .abort_handle(); diff --git a/rs/moq-relay/tests/integration/wire_stats.rs b/rs/moq-relay/tests/integration/wire_stats.rs index a3eb76ba3d0..36797b4159e 100644 --- a/rs/moq-relay/tests/integration/wire_stats.rs +++ b/rs/moq-relay/tests/integration/wire_stats.rs @@ -57,11 +57,11 @@ async fn wire_sources(io_uring: bool) { client.bind = Some("127.0.0.1:0".parse().unwrap()); let client = client.init(Default::default()).unwrap(); let url: url::Url = format!("{scheme}://{addr}/wire").parse().unwrap(); - let connection = moq_clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) + let connection = kio::clock::timeout(TIMEOUT, client.with_reconnect(false).connect(url).established()) .await .unwrap() .unwrap(); - let before = moq_clock::timeout(TIMEOUT, async { + let before = kio::clock::timeout(TIMEOUT, async { loop { let row = presence(®istry); if row.active() == 1 @@ -106,7 +106,7 @@ async fn wire_sources(io_uring: bool) { assert!(total > 0, "{scheme}: {body}"); } drop(connection); - let after = moq_clock::timeout(TIMEOUT, async { + let after = kio::clock::timeout(TIMEOUT, async { loop { let row = presence(®istry); if row.active() == 0 { @@ -121,7 +121,7 @@ async fn wire_sources(io_uring: bool) { assert_eq!(presence(®istry), after, "a closed source is unregistered"); } trigger.start(); - moq_clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, running).await.unwrap().unwrap().unwrap(); } #[tokio::test] diff --git a/rs/moq-room/Cargo.toml b/rs/moq-room/Cargo.toml index 23bb15d19c4..fed15448a0d 100644 --- a/rs/moq-room/Cargo.toml +++ b/rs/moq-room/Cargo.toml @@ -14,9 +14,8 @@ keywords = ["quic", "webtransport", "conferencing", "live"] categories = ["multimedia", "network-programming"] [dependencies] -kio = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-auth = { workspace = true } -moq-clock = { workspace = true } moq-json = { workspace = true } moq-net = { workspace = true } thiserror = { workspace = true } diff --git a/rs/moq-room/src/chat.rs b/rs/moq-room/src/chat.rs index dfc614159ef..cc912f75038 100644 --- a/rs/moq-room/src/chat.rs +++ b/rs/moq-room/src/chat.rs @@ -2,7 +2,7 @@ //! Sender identity comes from the broadcast, not the payload. use crate::Error; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::{broadcast, track}; use std::{ collections::VecDeque, @@ -21,10 +21,10 @@ pub const HISTORY: Duration = Duration::from_secs(10); pub type Event = moq_json::window::Event; /// Poll-driven wall-clock deadline, the same shape kio::time used before that -/// module left kio. Built on moq-clock so tokio::time::pause advances it in tests. +/// module left kio. Built on kio's clock so tokio::time::pause advances it in tests. struct Deadline { at: Option, - sleep: Option>>, + sleep: Option>>, } impl Deadline { @@ -44,8 +44,8 @@ impl Deadline { fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> { let Some(at) = self.at else { return Poll::Pending }; - let sleep = self.sleep.get_or_insert_with(|| Box::pin(moq_clock::sleep_until(at))); - if at <= moq_clock::now() { + let sleep = self.sleep.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(at))); + if at <= kio::clock::now() { return Poll::Ready(()); } waiter.poll_future(sleep.as_mut()) @@ -92,12 +92,12 @@ impl Publisher { self.prune()?; self.producer .push(moq_net::Timed::from(&text.to_owned()).at(moq_net::Timestamp::now()))?; - self.expires.push_back(moq_clock::now() + HISTORY); + self.expires.push_back(kio::clock::now() + HISTORY); Ok(()) } fn prune(&mut self) -> Result<(), Error> { - let now = moq_clock::now(); + let now = kio::clock::now(); let count = self.expires.iter().take_while(|expires| **expires <= now).count(); if count == 0 { return Ok(()); diff --git a/rs/moq-rtc/Cargo.toml b/rs/moq-rtc/Cargo.toml index e3ec0e5385b..9f73a89af70 100644 --- a/rs/moq-rtc/Cargo.toml +++ b/rs/moq-rtc/Cargo.toml @@ -27,7 +27,7 @@ axum = { workspace = true, optional = true } bytes = { workspace = true } hang = { workspace = true } # Drives each str0m connection over its UDP socket. -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-ice = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-rtc/clippy.toml b/rs/moq-rtc/clippy.toml index 567b22b3d60..0b18b407d46 100644 --- a/rs/moq-rtc/clippy.toml +++ b/rs/moq-rtc/clippy.toml @@ -1,23 +1,23 @@ # The root clippy.toml without its SystemTime ban: str0m sender reports carry SystemTime, # converted at that boundary. Keep the rest in step with the root file. 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::Instant::now", reason = "read the ambient clock: kio::clock::now()" }, + { path = "std::time::Instant::elapsed", reason = "read the ambient clock: kio::clock::Instant::elapsed()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: kio::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 = "std::thread::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: kio::clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: kio::clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: kio::clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: kio::clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: kio::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::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" }, + { path = "std::time::Instant", reason = "use kio::clock::Instant" }, + { path = "tokio::time::Instant", reason = "use kio::clock::Instant" }, + { path = "tokio::time::Sleep", reason = "use kio::clock::Sleep" }, + { path = "tokio::time::Interval", reason = "use kio::clock::Interval" }, ] diff --git a/rs/moq-rtc/src/client/whep.rs b/rs/moq-rtc/src/client/whep.rs index 444232eebc3..4c89f58d4fc 100644 --- a/rs/moq-rtc/src/client/whep.rs +++ b/rs/moq-rtc/src/client/whep.rs @@ -22,7 +22,7 @@ pub(crate) async fn dial(client: &Client, url: Url, broadcast: moq_net::broadcas let sink = Box::new(IngestSink::new(broadcast, config)?); let socket = session::bind_udp(&client.config().ice_candidates).await?; - let mut rtc = Rtc::new(moq_clock::now().into_std()); + let mut rtc = Rtc::new(kio::clock::now().into_std()); for addr in socket.locals() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); diff --git a/rs/moq-rtc/src/codec/bitstream_test.rs b/rs/moq-rtc/src/codec/bitstream_test.rs index 6ee6aa98ec2..005a06993b7 100644 --- a/rs/moq-rtc/src/codec/bitstream_test.rs +++ b/rs/moq-rtc/src/codec/bitstream_test.rs @@ -112,7 +112,7 @@ async fn idle_video_bridges_do_not_gate_audio_catalog() { ) .expect("push opus"); - let snapshot = moq_clock::timeout(std::time::Duration::from_millis(1), updates.next()) + let snapshot = kio::clock::timeout(std::time::Duration::from_millis(1), updates.next()) .await .expect("idle video must not gate active audio") .expect("catalog update") diff --git a/rs/moq-rtc/src/egress.rs b/rs/moq-rtc/src/egress.rs index 67ddd54e3ed..0df5e33e03c 100644 --- a/rs/moq-rtc/src/egress.rs +++ b/rs/moq-rtc/src/egress.rs @@ -14,7 +14,7 @@ use std::collections::VecDeque; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use bytes::Bytes; use hang::catalog::{AudioCodec, VideoCodecKind}; @@ -822,7 +822,7 @@ mod tests { /// The payload of the next write, required without another frame arriving. async fn written(writes: &mut mpsc::Receiver) -> Bytes { - moq_clock::timeout(Duration::from_millis(10), writes.recv()) + kio::clock::timeout(Duration::from_millis(10), writes.recv()) .await .expect("a frame is written") .expect("the pump is alive") @@ -831,7 +831,7 @@ mod tests { /// Nothing is written without another frame arriving. async fn idle(writes: &mut mpsc::Receiver) { - let next = moq_clock::timeout(Duration::from_millis(10), writes.recv()).await; + let next = kio::clock::timeout(Duration::from_millis(10), writes.recv()).await; assert!( next.is_err(), "unexpected write: {:?}", @@ -987,7 +987,7 @@ mod tests { .unwrap(); let next = async |writes: &mut mpsc::Receiver| { - let write = moq_clock::timeout(Duration::from_millis(10), writes.recv()) + let write = kio::clock::timeout(Duration::from_millis(10), writes.recv()) .await .expect("a frame is written") .expect("the pump is alive"); @@ -1294,7 +1294,7 @@ mod tests { while demand.wanted_changed().await?.is_some() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(Duration::from_secs(1), unwanted) + kio::clock::timeout(Duration::from_secs(1), unwanted) .await .expect("the line unsubscribes") .unwrap(); diff --git a/rs/moq-rtc/src/lib.rs b/rs/moq-rtc/src/lib.rs index 7c486d540fb..0d46cb443b0 100644 --- a/rs/moq-rtc/src/lib.rs +++ b/rs/moq-rtc/src/lib.rs @@ -114,7 +114,7 @@ mod tests { .await .expect("subscribe to output catalog"); let mut catalogs = moq_mux::catalog::hang::Consumer::<()>::new(catalog_track); - let catalog = moq_clock::timeout(TIMEOUT, catalogs.next()) + let catalog = kio::clock::timeout(TIMEOUT, catalogs.next()) .await .expect("output catalog timed out") .expect("read output catalog") @@ -130,7 +130,7 @@ mod tests { } async fn next_payload(track: &mut Track) -> Vec { - let frame = moq_clock::timeout(TIMEOUT, track.next()) + let frame = kio::clock::timeout(TIMEOUT, track.next()) .await .expect("output Opus packet timed out") .expect("read output Opus packet") @@ -171,7 +171,7 @@ mod tests { let mut instances = moq_mux::follow::Instances::new(&origin.consume(), "source", Some(&epoch)).unwrap(); let (mut new, catalog) = publish_opus(origin, epoch); push(&mut *new, 20_000, NEW_PACKET); - let started = moq_clock::timeout(TIMEOUT, instances.next()) + let started = kio::clock::timeout(TIMEOUT, instances.next()) .await .expect("the replacement never took over") .unwrap(); @@ -225,7 +225,7 @@ mod tests { let url = format!("http://{address}/whep/source").parse().expect("WHEP URL"); let fill = output.broadcast().clone(); let viewer = tokio::spawn(async move { client.subscribe(url, fill).await }); - let session = moq_clock::timeout(TIMEOUT, sessions.recv()) + let session = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("WHEP negotiation timed out") .unwrap(); @@ -241,7 +241,7 @@ mod tests { ); kill(old, old_catalog); - let ended = moq_clock::timeout(TIMEOUT, session) + let ended = kio::clock::timeout(TIMEOUT, session) .await .expect("the session outlived its route") .unwrap(); @@ -299,7 +299,7 @@ mod tests { ); kill(old, old_catalog); - let pushed = moq_clock::timeout(TIMEOUT, pushed) + let pushed = kio::clock::timeout(TIMEOUT, pushed) .await .expect("the push outlived its route") .unwrap(); @@ -332,7 +332,7 @@ mod tests { }, ) .expect("publish source packet"); - let (announcement, announcement_active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (announcement, announcement_active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("source announcement timed out") .expect("source origin closed"); @@ -404,7 +404,7 @@ mod tests { .await } }); - let (whip_id, whip_task) = moq_clock::timeout(TIMEOUT, sources_rx.recv()) + let (whip_id, whip_task) = kio::clock::timeout(TIMEOUT, sources_rx.recv()) .await .expect("WHIP negotiation timed out") .unwrap(); @@ -419,7 +419,7 @@ mod tests { .expect("WHEP URL"); let fill = output.broadcast().clone(); let whep_client = tokio::spawn(async move { client.subscribe(whep, fill).await }); - let (whep_id, whep_task) = moq_clock::timeout(TIMEOUT, sources_rx.recv()) + let (whep_id, whep_task) = kio::clock::timeout(TIMEOUT, sources_rx.recv()) .await .expect("WHEP negotiation timed out") .unwrap(); @@ -434,13 +434,13 @@ mod tests { } assert!(server.terminate(&whep_id)); assert!(server.terminate(&whip_id)); - moq_clock::timeout(TIMEOUT, whep_task).await.unwrap().unwrap().unwrap(); + kio::clock::timeout(TIMEOUT, whep_task).await.unwrap().unwrap().unwrap(); // The DELETE ended the ingest cleanly, so it serves the finished broadcast for the // linger; dropping the session, as an interrupt does, ends that at once. let ingested = server_origin.consume().request("ingested", None).await.unwrap(); assert!(!ingested.is_closed(), "the finished ingest lingers"); whip_task.abort(); - let stopped = moq_clock::timeout(TIMEOUT, whip_task).await.unwrap(); + let stopped = kio::clock::timeout(TIMEOUT, whip_task).await.unwrap(); assert!(stopped.unwrap_err().is_cancelled()); assert!(ingested.is_closed(), "the interrupt closes the finished ingest"); assert!(!server.terminate(&whip_id)); diff --git a/rs/moq-rtc/src/server/mux.rs b/rs/moq-rtc/src/server/mux.rs index ec6855a77d9..78e9ddef366 100644 --- a/rs/moq-rtc/src/server/mux.rs +++ b/rs/moq-rtc/src/server/mux.rs @@ -376,7 +376,7 @@ mod tests { .await .expect("IPv4 peer must reach a dual-stack mux"); - let (_data, src) = moq_clock::timeout(Duration::from_secs(5), rx.packets.recv()) + let (_data, src) = kio::clock::timeout(Duration::from_secs(5), rx.packets.recv()) .await .expect("the demux must route the IPv4 peer's binding request") .expect("session inbox stayed open"); diff --git a/rs/moq-rtc/src/server/whep.rs b/rs/moq-rtc/src/server/whep.rs index 72602221077..94214641072 100644 --- a/rs/moq-rtc/src/server/whep.rs +++ b/rs/moq-rtc/src/server/whep.rs @@ -157,7 +157,7 @@ pub async fn accept( let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config_with_codecs(&codecs) .set_local_ice_credentials(creds) - .build(moq_clock::now().into_std()); + .build(kio::clock::now().into_std()); for addr in mux.candidates() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); @@ -206,12 +206,12 @@ fn is_sdp(headers: &HeaderMap) -> bool { /// one, would park the handler forever. No route by the deadline is /// [`moq_net::Error::Unroutable`], so the WHEP client sees a 404 and retries (typical). async fn resolve(subscriber: &moq_net::origin::Consumer, path: moq_net::Path) -> Result { - let deadline = moq_clock::now() + CATALOG_TIMEOUT; + let deadline = kio::clock::now() + CATALOG_TIMEOUT; let mut following = subscriber.follow(path, None)?; - let broadcast = moq_clock::timeout_at(deadline, following.available()) + let broadcast = kio::clock::timeout_at(deadline, following.available()) .await .map_err(|_| Error::Moq(moq_net::Error::Unroutable))??; - moq_clock::timeout_at( + kio::clock::timeout_at( deadline, EgressSource::new(moq_mux::Source::new(subscriber.clone(), broadcast)), ) @@ -279,7 +279,7 @@ mod tests { .with_subscriber(sub_origin.clone()) .with_reconnect(false); let url: url::Url = format!("tcp://{addr}/").parse().expect("url"); - let connection = moq_clock::timeout(TIMEOUT, client.connect(url).established()) + let connection = kio::clock::timeout(TIMEOUT, client.connect(url).established()) .await .expect("connect timed out") .expect("connect"); @@ -330,7 +330,7 @@ mod tests { let (sub_origin, _connection, accept) = lazy_client(pub_origin).await; let _router = super::router(crate::server::Server::new(Default::default()), sub_origin.consume()); - let missing = moq_clock::timeout(TIMEOUT, sub_origin.consume().request("missing", None)) + let missing = kio::clock::timeout(TIMEOUT, sub_origin.consume().request("missing", None)) .await .expect("sync timed out"); assert!( diff --git a/rs/moq-rtc/src/server/whip.rs b/rs/moq-rtc/src/server/whip.rs index f84569203a9..6acc419b751 100644 --- a/rs/moq-rtc/src/server/whip.rs +++ b/rs/moq-rtc/src/server/whip.rs @@ -142,7 +142,7 @@ pub async fn accept( let (creds, inbound, registration) = mux.register(); let mut rtc = RtcConfig::new() .set_local_ice_credentials(creds) - .build(moq_clock::now().into_std()); + .build(kio::clock::now().into_std()); for addr in mux.candidates() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); @@ -275,7 +275,7 @@ mod tests { .await .unwrap(); // The session binds a real UDP socket, so this runs on the wall clock. - let stale_viewer = moq_clock::timeout(std::time::Duration::from_millis(200), async { + let stale_viewer = kio::clock::timeout(std::time::Duration::from_millis(200), async { loop { match catalog.recv_group().await { Ok(Some(_)) => continue, diff --git a/rs/moq-rtc/src/session.rs b/rs/moq-rtc/src/session.rs index 5307ae84fd7..c32da6f4d98 100644 --- a/rs/moq-rtc/src/session.rs +++ b/rs/moq-rtc/src/session.rs @@ -12,7 +12,7 @@ use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; -use moq_clock::Instant; +use kio::clock::Instant; use str0m::{Candidate, Event, Rtc}; use tokio::net::UdpSocket; @@ -431,10 +431,10 @@ struct SenderAnchor { } impl SenderAnchor { - fn new(sender: str0m::rtp::rtcp::SenderInfo) -> std::result::Result { - let wall = moq_clock::Wall::try_from(sender.ntp_time)?; + fn new(sender: str0m::rtp::rtcp::SenderInfo) -> std::result::Result { + let wall = kio::clock::Wall::try_from(sender.ntp_time)?; Ok(Self { - ntp_us: wall.saturating_duration_since(moq_clock::Wall::UNIX_EPOCH).as_micros() as i128, + ntp_us: wall.saturating_duration_since(kio::clock::Wall::UNIX_EPOCH).as_micros() as i128, rtp_us: media_time_to_micros(&sender.rtp_time) as i128, }) } @@ -556,7 +556,7 @@ pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> str0m::RtcConf /// [`rtc_config_with_codecs`] directly so it can inject the mux's known /// credentials before building. pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Rtc { - rtc_config_with_codecs(codecs).build(moq_clock::now().into_std()) + rtc_config_with_codecs(codecs).build(kio::clock::now().into_std()) } /// Bind an ephemeral UDP socket for a single client session, read by its own diff --git a/rs/moq-rtmp/Cargo.toml b/rs/moq-rtmp/Cargo.toml index 052203b6f0c..95c02d891b7 100644 --- a/rs/moq-rtmp/Cargo.toml +++ b/rs/moq-rtmp/Cargo.toml @@ -35,7 +35,7 @@ bytes = { workspace = true } futures = { workspace = true } hang = { workspace = true } hmac = "0.13" -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-mux = { workspace = true } moq-net = { workspace = true } rand = { workspace = true } @@ -54,7 +54,7 @@ tracing = { workspace = true } [dev-dependencies] criterion = { package = "bench-harness", path = "../bench-harness" } -moq-clock = { path = "../moq-clock", features = ["sim"] } +kio = { path = "../kio", features = ["sim"] } # The RTMPS test borrows moq-tokio's self-signed cert generation to build a # `rustls::ServerConfig`. No transport feature: a QUIC backend here would be # unified into every other crate a `--workspace` build selects, which is exactly diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 8f6e937023f..5ff85761d7f 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -88,7 +88,7 @@ impl Client { /// For `rtmps://` or any other transport, establish the stream yourself and use /// [`with_stream`](Self::with_stream) instead. pub async fn connect(addr: SocketAddr, app: &str) -> Result { - moq_clock::timeout(crate::server::REQUEST_TIMEOUT, async { + kio::clock::timeout(crate::server::REQUEST_TIMEOUT, async { let stream = TcpStream::connect(addr).await?; crate::server::configure_socket(&stream, addr); // Advertise a tcUrl derived from the dial target: several ingest servers @@ -107,7 +107,7 @@ impl Client { /// The bring-your-own-transport entry point: establish the connection (and, for /// `rtmps://`, the TLS handshake) yourself, then hand the stream here. pub async fn with_stream(stream: S, app: &str) -> Result { - moq_clock::timeout( + kio::clock::timeout( crate::server::REQUEST_TIMEOUT, Self::with_stream_config(stream, app, None), ) @@ -116,7 +116,7 @@ impl Client { } async fn with_stream_config(mut stream: S, app: &str, tc_url: Option) -> Result { - let remaining = moq_clock::timeout(crate::server::HANDSHAKE_TIMEOUT, client_handshake(&mut stream)) + let remaining = kio::clock::timeout(crate::server::HANDSHAKE_TIMEOUT, client_handshake(&mut stream)) .await .map_err(|_| anyhow::anyhow!("RTMP handshake timed out"))??; @@ -394,7 +394,7 @@ impl Client { loop { let n = tokio::select! { result = self.stream.read(&mut buffer) => result?, - _ = moq_clock::sleep_until(publisher.media_deadline) => anyhow::bail!("remote sent no RTMP media before timeout"), + _ = kio::clock::sleep_until(publisher.media_deadline) => anyhow::bail!("remote sent no RTMP media before timeout"), }; if n == 0 { return Ok(false); @@ -420,7 +420,7 @@ impl Client { for result in results { match result { ClientSessionResult::OutboundResponse(packet) => { - moq_clock::timeout_at(publisher.media_deadline, self.stream.write_all(&packet.bytes)) + kio::clock::timeout_at(publisher.media_deadline, self.stream.write_all(&packet.bytes)) .await .map_err(|_| { anyhow::anyhow!("remote blocked RTMP control output before the media deadline") @@ -456,7 +456,7 @@ impl Client { /// Pump the session until the publish/play request is accepted, writing any /// outbound packets and failing on an explicit rejection. async fn await_event(&mut self, direction: Direction) -> Result<()> { - moq_clock::timeout(crate::server::REQUEST_TIMEOUT, async { + kio::clock::timeout(crate::server::REQUEST_TIMEOUT, async { let mut buffer = [0u8; READ_BUFFER]; loop { while let Some(result) = self.work.pop_front() { @@ -591,7 +591,7 @@ struct Publisher { broadcast: moq_net::origin::Publication, // This pull's publisher instance, so pulling again replaces it rather than resuming into it. epoch: moq_net::Epoch, - media_deadline: moq_clock::Instant, + media_deadline: kio::clock::Instant, } impl Publisher { @@ -610,13 +610,13 @@ impl Publisher { importer, catalog, epoch, - media_deadline: moq_clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT, + media_deadline: kio::clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT, broadcast: handle, }) } fn push(&mut self, tag_type: u8, timestamp: u32, body: &Bytes) -> anyhow::Result<()> { - self.media_deadline = moq_clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT; + self.media_deadline = kio::clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT; flv::import(&mut self.importer, tag_type, timestamp, body) } @@ -656,7 +656,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn client_handshakes_and_requests_have_finite_budgets() { let (stream, _peer) = tokio::io::duplex(4096); - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); assert!(Client::with_stream(stream, "live").await.is_err()); assert_eq!(start.elapsed(), crate::server::HANDSHAKE_TIMEOUT); @@ -674,7 +674,7 @@ mod tests { linger: Duration::ZERO, metadata: Default::default(), }; - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); assert!(client.await_event(direction).await.is_err()); assert_eq!(start.elapsed(), crate::server::REQUEST_TIMEOUT); let origin = moq_tokio::origin::spawn(); @@ -683,7 +683,7 @@ mod tests { let (packet, _) = client.session.send_ping_request().unwrap(); client.work.push_back(ClientSessionResult::OutboundResponse(packet)); } - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); let mut pull = Box::pin(client.pull_media(&mut publisher)); assert!(futures::poll!(pull.as_mut()).is_pending()); tokio::time::advance(crate::server::PUBLISH_IDLE_TIMEOUT).await; @@ -824,7 +824,7 @@ mod tests { let mut listed = copy.track("catalog.json").unwrap().subscribe(None).await.unwrap(); assert!(listed.recv_group().await.unwrap().is_some()); - let start = moq_clock::now(); + let start = kio::clock::now(); catalog.finish().unwrap(); broadcast.close(); drop(importer); @@ -954,7 +954,7 @@ mod tests { let epoch = moq_net::Epoch::mint(); let mut instances = moq_mux::follow::Instances::new(&upstream.consume(), "live/cam0", Some(&epoch)).unwrap(); let (_new, _new_catalog) = publish(&upstream, &epoch, NEW_IDR); - moq_clock::timeout(Duration::from_secs(5), instances.next()) + kio::clock::timeout(Duration::from_secs(5), instances.next()) .await .expect("the new publisher takes over") .unwrap(); @@ -1045,7 +1045,7 @@ mod tests { .await .expect("subscribe catalog") .ordered(); - let mut group = moq_clock::timeout(Duration::from_secs(5), catalog_track.next_group()) + let mut group = kio::clock::timeout(Duration::from_secs(5), catalog_track.next_group()) .await .expect("catalog read timed out") .expect("catalog read") diff --git a/rs/moq-rtmp/src/rml/sessions/client/mod.rs b/rs/moq-rtmp/src/rml/sessions/client/mod.rs index 5fcd500388a..97865b589d3 100644 --- a/rs/moq-rtmp/src/rml/sessions/client/mod.rs +++ b/rs/moq-rtmp/src/rml/sessions/client/mod.rs @@ -24,7 +24,7 @@ use crate::rml::messages::{RtmpMessage, UserControlEventType}; use crate::rml::sessions::StreamMetadata; use crate::rml::time::RtmpTimestamp; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::HashMap; use std::mem; @@ -880,14 +880,14 @@ fn status_code_and_description(mut arguments: Values<'_>) -> (String, String) { mod clock_tests { use super::*; - #[moq_clock::test] + #[kio::test] async fn session_epoch_uses_the_timer_clock() { let (session, _) = ClientSession::new(ClientSessionConfig::new()).unwrap(); - moq_clock::sleep(std::time::Duration::from_millis(12_345)).await; + kio::clock::sleep(std::time::Duration::from_millis(12_345)).await; assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); - moq_clock::sim::step_wall(moq_clock::Wall::UNIX_EPOCH); + kio::clock::sim::step_wall(kio::clock::Wall::UNIX_EPOCH); assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); - moq_clock::sleep(std::time::Duration::from_millis(1 << 32)).await; + kio::clock::sleep(std::time::Duration::from_millis(1 << 32)).await; assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); } } diff --git a/rs/moq-rtmp/src/rml/sessions/server/mod.rs b/rs/moq-rtmp/src/rml/sessions/server/mod.rs index 179c1383fd1..f1934a986cd 100644 --- a/rs/moq-rtmp/src/rml/sessions/server/mod.rs +++ b/rs/moq-rtmp/src/rml/sessions/server/mod.rs @@ -20,7 +20,7 @@ use crate::rml::messages::{PeerBandwidthLimitType, RtmpMessage, UserControlEvent use crate::rml::sessions::StreamMetadata; use crate::rml::time::RtmpTimestamp; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::{HashMap, HashSet}; const FOURCC_CAN_DECODE: u32 = 0x01; @@ -1419,14 +1419,14 @@ fn create_status_object(level: &str, code: &str, description: &str) -> HashMap, + accept_retry: Option, } impl Server { @@ -374,11 +374,11 @@ impl Server { let request = Abortable::new(async move { // The TLS handshake (if any) and the RTMP handshake share one // budget, so a client that stalls either is dropped. - let outcome = moq_clock::timeout(REQUEST_TIMEOUT, async move { + let outcome = kio::clock::timeout(REQUEST_TIMEOUT, async move { #[cfg(feature = "tls")] let conn = match tls { Some(acceptor) if starts_tls(&stream).await? => Conn::Tls(Box::new( - moq_clock::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)) + kio::clock::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)) .await .map_err(|_| anyhow::anyhow!("RTMPS handshake timed out"))? .map_err(|e| anyhow::anyhow!("rtmps tls handshake: {e}"))?, @@ -420,7 +420,7 @@ impl Server { tracing::warn!(%err, "failed to accept RTMP connection; continuing"); let wait = self.accept_delay.mul_f64(0.5 + rand::rng().random::() / 2.0); self.accept_delay = (self.accept_delay * 2).min(ACCEPT_RETRY_MAX); - self.accept_retry = Some(moq_clock::Instant::now() + wait); + self.accept_retry = Some(kio::clock::Instant::now() + wait); } }, } @@ -437,7 +437,7 @@ const TLS_HANDSHAKE_RECORD: u8 = 0x16; #[cfg(feature = "tls")] async fn starts_tls(stream: &TcpStream) -> io::Result { let mut first = [0u8; 1]; - if moq_clock::timeout(HANDSHAKE_TIMEOUT, stream.peek(&mut first)) + if kio::clock::timeout(HANDSHAKE_TIMEOUT, stream.peek(&mut first)) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "TLS detection timed out"))?? == 0 @@ -451,9 +451,9 @@ async fn starts_tls(stream: &TcpStream) -> io::Result { /// /// The `select!` arm that uses this is guarded on `at` being set; the pending branch keeps the arm /// well-formed rather than leaving the macro with a `None` to unwrap. -async fn sleep_until(at: Option) { +async fn sleep_until(at: Option) { match at { - Some(at) => moq_clock::sleep_until(at).await, + Some(at) => kio::clock::sleep_until(at).await, None => std::future::pending().await, } } @@ -493,7 +493,7 @@ pub fn configure_socket(stream: &TcpStream, peer: SocketAddr) { /// /// Returns `Ok(None)` if the client disconnects before issuing `publish` or /// `play`. The handshake must finish in five seconds; wrap the call in -/// [`moq_clock::timeout`] to also bound the wait for a publish or play request. +/// [`kio::clock::timeout`] to also bound the wait for a publish or play request. pub async fn accept_stream(stream: S, peer: SocketAddr) -> Result>> { Ok(accept_until_request(stream, peer).await?) } @@ -826,7 +826,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - resolved = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, following.available()) => { + resolved = kio::clock::timeout(PLAY_RESOLVE_TIMEOUT, following.available()) => { match resolved { Ok(resolved) => resolved, Err(_) => { @@ -853,7 +853,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - catalog = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, CatalogStream::next(&mut check)) => { + catalog = kio::clock::timeout(PLAY_RESOLVE_TIMEOUT, CatalogStream::next(&mut check)) => { match catalog { Ok(Ok(Some(catalog))) => catalog, Ok(Ok(None)) => { @@ -901,7 +901,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - chunk = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, export.next()) => { + chunk = kio::clock::timeout(PLAY_RESOLVE_TIMEOUT, export.next()) => { match chunk { Ok(Ok(Some(chunk))) => chunk, Ok(Ok(None)) => { @@ -1125,7 +1125,7 @@ fn fourcc_label(fourcc: &[u8; 4]) -> String { /// Run one connection's handshake and connect exchange, returning a [`Request`] /// once the client issues `publish` or `play` (or `None` if it disconnects first). async fn accept_until_request(mut stream: S, peer: SocketAddr) -> anyhow::Result>> { - let remaining = moq_clock::timeout(HANDSHAKE_TIMEOUT, run_handshake(&mut stream, peer)) + let remaining = kio::clock::timeout(HANDSHAKE_TIMEOUT, run_handshake(&mut stream, peer)) .await .map_err(|_| anyhow::anyhow!("RTMP handshake timed out"))??; @@ -1261,24 +1261,24 @@ async fn pump( peer: SocketAddr, ) -> anyhow::Result { let mut buffer = [0u8; READ_BUFFER]; - let mut media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + let mut media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; loop { let mut finished = false; while let Some(result) = work.pop_front() { match result { ServerSessionResult::OutboundResponse(packet) => { - moq_clock::timeout_at(media_deadline, stream.write_all(&packet.bytes)) + kio::clock::timeout_at(media_deadline, stream.write_all(&packet.bytes)) .await .map_err(|_| anyhow::anyhow!("peer blocked RTMP control output before the media deadline"))??; } ServerSessionResult::RaisedEvent(event) => match event { // A timestamp restart ends this publisher; isolated malformed tags are skipped. ServerSessionEvent::AudioDataReceived { data, timestamp, .. } => { - media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; publisher.push(flv::TAG_AUDIO, timestamp.value, &data)?; } ServerSessionEvent::VideoDataReceived { data, timestamp, .. } => { - media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; publisher.push(flv::TAG_VIDEO, timestamp.value, &data)?; } ServerSessionEvent::PublishStreamFinished { .. } => finished = true, @@ -1300,7 +1300,7 @@ async fn pump( let n = tokio::select! { res = stream.read(&mut buffer) => res?, - _ = moq_clock::sleep_until(media_deadline) => { + _ = kio::clock::sleep_until(media_deadline) => { anyhow::bail!("peer {peer} sent no RTMP media for {:?}", PUBLISH_IDLE_TIMEOUT); } }; @@ -1579,7 +1579,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn a_silent_peer_cannot_hold_a_handshake() { let (_client, server) = tokio::io::duplex(4096); - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); let result = accept_stream(server, "127.0.0.1:1935".parse().unwrap()).await; assert!(result.is_err()); assert_eq!(start.elapsed(), HANDSHAKE_TIMEOUT); @@ -1593,7 +1593,7 @@ mod tests { let mut work = VecDeque::from([ServerSessionResult::OutboundResponse(packet)]); let origin = moq_tokio::origin::spawn(); let mut publisher = Publisher::new(&origin, "idle", Default::default()).unwrap(); - let start = moq_clock::Instant::now(); + let start = kio::clock::Instant::now(); assert!( pump( &mut stream, @@ -1871,7 +1871,7 @@ mod tests { let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let (client, server) = tokio::io::duplex(64 * 1024); - let start = moq_clock::now(); + let start = kio::clock::now(); let accept = tokio::spawn(accept_publish(server, origin.clone(), Duration::from_secs(10))); // A hangup ends the instance at once, before a follower would hand it out, so this // requests it on its announcement instead. @@ -1925,7 +1925,7 @@ mod tests { let accept = tokio::spawn(accept_publish(server, origin.clone(), Duration::from_secs(10))); publish_one_keyframe(client, Leave::Unpublish).await; - moq_clock::sleep(Duration::from_secs(5)).await; + kio::clock::sleep(Duration::from_secs(5)).await; let finished = consumer.request("live/cam0", None).await.unwrap(); let mut video = finished.track("0.flv-v").unwrap().subscribe(None).await.unwrap(); assert!( @@ -1937,11 +1937,11 @@ mod tests { let (client, server) = tokio::io::duplex(64 * 1024); let _reconnect = tokio::spawn(accept_publish(server, origin.clone(), Duration::from_secs(10))); let _encoder = tokio::spawn(publish_one_keyframe(client, Leave::Hangup)); - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; assert!(!accept.is_finished(), "the newer publisher leaves the linger running"); assert!(!finished.is_closed()); - let start = moq_clock::now(); + let start = kio::clock::now(); accept.await.unwrap(); assert_eq!(start.elapsed(), Duration::from_secs(4)); assert!(finished.is_closed()); @@ -2261,7 +2261,7 @@ mod tests { }); let stream = TcpStream::connect(addr).await.unwrap(); - let media = moq_clock::timeout(Duration::from_secs(5), play_client_collect(stream, 2, 0, &[])) + let media = kio::clock::timeout(Duration::from_secs(5), play_client_collect(stream, 2, 0, &[])) .await .expect("play client timed out"); @@ -2328,7 +2328,7 @@ mod tests { let (tx, mut media) = tokio::sync::mpsc::unbounded_channel(); let client = tokio::spawn(play_client(TcpStream::connect(addr).await.unwrap(), 0, &[], tx)); let mut next = async || { - moq_clock::timeout(Duration::from_secs(5), media.recv()) + kio::clock::timeout(Duration::from_secs(5), media.recv()) .await .expect("no media") .expect("the play ended") @@ -2340,7 +2340,7 @@ mod tests { let epoch = moq_net::Epoch::mint(); let mut instances = moq_mux::follow::Instances::new(&consumer, "live/cam0", Some(&epoch)).unwrap(); let (_new, _new_catalog) = publish_avc(&origin, epoch, &[0x65, 0x99, 0x99, 0x99, 0x99]); - moq_clock::timeout(Duration::from_secs(5), instances.next()) + kio::clock::timeout(Duration::from_secs(5), instances.next()) .await .expect("the new publisher takes over") .unwrap(); @@ -2354,7 +2354,7 @@ mod tests { old.abort(moq_net::Error::Transport("connection lost".into())); drop(old_catalog); - let played = moq_clock::timeout(Duration::from_secs(5), played) + let played = kio::clock::timeout(Duration::from_secs(5), played) .await .expect("the play outlived its route") .unwrap(); @@ -2397,7 +2397,7 @@ mod tests { }); let stream = TcpStream::connect(addr).await.unwrap(); - let status = moq_clock::timeout(Duration::from_secs(5), play_client_first_status(stream, 0, &[])) + let status = kio::clock::timeout(Duration::from_secs(5), play_client_first_status(stream, 0, &[])) .await .expect("play client timed out"); @@ -2676,7 +2676,7 @@ mod tests { // The player advertises multitrack; collect the four video messages (two // sequence headers + two keyframes across the two tracks). let stream = TcpStream::connect(addr).await.unwrap(); - let media = moq_clock::timeout( + let media = kio::clock::timeout( Duration::from_secs(5), play_client_collect(stream, 4, CAPS_EX_MULTITRACK, &[b"avc1"]), ) @@ -2759,7 +2759,7 @@ mod tests { run_client(stream, ClientMode::Publish).await; }); - let request = moq_clock::timeout(Duration::from_secs(5), server.accept()) + let request = kio::clock::timeout(Duration::from_secs(5), server.accept()) .await .expect("server.accept timed out") .expect("server yielded a request"); @@ -2809,13 +2809,13 @@ mod tests { let fresh_client = tokio::spawn(async move { run_client(TcpStream::connect(addr).await.unwrap(), ClientMode::Publish).await; }); - moq_clock::timeout(Duration::from_secs(5), async { + kio::clock::timeout(Duration::from_secs(5), async { while !matches!(announced.next().await, Some(moq_net::announce::Event::Restart(_))) {} }) .await .expect("the reconnect restarts the broadcast"); - let stale_viewer = moq_clock::timeout(Duration::from_millis(200), async { + let stale_viewer = kio::clock::timeout(Duration::from_millis(200), async { loop { match catalog.recv_group().await { Ok(Some(_)) => continue, @@ -2917,7 +2917,7 @@ mod tests { _ => {} } } - let n = moq_clock::timeout(Duration::from_secs(5), stream.read(&mut buffer)) + let n = kio::clock::timeout(Duration::from_secs(5), stream.read(&mut buffer)) .await .expect("timed out awaiting connect _result") .unwrap(); @@ -2961,7 +2961,7 @@ mod tests { run_client(stream, ClientMode::Play).await; }); - let request = moq_clock::timeout(Duration::from_secs(5), server.accept()) + let request = kio::clock::timeout(Duration::from_secs(5), server.accept()) .await .expect("server.accept timed out") .expect("server yielded a request"); @@ -3055,7 +3055,7 @@ mod tests { run_client(stream, ClientMode::Publish).await; }); - let request = moq_clock::timeout(Duration::from_secs(5), server.accept()) + let request = kio::clock::timeout(Duration::from_secs(5), server.accept()) .await .expect("server.accept timed out") .expect("server yielded a request"); @@ -3089,7 +3089,7 @@ mod tests { let stream = TcpStream::connect(addr).await.unwrap(); run_client(stream, ClientMode::Play).await; }); - let request = moq_clock::timeout(Duration::from_secs(5), server.accept()) + let request = kio::clock::timeout(Duration::from_secs(5), server.accept()) .await .expect("plaintext accept timed out") .expect("server yielded a plaintext request"); @@ -3128,7 +3128,7 @@ mod tests { // The refusal comes well inside REQUEST_TIMEOUT, so a client that stayed open // (a bug) fails the outer timeout rather than passing quietly. let refused = tokio::select! { - refused = moq_clock::timeout(Duration::from_secs(5), plain) => refused, + refused = kio::clock::timeout(Duration::from_secs(5), plain) => refused, request = server.accept() => panic!("plaintext client yielded a request: {}", request.is_some()), }; assert!(refused.expect("plaintext client was not refused").unwrap()); diff --git a/rs/moq-rtsp/Cargo.toml b/rs/moq-rtsp/Cargo.toml index a7f78c1ee9a..df9e23430d9 100644 --- a/rs/moq-rtsp/Cargo.toml +++ b/rs/moq-rtsp/Cargo.toml @@ -22,7 +22,7 @@ test-support = ["dep:base64", "dep:tokio", "tokio/io-util", "tokio/macros", "tok base64 = { workspace = true, optional = true } futures = { workspace = true } hang = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-mux = { workspace = true } moq-net = { workspace = true } # Only for `RedactedUrl`, so the session URL logs without its query. @@ -38,7 +38,7 @@ url = { workspace = true } [dev-dependencies] base64 = { workspace = true } # A clock only the stall tests move, so a loaded runner never fires a deadline early. -moq-clock = { path = "../moq-clock", features = ["manual"] } +kio = { path = "../kio", features = ["manual"] } tokio = { workspace = true, features = ["full", "test-util"] } tracing-test = { workspace = true } diff --git a/rs/moq-rtsp/src/client.rs b/rs/moq-rtsp/src/client.rs index cbf5f10e38a..b5089e24f9d 100644 --- a/rs/moq-rtsp/src/client.rs +++ b/rs/moq-rtsp/src/client.rs @@ -222,16 +222,16 @@ impl Client { let result: Result = async { let mut session = self.within(session.play(play)).await??.demuxed()?; tracing::info!(%url, streams = tracks.len(), "RTSP session playing"); - let playing = moq_clock::now(); + let playing = kio::clock::now(); // Measured from the last frame, so RTCP reports alone cannot keep a dead camera alive. let mut deadline = playing + self.timeout; - while let Some(item) = moq_clock::timeout(deadline - moq_clock::now(), session.next()) + while let Some(item) = kio::clock::timeout(deadline - kio::clock::now(), session.next()) .await .map_err(|_| Error::Stalled(self.timeout))? { let item = item?; if matches!(item, CodecItem::VideoFrame(_) | CodecItem::AudioFrame(_)) { - deadline = moq_clock::now() + self.timeout; + deadline = kio::clock::now() + self.timeout; } if ingest.push(item, session.streams())?.is_some() { tracing::warn!(%url, "RTSP timeline jumped, ending the session"); @@ -261,7 +261,7 @@ impl Client { impl Client { /// Fail `step` once it takes longer than the timeout. async fn within(&self, step: impl Future) -> Result { - moq_clock::timeout(self.timeout, step) + kio::clock::timeout(self.timeout, step) .await .map_err(|_| Error::Stalled(self.timeout)) } @@ -368,11 +368,11 @@ struct Stream { track: Track, /// The previous frame's timestamp, in the stream's clock units since the session start, and /// when it arrived. - last: Option<(i64, moq_clock::Instant)>, + last: Option<(i64, kio::clock::Instant)>, /// Whether a keyframe has been published (video) or the session started (audio). started: bool, /// When a lost packet broke the video's reference chain, so it waits for a keyframe. - held: Option, + held: Option, /// Whether retina's parameter sets still need inserting: until the splitter emits a keyframe /// carrying them, after which it re-inserts them ahead of every keyframe itself. fresh: bool, @@ -416,7 +416,7 @@ impl Ingest { frame.timestamp(), frame.data(), frame.has_new_parameters(), - moq_clock::Instant::from_std(frame.end_ctx().received()), + kio::clock::Instant::from_std(frame.end_ctx().received()), frame.loss(), ), CodecItem::AudioFrame(frame) => ( @@ -424,7 +424,7 @@ impl Ingest { frame.timestamp(), frame.data(), false, - moq_clock::Instant::from_std(frame.ctx().received()), + kio::clock::Instant::from_std(frame.ctx().received()), // AAC packets decode alone, and the decoder conceals a lost one. 0, ), @@ -467,7 +467,7 @@ impl Ingest { // access unit is damaged too, even when it is a keyframe, so drop it. if stream.started && stream.held.is_none() { tracing::warn!(stream_id, loss, "RTP packets lost, waiting for the next keyframe"); - stream.held = Some(moq_clock::now()); + stream.held = Some(kio::clock::now()); } video.reset(); return Ok(None); @@ -511,7 +511,7 @@ impl Ingest { /// Whether a video stream has waited longer than `timeout` for a keyframe: its first since /// `playing`, or its next since a loss held it. - fn awaiting_keyframe(&self, playing: moq_clock::Instant, timeout: std::time::Duration) -> bool { + fn awaiting_keyframe(&self, playing: kio::clock::Instant, timeout: std::time::Duration) -> bool { self.streams.iter().flatten().any(|stream| { let since = match stream.held { Some(held) => held, @@ -563,8 +563,8 @@ mod tests { /// Make the test runtime's clock one only the test moves, so a setup step on a loaded runner /// never reaches a deadline. Call it before anything reads the clock. - fn manual() -> moq_clock::Installed { - moq_clock::Manual::new().install(&tokio::runtime::Handle::current()) + fn manual() -> kio::clock::Installed { + kio::clock::Manual::new().install(&tokio::runtime::Handle::current()) } fn broadcast() -> (moq_net::broadcast::Producer, moq_mux::catalog::Producer) { @@ -1027,7 +1027,7 @@ mod tests { tokio::select! { result = &mut pull => return result.unwrap().unwrap_err(), // A driver turn, so the pull can read what was sent. - _ = moq_clock::sleep(Duration::ZERO) => {} + _ = kio::clock::sleep(Duration::ZERO) => {} } } unreachable!() @@ -1057,7 +1057,7 @@ mod tests { let snapshot = catalog_with(&catalog, 1, 0).await; let reader = subscribe(&broadcast, video_track(&snapshot)).await; // Half a second of silence, well past the 100ms allowance, then the matching timestamp. - moq_clock::sleep(Duration::from_millis(500)).await; + kio::clock::sleep(Duration::from_millis(500)).await; session.video(0, 45_000, &[fake::H264_SLICE]).await; session.close().await; assert_eq!(within("the pull", pull).await.unwrap().unwrap(), End::Closed); @@ -1153,7 +1153,7 @@ mod tests { tokio::select! { result = &mut pull => return result.unwrap().unwrap_err(), // A driver turn, so the pull can read what was sent. - _ = moq_clock::sleep(Duration::ZERO) => {} + _ = kio::clock::sleep(Duration::ZERO) => {} } } unreachable!() diff --git a/rs/moq-scene/Cargo.toml b/rs/moq-scene/Cargo.toml index 1fc6845e0ba..aceb936a597 100644 --- a/rs/moq-scene/Cargo.toml +++ b/rs/moq-scene/Cargo.toml @@ -33,9 +33,8 @@ hang = { workspace = true } humantime-serde = { workspace = true } # PNG and JPEG still images. Already in a studio's graph through eframe. image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } -kio = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-audio = { workspace = true, features = ["bus"] } -moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } # `render` is the compositor's whole input path: it turns every decoded or diff --git a/rs/moq-scene/src/compositor.rs b/rs/moq-scene/src/compositor.rs index 10c6fcdd656..baa5721184a 100644 --- a/rs/moq-scene/src/compositor.rs +++ b/rs/moq-scene/src/compositor.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::num::NonZeroU64; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_video::render::{Renderer, wgpu}; use crate::Error; diff --git a/rs/moq-shaper/Cargo.toml b/rs/moq-shaper/Cargo.toml index 54184d88d4a..6194b81cc0a 100644 --- a/rs/moq-shaper/Cargo.toml +++ b/rs/moq-shaper/Cargo.toml @@ -25,7 +25,7 @@ anyhow = { workspace = true } clap = { workspace = true } humantime = { workspace = true } humantime-serde = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } rand = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/rs/moq-shaper/src/lib.rs b/rs/moq-shaper/src/lib.rs index 54deed829ae..5cc1e5cca8e 100644 --- a/rs/moq-shaper/src/lib.rs +++ b/rs/moq-shaper/src/lib.rs @@ -42,9 +42,9 @@ mod preset; pub use preset::Preset; use anyhow::Context; +use kio::clock::Instant; #[cfg(test)] use mem::UdpSocket; -use moq_clock::Instant; use rand::{RngExt, SeedableRng, rngs::Xoshiro256PlusPlus}; use serde::{Deserialize, Serialize}; #[cfg(not(test))] @@ -898,7 +898,7 @@ async fn deliver( None => ready.push(parcel), } } - _ = moq_clock::sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => { + _ = kio::clock::sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => { // The window closes a batch that never filled. if let Some(closes) = held.closes.filter(|&closes| closes <= Instant::now()) { held.release(closes, &mut ready, &tally[direction]); @@ -1328,7 +1328,7 @@ mod tests { for _ in 0..3 { link.push(start, vec![0; 1000], &socket, LOCALHOST, &tally); } - moq_clock::timeout(Duration::from_secs(1), burst.completed()) + kio::clock::timeout(Duration::from_secs(1), burst.completed()) .await .expect("the gate never opened") .unwrap(); @@ -1477,7 +1477,7 @@ mod tests { } let mut got = Vec::new(); let mut buf = [0u8; 4]; - while let Ok(Ok(_)) = moq_clock::timeout(Duration::from_millis(200), client.recv(&mut buf)).await { + while let Ok(Ok(_)) = kio::clock::timeout(Duration::from_millis(200), client.recv(&mut buf)).await { got.push(u32::from_be_bytes(buf)); } got @@ -1505,7 +1505,7 @@ mod tests { let (shaper, client) = setup(1, delayed, Profile::default()).await; client.send(b"held").await.unwrap(); while shaper.stats().up.packets == 0 { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } let outage = shaper.cut(); @@ -1580,18 +1580,18 @@ mod tests { drop(dead); client.send(b"lost").await.unwrap(); while shaper.stats().up.packets < 2 { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } shaper.retarget(next.local_addr().unwrap()).unwrap(); client.send(b"after").await.unwrap(); - let (size, flow) = moq_clock::timeout(Duration::from_secs(1), next.recv_from(&mut buf)) + let (size, flow) = kio::clock::timeout(Duration::from_secs(1), next.recv_from(&mut buf)) .await .expect("the retarget never forwarded") .unwrap(); assert_eq!(&buf[..size], b"after"); next.send_to(b"reply", flow).await.unwrap(); - let size = moq_clock::timeout(Duration::from_secs(1), client.recv(&mut buf)) + let size = kio::clock::timeout(Duration::from_secs(1), client.recv(&mut buf)) .await .expect("the reply never arrived") .unwrap(); @@ -1609,7 +1609,7 @@ mod tests { gone.send(b"gone").await.unwrap(); drop(gone); while shaper.stats().down.packets < 1 { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } let got = round_trip(&client, 10).await; @@ -2137,7 +2137,7 @@ mod tests { let mut got = Vec::new(); let mut buf = [0u8; 4]; - while let Ok(Ok(_)) = moq_clock::timeout(Duration::from_millis(500), target.recv_from(&mut buf)).await { + while let Ok(Ok(_)) = kio::clock::timeout(Duration::from_millis(500), target.recv_from(&mut buf)).await { got.push((u32::from_be_bytes(buf), start.elapsed())); } got @@ -2194,14 +2194,14 @@ mod tests { for id in 0..count { sent.push(Instant::now()); client.send(&id.to_be_bytes()).await.unwrap(); - moq_clock::sleep(spacing).await; + kio::clock::sleep(spacing).await; } sent }; let receive = async { let mut got = Vec::new(); let mut buf = [0u8; 4]; - while let Ok(Ok(_)) = moq_clock::timeout(Duration::from_millis(500), client.recv(&mut buf)).await { + while let Ok(Ok(_)) = kio::clock::timeout(Duration::from_millis(500), client.recv(&mut buf)).await { got.push((u32::from_be_bytes(buf), Instant::now())); } got @@ -2584,7 +2584,7 @@ mod tests { let mut buf = [0u8; 4]; client.send(&0u32.to_be_bytes()).await.unwrap(); client.recv(&mut buf).await.unwrap(); - moq_clock::sleep(ms(250)).await; + kio::clock::sleep(ms(250)).await; client.send(&1u32.to_be_bytes()).await.unwrap(); client.recv(&mut buf).await.unwrap(); @@ -2615,7 +2615,7 @@ mod tests { .await; // The first datagram comes after the step, so the 5ms phase passes with nothing in it. - moq_clock::sleep(ms(250)).await; + kio::clock::sleep(ms(250)).await; let mut buf = [0u8; 4]; client.send(&0u32.to_be_bytes()).await.unwrap(); client.recv(&mut buf).await.unwrap(); diff --git a/rs/moq-shaper/src/main.rs b/rs/moq-shaper/src/main.rs index 1c652de50f8..19da706ec9f 100644 --- a/rs/moq-shaper/src/main.rs +++ b/rs/moq-shaper/src/main.rs @@ -128,7 +128,7 @@ async fn main() -> anyhow::Result<()> { // The first tick is a full period in, so a line reports traffic, not the start. let mut interval = args .report_interval - .map(|period| moq_clock::interval_at(moq_clock::now() + period, period)); + .map(|period| kio::clock::interval_at(kio::clock::now() + period, period)); let shutdown = shutdown(); tokio::pin!(shutdown); loop { @@ -201,7 +201,7 @@ struct Report<'a> { } /// The next report tick, or never without an interval. -async fn tick(interval: &mut Option) { +async fn tick(interval: &mut Option) { match interval { Some(interval) => { interval.tick().await; diff --git a/rs/moq-srt/Cargo.toml b/rs/moq-srt/Cargo.toml index ba5714d2b8c..a8a6b7e0064 100644 --- a/rs/moq-srt/Cargo.toml +++ b/rs/moq-srt/Cargo.toml @@ -28,7 +28,7 @@ tracing = { workspace = true } [dev-dependencies] # Builds the synthetic broadcasts the egress tests mux back to TS. hang = { path = "../hang" } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } srt-protocol = "0.4" tracing-subscriber = { workspace = true } diff --git a/rs/moq-srt/src/dial.rs b/rs/moq-srt/src/dial.rs index bb99db8a359..5f1aac3ff0e 100644 --- a/rs/moq-srt/src/dial.rs +++ b/rs/moq-srt/src/dial.rs @@ -274,14 +274,14 @@ mod tests { // Caller: dial with m=publish, then drop (we only assert connect + routing). let caller = tokio::spawn(async move { Client::new(addr, "cam0").call(Mode::Publish).await }); - let socket = moq_clock::timeout(Duration::from_secs(10), caller) + let socket = kio::clock::timeout(Duration::from_secs(10), caller) .await .expect("caller timed out") .expect("caller task") .expect("SRT caller should connect"); drop(socket); - let (resource, is_publish) = moq_clock::timeout(Duration::from_secs(10), server_task) + let (resource, is_publish) = kio::clock::timeout(Duration::from_secs(10), server_task) .await .expect("server timed out") .expect("server task"); @@ -315,14 +315,14 @@ mod tests { let caller = tokio::spawn(async move { Client::new(addr, "cam0").call(Mode::Request).await }); - let socket = moq_clock::timeout(Duration::from_secs(10), caller) + let socket = kio::clock::timeout(Duration::from_secs(10), caller) .await .expect("caller timed out") .expect("caller task") .expect("SRT caller should connect"); drop(socket); - let (resource, is_subscribe) = moq_clock::timeout(Duration::from_secs(10), server_task) + let (resource, is_subscribe) = kio::clock::timeout(Duration::from_secs(10), server_task) .await .expect("server timed out") .expect("server task"); diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index ecbb0c9c4cf..d5f12b01665 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -750,7 +750,7 @@ mod tests { for sequence in 0..MESSAGES { sender .send(( - moq_clock::now().into_std(), + kio::clock::now().into_std(), Bytes::copy_from_slice(&sequence.to_be_bytes()), )) .await @@ -758,7 +758,7 @@ mod tests { } for sequence in 0..MESSAGES { - let (_, payload) = moq_clock::timeout(Duration::from_secs(3), receiver.next()) + let (_, payload) = kio::clock::timeout(Duration::from_secs(3), receiver.next()) .await .expect("SRT sender stalled after its small default buffer overflowed") .expect("SRT sender closed before the burst finished") @@ -969,7 +969,7 @@ mod tests { // so the marker lands a real wall-clock distance after the first packet. write(&mut producer, 30, OFFSET); let mut received = Vec::new(); - let first = moq_clock::timeout(Duration::from_secs(10), receiver.next()) + let first = kio::clock::timeout(Duration::from_secs(10), receiver.next()) .await .expect("the first payload never arrived") .expect("the SRT egress closed early") @@ -983,7 +983,7 @@ mod tests { // Drain until the muxer flags the break, which it does exactly once, on the new // generation's leading clock packet. let boundary = loop { - let payload = moq_clock::timeout(Duration::from_secs(10), receiver.next()) + let payload = kio::clock::timeout(Duration::from_secs(10), receiver.next()) .await .expect("the resumed generation never arrived") .expect("the SRT egress closed before the marker") @@ -1131,7 +1131,7 @@ mod tests { let (mut receiver, egress) = egress(&origin, Duration::from_secs(10), true).await; old.write(30, 600_000_000); - let first = moq_clock::timeout(Duration::from_secs(10), receiver.next()) + let first = kio::clock::timeout(Duration::from_secs(10), receiver.next()) .await .expect("the first payload never arrived") .expect("the SRT egress closed early") @@ -1141,7 +1141,7 @@ mod tests { // The replacement starts its own timeline over while the old instance stays up. let mut new = Instance::publish(&origin, "new.aac"); new.write(30, 0); - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { loop { let (_, payload) = receiver .next() @@ -1171,15 +1171,15 @@ mod tests { let (mut receiver, egress) = egress(&origin, FOLLOW, false).await; live.write(5, 0); - moq_clock::timeout(Duration::from_secs(10), receiver.next()) + kio::clock::timeout(Duration::from_secs(10), receiver.next()) .await .expect("the first payload never arrived") .expect("the SRT egress closed early") .unwrap(); - let ended = moq_clock::now(); + let ended = kio::clock::now(); live.finish(); - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { while let Some(payload) = receiver.next().await { payload.unwrap(); } @@ -1200,19 +1200,19 @@ mod tests { let (mut receiver, egress) = egress(&origin, Duration::from_secs(600), false).await; live.write(5, 0); - moq_clock::timeout(Duration::from_secs(10), receiver.next()) + kio::clock::timeout(Duration::from_secs(10), receiver.next()) .await .expect("the first payload never arrived") .expect("the SRT egress closed early") .unwrap(); live.finish(); // Take everything the broadcast sent, so the egress is following when the caller goes. - while let Ok(Some(payload)) = moq_clock::timeout(Duration::from_secs(2), receiver.next()).await { + while let Ok(Some(payload)) = kio::clock::timeout(Duration::from_secs(2), receiver.next()).await { payload.unwrap(); } receiver.close().await.unwrap(); - moq_clock::timeout(Duration::from_secs(10), egress) + kio::clock::timeout(Duration::from_secs(10), egress) .await .expect("the egress outlived its caller") .unwrap() diff --git a/rs/moq-srt/src/ts.rs b/rs/moq-srt/src/ts.rs index 10806cb64b1..b15fb1e82d5 100644 --- a/rs/moq-srt/src/ts.rs +++ b/rs/moq-srt/src/ts.rs @@ -326,7 +326,7 @@ impl Subscriber { #[cfg(test)] mod tests { - use moq_clock::timeout; + use kio::clock::timeout; use moq_mux::catalog::hang::Container; use moq_mux::catalog::{CatalogFormat, Stream}; @@ -676,7 +676,7 @@ mod tests { .unwrap(); let _fresh = Publisher::new(&origin, "ingest", Default::default(), None).unwrap(); - let stale_viewer = moq_clock::timeout(Duration::from_secs(1), async { + let stale_viewer = kio::clock::timeout(Duration::from_secs(1), async { loop { match catalog.recv_group().await { Ok(Some(_)) => continue, @@ -728,9 +728,9 @@ mod tests { let consumer = origin.consume(); let broadcast = consumer.follow("live/cam0", None).unwrap().available().await.unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); let wait = tokio::spawn(publisher.finish(linger).unwrap().wait()); - moq_clock::sleep(linger / 2).await; + kio::clock::sleep(linger / 2).await; let mut catalog = broadcast.track("catalog.json").unwrap().subscribe(None).await.unwrap(); assert!( catalog.recv_group().await.unwrap().is_some(), diff --git a/rs/moq-stats/Cargo.toml b/rs/moq-stats/Cargo.toml index baae174105b..0bdd053bdfd 100644 --- a/rs/moq-stats/Cargo.toml +++ b/rs/moq-stats/Cargo.toml @@ -19,7 +19,7 @@ categories = ["multimedia", "network-programming", "web-programming"] bench = ["moq-net/fuzz"] [dependencies] -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-json = { workspace = true } moq-net = { workspace = true } serde = { workspace = true } diff --git a/rs/moq-stats/src/aggregate.rs b/rs/moq-stats/src/aggregate.rs index bb5d0a73eaa..7bed6f4aeb1 100644 --- a/rs/moq-stats/src/aggregate.rs +++ b/rs/moq-stats/src/aggregate.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, HashMap}; use std::task::Poll; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::kio::{self, Pending, Waiter}; use moq_net::stats::{Presence, Traffic}; use moq_net::track::Subscribing; @@ -840,7 +840,7 @@ impl Merged { // then fold every departed node whose grace elapsed. A fold leaves the // merged view unchanged, and only an announce adds a node, which polls // here, so no timer is needed to keep the map bounded. - let now = moq_clock::now(); + let now = kio::clock::now(); let config = &self.config; let name = self.name.as_str(); let origin = &self.origin; @@ -897,7 +897,7 @@ impl Merged { // grace re-arms it. return match self.nodes.get_mut(&key) { Some(node) => { - node.departed = Some(moq_clock::now()); + node.departed = Some(kio::clock::now()); node.depart() } None => false, @@ -939,7 +939,7 @@ impl Merged { let node = entry.get_mut(); // A return after the grace starts over, even when this announce // is the first poll since the grace elapsed. - node.fold_expired(&mut self.retired, self.grace, moq_clock::now()); + node.fold_expired(&mut self.retired, self.grace, kio::clock::now()); node.departed = None; if matches!(node.reader, Reader::Ended) { node.reader = resolve(&self.origin, &node.path, node.epoch.clone()); @@ -1669,7 +1669,7 @@ mod tests { fn replacement_while_reader_retries(drop_epoch: bool) { use std::sync::Barrier; - let now = moq_clock::now(); + let now = kio::clock::now(); // The clock never advances here, so nothing may wait out the update hold. let mut config = origin::Config::default(); config.update_hold = std::time::Duration::ZERO; diff --git a/rs/moq-stats/src/produce.rs b/rs/moq-stats/src/produce.rs index 7e9231f2d27..db53bb9cccc 100644 --- a/rs/moq-stats/src/produce.rs +++ b/rs/moq-stats/src/produce.rs @@ -6,7 +6,7 @@ use std::time::Duration; use std::task::Poll; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::stats::{Presence, Registry, Report, Tier, Traffic, TrafficEntry}; use moq_net::{Epoch, Path, broadcast, kio, origin, track}; use serde::Serialize; @@ -232,8 +232,8 @@ impl Task { return; }; - let mut ticker = moq_clock::interval(interval); - ticker.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); + let mut ticker = kio::clock::interval(interval); + ticker.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Delay); loop { // Scheduled instants are at least an interval apart, even after a late tick, @@ -281,7 +281,7 @@ impl Drain { /// `None` if the origin refused it. fn new(task: Task) -> Option { let node = NodePublisher::create(&task)?; - let now = moq_clock::now(); + let now = kio::clock::now(); Some(Self { task, node, @@ -1320,7 +1320,7 @@ mod tests { /// A drain at the current instant, numbered `group`. fn stamp(group: u64) -> Stamp { Stamp { - at: moq_clock::now(), + at: kio::clock::now(), group, } } @@ -1404,12 +1404,12 @@ mod tests { .with_versions(version.into()) .with_publisher(upstream.consume().with_hidden(true)); let client = async { - let (session, driver) = client.connect(moq_clock::now(), client_transport).await.unwrap(); + let (session, driver) = client.connect(kio::clock::now(), client_transport).await.unwrap(); tokio::spawn(moq_net::time::run(driver)); session }; let server = async { - let (session, driver) = server.accept(moq_clock::now(), server_transport).await.unwrap(); + let (session, driver) = server.accept(kio::clock::now(), server_transport).await.unwrap(); tokio::spawn(moq_net::time::run(driver)); session }; @@ -1840,7 +1840,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn a_late_drain_leaves_the_next_its_own_interval() { // Schedule the drains a millisecond before an interval boundary. - let phase = Duration::from(Timestamp::from(moq_clock::now())).as_millis() % 1000; + let phase = Duration::from(Timestamp::from(kio::clock::now())).as_millis() % 1000; tokio::time::advance(Duration::from_millis(((1999 - phase) % 1000) as u64)).await; let origin = produce_origin(); @@ -1896,7 +1896,7 @@ mod tests { interval, }) .unwrap(); - let start = moq_clock::now(); + let start = kio::clock::now(); for phase in (0..1500).step_by(100) { let at = start + Duration::from_micros(phase); assert_eq!( @@ -2366,7 +2366,7 @@ mod tests { .expect("drain"); let mut tick = || { drain.collect(); - drain.publish(moq_clock::now()); + drain.publish(kio::clock::now()); drain.node.presence.len() }; let broadcast = origin.consume().request(".stats/node", None).await.expect("resolve"); @@ -2621,7 +2621,7 @@ mod tests { .expect("drain"); let mut tick = || { drain.collect(); - drain.publish(moq_clock::now()); + drain.publish(kio::clock::now()); drain.node.prefixes.len() }; let broadcast = origin.consume().request(".stats/node", None).await.expect("resolve"); @@ -2852,24 +2852,24 @@ mod tests { // Warm up: create the groups and tracks and grow every buffer. for _ in 0..3 { drain.collect(); - drain.publish(moq_clock::now()); + drain.publish(kio::clock::now()); } // Hold a prefix with a child per tier, as a reader would. let _held = hold.then(|| { let tick = drain.tick; - let stamp = drain.stamp(moq_clock::now()); + let stamp = drain.stamp(kio::clock::now()); drain .node .adopt_prefix(&drain.report, Path::from_static("room0"), None, tick, stamp); drain.node.prefixes["room0"].output.snapshot.track.subscribe(None) }); drain.collect(); - drain.publish(moq_clock::now()); + drain.publish(kio::clock::now()); let before = counting::allocs(); drain.collect(); let allocs = counting::allocs() - before; - drain.publish(moq_clock::now()); + drain.publish(kio::clock::now()); assert!(!drain.report.traffic.is_empty(), "the drain carried entries"); assert_eq!( diff --git a/rs/moq-stats/src/produce_bench.rs b/rs/moq-stats/src/produce_bench.rs index 898bfc4ba05..10993a72322 100644 --- a/rs/moq-stats/src/produce_bench.rs +++ b/rs/moq-stats/src/produce_bench.rs @@ -3,7 +3,7 @@ use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::{Path, origin, stats::Registry, track}; use super::{Drain, Task}; @@ -45,7 +45,7 @@ impl Driver { }; Some(Self { drain: Drain::new(task)?, - now: moq_clock::now(), + now: kio::clock::now(), }) } diff --git a/rs/moq-studio/Cargo.toml b/rs/moq-studio/Cargo.toml index 348f39d50f2..60b37380595 100644 --- a/rs/moq-studio/Cargo.toml +++ b/rs/moq-studio/Cargo.toml @@ -44,8 +44,8 @@ eframe = { version = "0.36", default-features = false, features = ["default_font egui = "0.36" # Docked, rearrangeable panels. 0.21 is the newest release and pins egui 0.36. egui_dock = "0.21" +kio = { workspace = true, features = ["runtime"] } moq-audio = { workspace = true, features = ["bus"] } -moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } moq-scene = { workspace = true } diff --git a/rs/moq-studio/src/engine.rs b/rs/moq-studio/src/engine.rs index 30966dde93b..ef3ea8d1cc5 100644 --- a/rs/moq-studio/src/engine.rs +++ b/rs/moq-studio/src/engine.rs @@ -17,7 +17,7 @@ use std::time::Duration; use anyhow::Context; use bytes::Bytes; -use moq_clock::Instant; +use kio::clock::Instant; use moq_scene::source::{self, Driver, Sources}; use moq_scene::{Collection, Compositor, wgpu}; use moq_video::render::export::{Exporter, Pending, Route}; @@ -292,8 +292,8 @@ impl Engine { ) { let canvas = self.state.lock().unwrap().collection.canvas; let period = Duration::from_secs(1) / canvas.framerate; - let mut clock = moq_clock::interval_at(start, period); - clock.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Skip); + let mut clock = kio::clock::interval_at(start, period); + clock.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Skip); let mut watched = false; loop { @@ -356,8 +356,8 @@ impl Engine { let config = self.bus.config().clone(); let rate = u128::from(config.sample_rate); let channels = config.layout.channels() as usize; - let mut clock = moq_clock::interval_at(start, AUDIO_PERIOD); - clock.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Skip); + let mut clock = kio::clock::interval_at(start, AUDIO_PERIOD); + clock.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Skip); let mut samples = Vec::new(); let mut written: u128 = 0; @@ -632,7 +632,7 @@ mod tests { .await .expect("the studio starts"); - let broadcast = moq_clock::timeout(TIMEOUT, relay.follow("studio", None).unwrap().available()) + let broadcast = kio::clock::timeout(TIMEOUT, relay.follow("studio", None).unwrap().available()) .await .expect("the relay routes the program") .expect("broadcast"); @@ -649,7 +649,7 @@ mod tests { .expect("video decoder"); // The canvas is black until the color source delivers its first // picture, so wait for the composed one rather than take the first. - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { let frame = match decoder.read().await.expect("decode") { Some(moq_video::decode::Read::Frame(frame)) => frame, @@ -688,7 +688,7 @@ mod tests { let mut decoder = moq_audio::decode::Consumer::new(&broadcast, config, audio.clone(), options) .await .expect("audio decoder"); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { loop { match decoder.read().await.expect("decode") { Some(moq_audio::decode::Read::Frame(_)) => return, diff --git a/rs/moq-studio/src/ui.rs b/rs/moq-studio/src/ui.rs index cf149e50446..3effd3a8950 100644 --- a/rs/moq-studio/src/ui.rs +++ b/rs/moq-studio/src/ui.rs @@ -224,7 +224,7 @@ impl Panels { state.compositor.cut(); } if ui.button(format!("Fade ({} ms)", fade.as_millis())).clicked() { - state.compositor.fade(fade, moq_clock::Instant::now()); + state.compositor.fade(fade, kio::clock::Instant::now()); } ui.label(format!( "Program: {}", diff --git a/rs/moq-tokio/Cargo.toml b/rs/moq-tokio/Cargo.toml index 56602658250..cba109df9a1 100644 --- a/rs/moq-tokio/Cargo.toml +++ b/rs/moq-tokio/Cargo.toml @@ -21,7 +21,7 @@ net = ["dep:moq-net", "dep:web-transport-trait"] # the MoQ backend. Needs a crypto-provider feature. driver = ["dep:moq-congestion", "dep:moq-quic", "dep:pin-project-lite", "dep:rustc-hash"] # QUIC and WebTransport over moq-quic, for `https://`, `moqt://`, and `moql://`. -quic = ["_transport", "_certs", "driver", "dep:http", "dep:kio", "dep:web-transport-proto", "dep:reqwest", "watch", "dep:dns-lookup"] +quic = ["_transport", "_certs", "driver", "dep:http", "dep:web-transport-proto", "dep:reqwest", "watch", "dep:dns-lookup"] # Server-side certificate handling: chains loaded from disk, self-signed generation, # in-memory identities, and per-SNI selection. Not one to enable on its own, since # nothing turns it into a listener: every QUIC backend needs it for its own TLS, and @@ -67,10 +67,8 @@ http = { version = "1", optional = true } humantime = "2.3" humantime-serde = { workspace = true } if-addrs = { workspace = true, optional = true } -kio = { workspace = true, optional = true } +kio = { workspace = true, features = ["runtime"] } mdns-sd = { workspace = true, optional = true } - -moq-clock = { workspace = true } moq-congestion = { workspace = true, optional = true } # The ICE agent behind the `webrtc` module. Private, like str0m: neither appears in this crate's API. moq-ice = { workspace = true, optional = true } @@ -134,7 +132,7 @@ chrono = "0.4" # Use the channel type behind `mdns_sd::Receiver` so the mDNS readiness gate can # be driven with synthetic daemon events. flume = "0.12" -moq-clock = { path = "../moq-clock", features = ["sim"] } +kio = { path = "../kio", features = ["sim"] } # A bufferbloated path for the receive-credit tests and benchmark. moq-shaper = { path = "../moq-shaper" } rcgen = { workspace = true, features = ["pem", "aws_lc_rs"] } diff --git a/rs/moq-tokio/examples/chat.rs b/rs/moq-tokio/examples/chat.rs index 7e025da587e..b892cc85fbc 100644 --- a/rs/moq-tokio/examples/chat.rs +++ b/rs/moq-tokio/examples/chat.rs @@ -73,7 +73,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> tracing::info!("wrote hello + world"); // Sleep before sending our next message. - moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; + kio::clock::sleep(tokio::time::Duration::from_secs(10)).await; // There's also a helper method to create a group with a single frame. track.write_frame( @@ -83,7 +83,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> tracing::info!("wrote foobarbaz"); // Sleep before exiting and closing the broadcast. - moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; + kio::clock::sleep(tokio::time::Duration::from_secs(10)).await; // End the broadcast. Dropping the producer does the same; closing is explicit. broadcast.close(); diff --git a/rs/moq-tokio/examples/clock.rs b/rs/moq-tokio/examples/clock.rs index aa3ba0a5879..8ef3b628925 100644 --- a/rs/moq-tokio/examples/clock.rs +++ b/rs/moq-tokio/examples/clock.rs @@ -163,7 +163,7 @@ impl Publisher { let next = next.with_second(0).unwrap().with_nanosecond(0).unwrap(); let delay = (next - now).to_std().unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; now = next; // just assume we didn't undersleep } @@ -183,7 +183,7 @@ impl Publisher { let next = next.with_nanosecond(0).unwrap(); let delay = (next - now).to_std().unwrap(); - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; // Get the current time again to check if we overslept let actual = Utc::now(); diff --git a/rs/moq-tokio/src/accept.rs b/rs/moq-tokio/src/accept.rs index cd53c208c58..f2ea69f90bd 100644 --- a/rs/moq-tokio/src/accept.rs +++ b/rs/moq-tokio/src/accept.rs @@ -32,7 +32,7 @@ use std::{ time::Duration, }; -use moq_clock::Instant; +use kio::clock::Instant; /// Delay after an accept failure that is not one connection's fault, escalating /// while they continue and reset by the next successful accept. @@ -470,11 +470,11 @@ mod tests { } #[cfg(unix)] - #[moq_clock::test] + #[kio::test] async fn exhaustion_stall_uses_the_retry_clock() { let health = Health::new("test"); let _ = health.failed(&io(libc::EMFILE)); - moq_clock::sleep(Duration::from_secs(30)).await; + kio::clock::sleep(Duration::from_secs(30)).await; assert_eq!(health.stalled(), Some(Duration::from_secs(30))); } } diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index c77e7b7f2cc..3a7cd4c0d7d 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -355,7 +355,7 @@ impl Client { let session = match self.timeout.is_zero() { true => attempt.await?, - false => moq_clock::timeout(self.timeout, attempt) + false => kio::clock::timeout(self.timeout, attempt) .await .map_err(|_| Error::ConnectTimeout(self.timeout))??, }; @@ -427,7 +427,7 @@ impl Client { // arm was still pending. let dialed = match self.timeout.is_zero() { true => attempt.await?, - false => match moq_clock::timeout(self.timeout, attempt).await { + false => match kio::clock::timeout(self.timeout, attempt).await { Ok(res) => res?, Err(_) => return Err(Error::ConnectTimeout(self.timeout)), }, @@ -1104,7 +1104,7 @@ mod tests { .map_err(Error::from) }); - let dialed = moq_clock::timeout( + let dialed = kio::clock::timeout( std::time::Duration::from_secs(10), client.race_moq_connect(&client.moq, ws_addr, quic), ) @@ -1357,7 +1357,7 @@ mod tests { let quic = async { Ok("quic") }; let websocket = std::future::pending::>>(); - let value = moq_clock::timeout( + let value = kio::clock::timeout( std::time::Duration::from_secs(1), super::race_transport_connect(&race_url(), quic, websocket), ) diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index fa7791f11af..388efa16e3f 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -607,7 +607,7 @@ struct State { session: Option, /// The loop's [`Draining`] predecessor and its handover deadline, so /// [`Connection::close`] drains it too without overstaying that window. - predecessor: Option<(moq_net::Session, moq_clock::Instant)>, + predecessor: Option<(moq_net::Session, kio::clock::Instant)>, } /// The producer side of everything a [`Connection`] handle can observe. @@ -1094,7 +1094,7 @@ impl Connection { let mut close = std::pin::pin!(session.close()); tokio::select! { res = &mut close => res, - _ = moq_clock::sleep_until(deadline) => { + _ = kio::clock::sleep_until(deadline) => { abort.abort(moq_net::Error::GoawayTimeout); close.await } @@ -1140,7 +1140,7 @@ impl Connection { shared.tokens.connected(&dialed.session); let session = dialed.session; - let connected = moq_clock::now(); + let connected = kio::clock::now(); // Wait for the session to end, forwarding its bandwidth estimates into the // persistent producers meanwhile so consumers track the live stats across the // connection, and draining any predecessor left over from a migration. @@ -1270,7 +1270,7 @@ impl Connection { if restarting { // After the sleep, so the window counts only the time after the // peer stops answering. - retry.start = moq_clock::now(); + retry.start = kio::clock::now(); } continue; } @@ -1401,7 +1401,7 @@ impl Connection { let dialed = match attempt_timeout(index, candidates.len()) { None => dialed.await, - Some(limit) => match moq_clock::timeout(limit, dialed).await { + Some(limit) => match kio::clock::timeout(limit, dialed).await { Ok(dialed) => dialed, Err(_) => Err(Error::Reconnect(format!("timed out connecting to {}", Endpoint(url)))), }, @@ -1615,7 +1615,7 @@ struct Retry { /// The wait before the next attempt, before jitter. delay: Duration, /// When this run of failures began; the give-up timeout counts from here. - start: moq_clock::Instant, + start: kio::clock::Instant, /// The latest failure, so giving up reports a real cause. last_error: Option, } @@ -1624,7 +1624,7 @@ impl Retry { fn new(initial: Duration) -> Self { Self { delay: initial, - start: moq_clock::now(), + start: kio::clock::now(), last_error: None, } } @@ -1649,7 +1649,7 @@ fn timeout_error(timeout: Duration, last_error: Option<&Error>) -> Error { } /// Jitter the next delay and cap it at the retry window. `None` means the window is exhausted. -fn retry_wait(delay: Duration, retry_start: moq_clock::Instant, timeout: Duration) -> Option { +fn retry_wait(delay: Duration, retry_start: kio::clock::Instant, timeout: Duration) -> Option { let wait = delay.mul_f64(0.5 + rand::rng().random::() / 2.0); if timeout.is_zero() { return Some(wait); @@ -1730,7 +1730,7 @@ struct Draining { session: moq_net::Session, /// Resolves once the session closes, on its own or through [`Self::poll_idle`]. closed: std::pin::Pin + Send>>, - deadline: std::pin::Pin>, + deadline: std::pin::Pin>, /// Whether [`Self::poll_idle`] started the graceful close. closing: bool, /// Mirrors the session into [`State::predecessor`] for as long as this lives. @@ -1739,7 +1739,7 @@ struct Draining { impl Draining { fn new(session: moq_net::Session, handover: Duration, state: &kio::Producer) -> Self { - let deadline = Box::pin(moq_clock::sleep(handover)); + let deadline = Box::pin(kio::clock::sleep(handover)); if let Ok(mut state) = state.write() { state.predecessor = Some((session.clone(), deadline.deadline())); } @@ -1827,7 +1827,7 @@ fn poll_draining(draining: &mut Option, waiter: &kio::Waiter) -> bool /// to reach would leave the old session holding its connection well past the /// handover window. async fn sleep_draining(delay: Duration, draining: &mut Option, shared: &Shared) { - let mut sleep = std::pin::pin!(moq_clock::sleep(delay)); + let mut sleep = std::pin::pin!(kio::clock::sleep(delay)); kio::wait(|waiter| { // Nothing is serving once it retires: the predecessor closed or overstayed // its handover, and the replacement is still a dial away. Leaving the state @@ -2755,7 +2755,7 @@ mod tests { let shared = shared(); let mut draining = None; - let (connected, _session) = moq_clock::timeout( + let (connected, _session) = kio::clock::timeout( WALK_TIMEOUT, Connection::dial_any(&shared, &client, &addrs, &mut draining, &mut None), ) @@ -2777,7 +2777,7 @@ mod tests { let shared = shared(); let mut draining = None; - let result = moq_clock::timeout( + let result = kio::clock::timeout( WALK_TIMEOUT, Connection::dial_any(&shared, &client, &addrs, &mut draining, &mut None), ) @@ -2825,9 +2825,9 @@ mod tests { config.tls.insecure = Some(true); config.backoff.timeout = Some((Duration::ZERO).into()); let client = config.init(Default::default()).expect("build client"); - let started = moq_clock::now(); + let started = kio::clock::now(); let connection = client.connect(url("moqz://localhost/")); - let err = moq_clock::timeout(Duration::from_secs(1), connection.closed()) + let err = kio::clock::timeout(Duration::from_secs(1), connection.closed()) .await .expect("invalid scheme kept retrying") .expect_err("invalid scheme connected"); @@ -2851,7 +2851,7 @@ mod tests { "tls://a!b:1/", ] { let connection = client.connect(url(target)); - let err = moq_clock::timeout(Duration::from_secs(1), connection.closed()) + let err = kio::clock::timeout(Duration::from_secs(1), connection.closed()) .await .unwrap_or_else(|_| panic!("{target} kept retrying")) .expect_err("invalid server name connected"); @@ -2894,7 +2894,7 @@ mod tests { config.race = Some((Duration::ZERO).into()); let client = config.init(Default::default()).expect("build client"); - let started = moq_clock::now(); + let started = kio::clock::now(); let connection = client.connect(url(&format!("tcp://{addr}/"))); let err = connection.closed().await.expect_err("refused socket connected"); assert!(matches!(err, Error::Reconnect(_)), "{err}"); @@ -3023,11 +3023,11 @@ mod tests { let mut added = Some(added); let mut token = None; for round in 0..2 { - let mut request = moq_clock::timeout(WAIT, listener.accept()).await.unwrap().unwrap(); + let mut request = kio::clock::timeout(WAIT, listener.accept()).await.unwrap().unwrap(); let mut requests = request.requests(); let session = request.ok().await.unwrap(); loop { - let request = moq_clock::timeout(WAIT, requests.next()).await.unwrap().unwrap(); + let request = kio::clock::timeout(WAIT, requests.next()).await.unwrap().unwrap(); if request.token().is_empty() { issued.push(request.accept(moq_net::auth::Grant::default())); continue; @@ -3041,14 +3041,14 @@ mod tests { } let mut grant = token.as_ref().unwrap().grant(); while grant.peek() != Some(moq_net::auth::Grant::all()) { - moq_clock::timeout(WAIT, grant.changed()).await.unwrap().unwrap(); + kio::clock::timeout(WAIT, grant.changed()).await.unwrap().unwrap(); } session.abort(moq_net::Error::Cancel); } drop(connection); let token = token.unwrap(); // Not `Cancel`, which reads as the peer ending the grant cleanly. - let closed = moq_clock::timeout(WAIT, token.closed()).await.unwrap(); + let closed = kio::clock::timeout(WAIT, token.closed()).await.unwrap(); assert!(matches!(closed, moq_net::Error::Closed), "{closed:?}"); } @@ -3068,10 +3068,10 @@ mod tests { .unwrap() .connect(url(&format!("tcp://{addr}/"))); - let session = moq_clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); + let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); connection.auth().abort(moq_net::Error::App(9)); session.abort(moq_net::Error::Cancel); - let closed = moq_clock::timeout(WAIT, connection.closed()) + let closed = kio::clock::timeout(WAIT, connection.closed()) .await .expect("the loop kept redialing on an ended auth handle"); assert!( @@ -3094,17 +3094,17 @@ mod tests { let connection = client.connect(url(&format!("tcp://{addr}/"))); let monitor = connection.monitor(); - let session = moq_clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); + let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); let mut state = monitor.state(); while state.phase != Phase::Connected { - state = moq_clock::timeout(WAIT, monitor.state_changed(state.revision)) + state = kio::clock::timeout(WAIT, monitor.state_changed(state.revision)) .await .unwrap() .unwrap(); } let (woken, _waiter) = Woken::watch(&monitor); session.abort(moq_net::Error::App(7)); - let closed = moq_clock::timeout(WAIT, connection.closed()) + let closed = kio::clock::timeout(WAIT, connection.closed()) .await .expect("the connection did not close"); assert!(closed.is_err(), "the abort ends the loop with an error"); @@ -3287,18 +3287,18 @@ mod tests { config.websocket.delay = Some((Duration::ZERO).into()); let client = config.init(Default::default()).unwrap(); let url = url(&format!("http://127.0.0.1:{port}/")); - let connection = moq_clock::timeout(WAIT, client.connect(url).established()) + let connection = kio::clock::timeout(WAIT, client.connect(url).established()) .await .expect("never connected") .unwrap(); assert_eq!(connection.transport(), Some(crate::Transport::WebTransport)); - let (transport, _session) = moq_clock::timeout(WAIT, sessions.recv()) + let (transport, _session) = kio::clock::timeout(WAIT, sessions.recv()) .await .expect("the server never accepted a session") .unwrap(); assert_eq!(transport, crate::Transport::WebTransport); - moq_clock::timeout(WAIT, cancelled) + kio::clock::timeout(WAIT, cancelled) .await .expect("the WebSocket dial outlived QUIC's win") .unwrap(); @@ -3371,10 +3371,10 @@ mod tests { let url: Url = format!("tcp://{HOST}:1/").parse().unwrap(); let _connection = client.connect(url); - let session_a = moq_clock::timeout(WAIT, accepted_a.recv()).await.unwrap().unwrap(); + let session_a = kio::clock::timeout(WAIT, accepted_a.recv()).await.unwrap().unwrap(); let consumer = subscriber.consume(); - let cam = moq_clock::timeout(WAIT, consumer.follow("cam", None).unwrap().available()) + let cam = kio::clock::timeout(WAIT, consumer.follow("cam", None).unwrap().available()) .await .unwrap() .unwrap(); @@ -3383,7 +3383,7 @@ mod tests { let mut group = track.append_group().unwrap(); group.write_frame(moq_net::Timestamp::ZERO, b"g0".as_ref()).unwrap(); group.finish().unwrap(); - let g0 = moq_clock::timeout(WAIT, sub.recv_group()) + let g0 = kio::clock::timeout(WAIT, sub.recv_group()) .await .unwrap() .unwrap() @@ -3392,13 +3392,13 @@ mod tests { // Withdraw A from DNS, then drain it. crate::resolve::hosts::point(HOST, [addr_b]); - let drained = moq_clock::now(); + let drained = kio::clock::now(); session_a .drain() .send(moq_net::goaway::Goaway::new().with_timeout(DEADLINE)) .unwrap(); - let _session_b = moq_clock::timeout(WAIT, accepted_b.recv()) + let _session_b = kio::clock::timeout(WAIT, accepted_b.recv()) .await .expect("never redialed through the fresh resolve") .unwrap(); @@ -3406,7 +3406,7 @@ mod tests { let mut group = track.append_group().unwrap(); group.write_frame(moq_net::Timestamp::ZERO, b"g1".as_ref()).unwrap(); group.finish().unwrap(); - let mut g1 = moq_clock::timeout(WAIT, sub.recv_group()) + let mut g1 = kio::clock::timeout(WAIT, sub.recv_group()) .await .unwrap() .unwrap() @@ -3414,7 +3414,7 @@ mod tests { assert_eq!(g1.sequence, 1, "delivery resumes at the next group after the swap"); assert_eq!(g1.read_frame().await.unwrap().unwrap().payload[..], b"g1"[..]); - moq_clock::timeout(WAIT, session_a.closed()) + kio::clock::timeout(WAIT, session_a.closed()) .await .expect("the drained session never closed"); assert!( @@ -3448,16 +3448,16 @@ mod tests { .with_subscriber(subscriber.clone()) .with_restart(Restart::Wait); let mut connection = client.connect(url(&format!("tcp://{addr}/"))); - let status = moq_clock::timeout(WAIT, connection.status()).await.unwrap(); + let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); assert_eq!(status.unwrap(), Status::Connected); - let session = moq_clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); + let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); session.drain().send(moq_net::goaway::Goaway::new()).unwrap(); // A broadcast announced after the GOAWAY still arrives: the drained session serves. let late = origin.create_broadcast("late").unwrap(); late.announce(Default::default()).unwrap(); - moq_clock::timeout(WAIT, subscriber.consume().follow("late", None).unwrap().available()) + kio::clock::timeout(WAIT, subscriber.consume().follow("late", None).unwrap().available()) .await .expect("the drained session stopped serving") .unwrap(); @@ -3475,11 +3475,11 @@ mod tests { assert!(accepted.try_recv().is_err(), "redialed while the session served"); session.abort(moq_net::Error::GoawayTimeout); - let status = moq_clock::timeout(WAIT, connection.status()).await.unwrap(); + let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); assert_eq!(status.unwrap(), Status::Disconnected); - let status = moq_clock::timeout(WAIT, connection.status()).await.unwrap(); + let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); assert_eq!(status.unwrap(), Status::Connected); - moq_clock::timeout(WAIT, accepted.recv()) + kio::clock::timeout(WAIT, accepted.recv()) .await .expect("never redialed after the close") .unwrap(); @@ -3506,7 +3506,7 @@ mod tests { max: Duration, timeout: Duration, peers: Vec<(Url, Flap)>, - ) -> (Client, tokio::sync::mpsc::UnboundedReceiver<(Url, moq_clock::Instant)>) { + ) -> (Client, tokio::sync::mpsc::UnboundedReceiver<(Url, kio::clock::Instant)>) { let mut config = crate::connect::Config::default(); config.backoff.initial = Some(initial.into()); config.backoff.max = Some(max.into()); @@ -3524,7 +3524,7 @@ mod tests { let accepted = accepted.clone(); Box::pin(async move { let session = flap_once(flap).await; - let _ = accepted.send((url, moq_clock::now())); + let _ = accepted.send((url, kio::clock::now())); Ok(crate::client::Dialed { session, transport: crate::Transport::Tcp, @@ -3591,7 +3591,7 @@ mod tests { /// have waited: between half of `delay` and all of it, starting at `initial` and /// doubling up to `max`. #[cfg(feature = "tcp")] - fn assert_paced(accepts: &[(Url, moq_clock::Instant)], initial: Duration, max: Duration) { + fn assert_paced(accepts: &[(Url, kio::clock::Instant)], initial: Duration, max: Duration) { let mut delay = initial; for (index, pair) in accepts.windows(2).enumerate() { let gap = pair[1].1 - pair[0].1; @@ -3677,7 +3677,7 @@ mod tests { // Leave the session the time a multithreaded runtime may give it before the dial // returns: on the paused clock, every exchange the session can make lands first, // the connection credential's answer included. - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; Ok(crate::client::Dialed { session, transport: crate::Transport::Tcp, @@ -3692,7 +3692,7 @@ mod tests { .expect("the dial failed"); let mut announced = server_origin.consume().announced(); - let arrived = moq_clock::timeout(Duration::from_secs(5), announced.next()) + let arrived = kio::clock::timeout(Duration::from_secs(5), announced.next()) .await .expect("the broadcast never reached the server") .expect("the server's origin closed"); @@ -3717,7 +3717,7 @@ mod tests { let peer = url("tcp://peer:1/"); let (client, mut accepted) = flapping(INITIAL, MAX, TIMEOUT, vec![(peer.clone(), Flap::Close)]); - let started = moq_clock::now(); + let started = kio::clock::now(); let err = client .connect(peer) .closed() @@ -3773,7 +3773,7 @@ mod tests { ]; let (client, mut accepted) = flapping(INITIAL, MAX, TIMEOUT, peers); - let started = moq_clock::now(); + let started = kio::clock::now(); let err = client .connect(a.clone()) .closed() diff --git a/rs/moq-tokio/src/failover.rs b/rs/moq-tokio/src/failover.rs index 588aaa664ae..d3c0b55f8b2 100644 --- a/rs/moq-tokio/src/failover.rs +++ b/rs/moq-tokio/src/failover.rs @@ -108,7 +108,7 @@ where // When the next attempt may start: the first as soon as an address resolves, // each later one a stagger after the one before it. - let mut ready = moq_clock::now(); + let mut ready = kio::clock::now(); let mut next_index = 0; let mut start = |addr: SocketAddr, attempts: &mut FuturesUnordered<_>| { @@ -151,7 +151,7 @@ where failures.push((index, Attempt { addr, error: err })); // A failure starts the next candidate immediately (RFC 8305 // section 5) rather than waiting out the stagger delay. - ready = moq_clock::now(); + ready = kio::clock::now(); } } } @@ -162,7 +162,7 @@ where match addr { Some(addr) => { start(addr, &mut attempts); - ready = moq_clock::now() + delay; + ready = kio::clock::now() + delay; } None => exhausted = true, } @@ -175,8 +175,8 @@ where /// /// Resolution can outlast the stagger, in which case the attempt starts as soon /// as an address lands. -async fn pull(candidates: &mut Candidates, ready: moq_clock::Instant) -> Option { - moq_clock::sleep_until(ready).await; +async fn pull(candidates: &mut Candidates, ready: kio::clock::Instant) -> Option { + kio::clock::sleep_until(ready).await; candidates.next().await } @@ -256,7 +256,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn second_wins_when_first_hangs() { - let start = moq_clock::now(); + let start = kio::clock::now(); let res: Result<&str, TestError> = race( Candidates::fixed([addr("1.1.1.1:1"), addr("2.2.2.2:2")]), DEFAULT_RACE, @@ -275,7 +275,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn failure_starts_the_next_attempt_immediately() { - let start = moq_clock::now(); + let start = kio::clock::now(); let res: Result<&str, TestError> = race( Candidates::fixed([addr("1.1.1.1:1"), addr("2.2.2.2:2")]), DEFAULT_RACE, @@ -304,7 +304,7 @@ mod tests { if dest == addr("1.1.1.1:1") { Err(TestError::Dial("network unreachable")) } else { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; Err(TestError::Dial("invalid peer certificate")) } }, @@ -330,7 +330,7 @@ mod tests { Duration::from_millis(10), |dest| async move { if dest == addr("1.1.1.1:1") { - moq_clock::sleep(Duration::from_secs(30)).await; + kio::clock::sleep(Duration::from_secs(30)).await; Err(TestError::Dial("timed out")) } else { Err(TestError::Dial("invalid peer certificate")) @@ -387,7 +387,7 @@ mod tests { std::future::pending().await } else { drop(guard); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; Ok("second") } } @@ -400,7 +400,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn zero_delay_dials_all_at_once() { - let start = moq_clock::now(); + let start = kio::clock::now(); let res: Result<&str, TestError> = race( Candidates::fixed([addr("1.1.1.1:1"), addr("2.2.2.2:2")]), Duration::ZERO, @@ -433,7 +433,7 @@ mod tests { /// parallel queries exist for. #[tokio::test(start_paused = true)] async fn dials_the_first_address_to_resolve() { - let start = moq_clock::now(); + let start = kio::clock::now(); let res: Result<&str, TestError> = race( Candidates::slow( (&[], Duration::from_secs(30)), @@ -458,7 +458,7 @@ mod tests { /// carrying the address that works, takes a second. #[tokio::test(start_paused = true)] async fn a_late_candidate_starts_as_soon_as_it_resolves() { - let start = moq_clock::now(); + let start = kio::clock::now(); let res: Result<&str, TestError> = race( Candidates::slow( (&[addr("[2001:db8::1]:1"), addr("1.1.1.1:1")], Duration::from_secs(1)), diff --git a/rs/moq-tokio/src/iroh.rs b/rs/moq-tokio/src/iroh.rs index 71265d945ec..40f2aee5c06 100644 --- a/rs/moq-tokio/src/iroh.rs +++ b/rs/moq-tokio/src/iroh.rs @@ -604,7 +604,7 @@ mod tests { /// same pairing as the quic backend. #[test] fn congestion_factory_maps_each_family() { - let now = moq_clock::now().into_std(); + let now = kio::clock::now().into_std(); let mtu = 1200; let loss = congestion_factory(CongestionControl::Loss).build(now, mtu); diff --git a/rs/moq-tokio/src/jemalloc.rs b/rs/moq-tokio/src/jemalloc.rs index 4fb1e6c5b2b..971b44b5c56 100644 --- a/rs/moq-tokio/src/jemalloc.rs +++ b/rs/moq-tokio/src/jemalloc.rs @@ -188,7 +188,7 @@ mod tests { if super::sampling() { break; } - moq_clock::sleep(std::time::Duration::from_millis(10)).await; + kio::clock::sleep(std::time::Duration::from_millis(10)).await; } assert!(super::sampling(), "SIGUSR1 did not start sampling"); diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index a4ac473d50c..a5d25359d17 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -506,7 +506,7 @@ impl Config { /// forever: for zero, and for a timeout too long for the clock to reach. pub fn resolved_timeout(&self) -> Option { let timeout = self.timeout.map(Into::into).unwrap_or(DEFAULT_TIMEOUT); - (!timeout.is_zero() && moq_clock::now().checked_add(timeout).is_some()).then_some(timeout) + (!timeout.is_zero() && kio::clock::now().checked_add(timeout).is_some()).then_some(timeout) } /// The QUIC listener settings, for a runtime outside this crate to map. diff --git a/rs/moq-tokio/src/mdns.rs b/rs/moq-tokio/src/mdns.rs index fd8c6460833..3428373bfa2 100644 --- a/rs/moq-tokio/src/mdns.rs +++ b/rs/moq-tokio/src/mdns.rs @@ -712,12 +712,12 @@ fn addr_url(addr: SocketAddr) -> Option { /// refusing to start over one of those would be wrong; an error only decides the /// outcome if *nothing* announces. async fn announced(monitor: &mdns_sd::Receiver) -> Result<()> { - let deadline = moq_clock::now() + ANNOUNCE_TIMEOUT; + let deadline = kio::clock::now() + ANNOUNCE_TIMEOUT; // Kept so a total failure reports why rather than just "timed out". let mut failure = None; loop { - let event = match moq_clock::timeout_at(deadline, monitor.recv_async()).await { + let event = match kio::clock::timeout_at(deadline, monitor.recv_async()).await { Ok(Ok(event)) => event, // The daemon died, or nothing announced in time. Either way the mesh is // not live, which is exactly what the caller is gating on. @@ -1185,7 +1185,7 @@ mod tests { } } }; - moq_clock::timeout(std::time::Duration::from_secs(30), wait) + kio::clock::timeout(std::time::Duration::from_secs(30), wait) .await .unwrap_or_else(|_| panic!("timed out discovering {fingerprint}")) } @@ -1251,7 +1251,7 @@ mod tests { async fn stopped(monitor: mdns_sd::Receiver) { // Monitor senders belong to the worker, not the command handle. Their // closure proves the worker released them rather than just accepting Exit. - moq_clock::timeout(std::time::Duration::from_secs(5), async { + kio::clock::timeout(std::time::Duration::from_secs(5), async { while monitor.recv_async().await.is_ok() {} }) .await @@ -1373,7 +1373,7 @@ mod tests { "exactly one side of the pair dials" ); - let leaked = moq_clock::timeout(std::time::Duration::from_secs(2), async { + let leaked = kio::clock::timeout(std::time::Duration::from_secs(2), async { loop { match foreign.recv().await { Some(Event::Found(peer)) diff --git a/rs/moq-tokio/src/quic/backend.rs b/rs/moq-tokio/src/quic/backend.rs index 15844109424..7fe873b77a3 100644 --- a/rs/moq-tokio/src/quic/backend.rs +++ b/rs/moq-tokio/src/quic/backend.rs @@ -890,7 +890,7 @@ mod tests { let client = Client::new(&config, &crate::quic::Config::default()).expect("client init"); let url: Url = format!("http://127.0.0.1:{port}/").parse().unwrap(); let versions = moq_net::Versions::default(); - let result = moq_clock::timeout(Duration::from_secs(5), client.connect(&tls, url.into(), &versions)) + let result = kio::clock::timeout(Duration::from_secs(5), client.connect(&tls, url.into(), &versions)) .await .expect("dial timed out"); assert!( @@ -936,7 +936,7 @@ mod tests { let incoming = server.accept().await.expect("incoming connection"); super::accept(incoming, versions.alpns()).await }; - let result = moq_clock::timeout(Duration::from_secs(5), async { tokio::try_join!(dial, accept) }) + let result = kio::clock::timeout(Duration::from_secs(5), async { tokio::try_join!(dial, accept) }) .await .expect("handshake timed out"); let (_client, _server) = result.expect("pinned connection failed"); @@ -976,7 +976,7 @@ mod tests { #[test] fn congestion_factory_maps_each_family() { let init = moq_congestion::Init { - now: moq_clock::Instant::now(), + now: kio::clock::Instant::now(), mtu: 1200, rtt: std::time::Duration::from_millis(333), max_pacing_rate: None, @@ -1041,7 +1041,7 @@ mod tests { // Bound the whole connect + accept + assert flow so a handshake // regression fails fast instead of stalling CI. - moq_clock::timeout(Duration::from_secs(5), async move { + kio::clock::timeout(Duration::from_secs(5), async move { let session = client .connect(&tls, url.into(), &moq_net::Versions::default()) .await diff --git a/rs/moq-tokio/src/quic/driver/connection.rs b/rs/moq-tokio/src/quic/driver/connection.rs index 1772bcb3046..a9efe424d20 100644 --- a/rs/moq-tokio/src/quic/driver/connection.rs +++ b/rs/moq-tokio/src/quic/driver/connection.rs @@ -832,7 +832,7 @@ pub(crate) struct State { handle: ConnectionHandle, on_handshake_data: Option>, connected: bool, - timer: Option, + timer: Option, timer_deadline: Option, conn_events: mpsc::UnboundedReceiver, endpoint_events: mpsc::UnboundedSender<(ConnectionHandle, EndpointEvent)>, @@ -1027,7 +1027,7 @@ impl State { delay.reset(deadline); } None => { - self.timer = Some(moq_clock::sleep_until(deadline)); + self.timer = Some(kio::clock::sleep_until(deadline)); } _ => {} } diff --git a/rs/moq-tokio/src/quic/driver/mod.rs b/rs/moq-tokio/src/quic/driver/mod.rs index ff5d9dad20d..e76e92a18b0 100644 --- a/rs/moq-tokio/src/quic/driver/mod.rs +++ b/rs/moq-tokio/src/quic/driver/mod.rs @@ -54,7 +54,7 @@ mod runtime; pub mod send; mod work_limiter; -pub(crate) use moq_clock::Instant; +pub(crate) use kio::clock::Instant; pub(crate) use std::time::Duration; pub use moq_quic::{ diff --git a/rs/moq-tokio/src/quic/driver/tests.rs b/rs/moq-tokio/src/quic/driver/tests.rs index 661fe168c4e..a595f16b4e9 100755 --- a/rs/moq-tokio/src/quic/driver/tests.rs +++ b/rs/moq-tokio/src/quic/driver/tests.rs @@ -22,7 +22,7 @@ use std::{ use crate::quic::driver::runtime::{AsyncUdpSocket, wrap_udp_socket}; use crate::quic::driver::{Duration, Instant}; use bytes::{Buf, Bytes}; -use moq_clock::{sleep, timeout}; +use kio::clock::{sleep, timeout}; use moq_quic::{ ConnectionId, RandomConnectionIdGenerator, Version, crypto::rustls::{QuicClientConfig, QuicServerConfig}, @@ -2373,7 +2373,7 @@ async fn close_during_handshake_does_not_wait_for_silent_peer() { // Let the driver send the Initial. tokio::task::yield_now().await; - let start = moq_clock::now(); + let start = kio::clock::now(); client.close(0u32.into(), "closing").await; let elapsed = start.elapsed(); assert!(connect.await.is_err()); diff --git a/rs/moq-tokio/src/quic/web/session.rs b/rs/moq-tokio/src/quic/web/session.rs index 0add2bdd50b..d010c538840 100644 --- a/rs/moq-tokio/src/quic/web/session.rs +++ b/rs/moq-tokio/src/quic/web/session.rs @@ -513,7 +513,7 @@ impl Session { } // Wait for the peer to close the CONNECT stream after receiving the capsule. - if moq_clock::timeout(timeout, self.conn.closed()).await.is_err() { + if kio::clock::timeout(timeout, self.conn.closed()).await.is_err() { tracing::debug!("timeout waiting for peer to close; force-closing connection"); self.conn.close(http3_code, ""); } @@ -1447,7 +1447,7 @@ mod tests { ) }; // Without the header the server never surfaces the streams, so bound the wait. - let (uni, bi) = moq_clock::timeout(Duration::from_secs(10), read).await.unwrap(); + let (uni, bi) = kio::clock::timeout(Duration::from_secs(10), read).await.unwrap(); assert!(matches!(uni, crate::quic::web::ReadError::Reset(7)), "{uni:?}"); assert!(matches!(bi, crate::quic::web::ReadError::Reset(8)), "{bi:?}"); } @@ -1485,7 +1485,7 @@ mod tests { (uni, client_bi.read_chunk(usize::MAX).await) }; // Without the header the server never surfaces the stream, so bound the wait. - let (uni, bi) = moq_clock::timeout(Duration::from_secs(10), read).await.unwrap(); + let (uni, bi) = kio::clock::timeout(Duration::from_secs(10), read).await.unwrap(); assert!(matches!(uni, Err(crate::quic::web::ReadError::Reset(0))), "{uni:?}"); assert!(matches!(bi, Err(crate::quic::web::ReadError::Reset(0))), "{bi:?}"); } @@ -1520,7 +1520,7 @@ mod tests { } } }; - let (uni, bi) = moq_clock::timeout(Duration::from_secs(10), async { + let (uni, bi) = kio::clock::timeout(Duration::from_secs(10), async { tokio::join!(stopped(uni), stopped(bi)) }) .await diff --git a/rs/moq-tokio/src/resolve.rs b/rs/moq-tokio/src/resolve.rs index 2cf0819cf0e..5fd76d8ce91 100644 --- a/rs/moq-tokio/src/resolve.rs +++ b/rs/moq-tokio/src/resolve.rs @@ -329,7 +329,7 @@ impl Candidates { // stagger between attempts dwarfs this. if self.count == 0 && !self.delayed && self.full.pending() { self.delayed = true; - let _ = moq_clock::timeout(self.delay, self.answer_full()).await; + let _ = kio::clock::timeout(self.delay, self.answer_full()).await; continue; } @@ -588,7 +588,7 @@ impl Query { Self { call: Some(tokio::spawn(async move { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; Ok(addrs) })), ..Default::default() @@ -764,7 +764,7 @@ mod tests { ); candidates.delay = DEFAULT_RESOLUTION_DELAY; - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(candidates.next().await, Some(addr("[2001:db8::1]:443"))); assert_eq!( start.elapsed(), @@ -784,7 +784,7 @@ mod tests { ); candidates.delay = DEFAULT_RESOLUTION_DELAY; - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(candidates.next().await, Some(addr("1.2.3.4:443"))); assert_eq!(start.elapsed(), DEFAULT_RESOLUTION_DELAY); } @@ -797,7 +797,7 @@ mod tests { candidates.delay = DEFAULT_RESOLUTION_DELAY; candidates.full.call = Some(tokio::spawn(async { Err(io::Error::other("nope")) })); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(candidates.next().await, Some(addr("1.2.3.4:443"))); assert_eq!(start.elapsed(), Duration::ZERO); } @@ -814,7 +814,7 @@ mod tests { assert_eq!(candidates.next().await, Some(addr("1.2.3.4:443"))); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(candidates.next().await, Some(addr("5.6.7.8:443"))); assert_eq!(start.elapsed(), Duration::ZERO); } @@ -839,7 +839,7 @@ mod tests { assert_eq!(candidates.next().await, Some(addr("1.2.3.4:443"))); assert_eq!(candidates.next().await, Some(addr("5.6.7.8:443"))); - let start = moq_clock::now(); + let start = kio::clock::now(); assert_eq!(candidates.next().await, Some(addr("[2001:db8::1]:443"))); assert_eq!(start.elapsed(), Duration::from_secs(1), "waited on the full answer"); assert_eq!(candidates.next().await, None, "an address was dialed twice"); @@ -867,7 +867,7 @@ mod tests { // That dial is in flight when the full answer lands, so the next candidate // comes from the platform's order rather than the fast lane's leftovers. - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; assert_eq!(candidates.next().await, Some(addr("[2001:db8::1]:443"))); assert_eq!(candidates.next().await, Some(addr("5.6.7.8:443"))); assert_eq!(candidates.next().await, None); diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index 7df8b36c812..39be3b6a5c1 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -922,7 +922,9 @@ impl Listener { if !server.versions.alpns().contains(&peer.protocol()) { return Err(WebRtcError::Protocol(peer.protocol().to_string()).into()); } - let deadline = server.timeout.and_then(|timeout| moq_clock::now().checked_add(timeout)); + let deadline = server + .timeout + .and_then(|timeout| kio::clock::now().checked_add(timeout)); let handshake = async { let opened = peer.channel().await?; @@ -1045,8 +1047,8 @@ struct Setup { impl Setup { /// When a connection accepted now must finish its handshake, or `None` to wait /// forever, including past the clock's range. - fn deadline(&self) -> Option { - moq_clock::now().checked_add(self.timeout?) + fn deadline(&self) -> Option { + kio::clock::now().checked_add(self.timeout?) } } @@ -1064,7 +1066,7 @@ impl Setup { async fn accept_request( server: &moq_net::Server, session: S, - deadline: Option, + deadline: Option, ) -> crate::Result<(moq_net::server::Handshake, Option)> where S: moq_net::transport::poll::Boxable + Send + Sync, @@ -1081,7 +1083,7 @@ where pub(crate) async fn accept_websocket( session: qmux::Session, options: crate::websocket::Options, - deadline: Option, + deadline: Option, ) -> crate::Result { let (request, deadline) = accept_request(&options.server, session, deadline).await?; let authority = options.url.host_str().filter(|h| !h.is_empty()).map(str::to_owned); @@ -1102,7 +1104,7 @@ pub(crate) async fn accept_websocket( /// When an accepted connection's handshake must be done, and how to tell the peer /// it wasn't. struct Deadline { - at: moq_clock::Instant, + at: kio::clock::Instant, /// Closes the session with the timeout code. close: Box, } @@ -1116,7 +1118,7 @@ impl Deadline { all(feature = "uds", unix), feature = "webrtc" ))] - fn new(at: moq_clock::Instant, session: S) -> Self + fn new(at: kio::clock::Instant, session: S) -> Self where S: moq_net::transport::poll::Session + Send + Sync, { @@ -1140,7 +1142,7 @@ impl Deadline { let Some(deadline) = deadline else { return handshake.await; }; - match moq_clock::timeout_at(deadline.at, handshake).await { + match kio::clock::timeout_at(deadline.at, handshake).await { Ok(res) => res, Err(_) => { (deadline.close)(); @@ -1163,7 +1165,7 @@ impl Deadline { feature = "webrtc" ))] async fn within( - deadline: Option, + deadline: Option, handshake: impl Future>, ) -> crate::Result where @@ -1172,7 +1174,7 @@ where let Some(deadline) = deadline else { return Ok(handshake.await?); }; - match moq_clock::timeout_at(deadline, handshake).await { + match kio::clock::timeout_at(deadline, handshake).await { Ok(res) => Ok(res?), Err(_) => Err(moq_net::Error::Timeout.into()), } @@ -1564,7 +1566,7 @@ struct Incoming { link: Link, authority: Option, identity: Option, - deadline: Option, + deadline: Option, active: moq_net::server::Active, } @@ -2158,7 +2160,7 @@ mod tests { tokio::time::pause(); task.abort(); let _ = task.await; - let closed = moq_clock::timeout(std::time::Duration::from_secs(1), rx.recv()).await; + let closed = kio::clock::timeout(std::time::Duration::from_secs(1), rx.recv()).await; assert!(matches!(closed, Ok(None)), "stalled handshake outlived its accept loop"); } @@ -2188,7 +2190,7 @@ mod tests { tokio::time::pause(); task.abort(); let _ = task.await; - let closed = moq_clock::timeout(std::time::Duration::from_secs(1), rx.recv()).await; + let closed = kio::clock::timeout(std::time::Duration::from_secs(1), rx.recv()).await; assert!(matches!(closed, Ok(None)), "stalled handshake outlived its accept loop"); } @@ -2488,7 +2490,7 @@ mod tests { server: moq_net::Server::new(), timeout: Some(timeout), }; - let start = moq_clock::now(); + let start = kio::clock::now(); let Err(err) = accept_request( &setup.server, crate::transport::Session::new(peer.clone(), moq_net::transport::Address::Uri), @@ -2525,7 +2527,7 @@ mod tests { .await; } }); - moq_clock::sleep(std::time::Duration::from_secs(1)).await; + kio::clock::sleep(std::time::Duration::from_secs(1)).await; client.abort(); let bytes = std::mem::take(&mut *recorder.written.lock().unwrap()); assert!(!bytes.is_empty(), "the client never wrote its SETUP"); @@ -2538,7 +2540,7 @@ mod tests { server: moq_net::Server::new(), timeout: Some(timeout), }; - let start = moq_clock::now(); + let start = kio::clock::now(); let Ok((request, deadline)) = accept_request( &setup.server, crate::transport::Session::new(peer.clone(), moq_net::transport::Address::Uri), @@ -2614,7 +2616,7 @@ mod tests { tokio::spawn(moq_net::time::run(driver)); let _client = connect.await.unwrap(); - moq_clock::sleep(timeout * 2).await; + kio::clock::sleep(timeout * 2).await; assert!( client.closed().now_or_never().is_none(), "a completed handshake was closed at its deadline" @@ -2650,7 +2652,7 @@ mod tests { moq_net::time::run(driver).await }); - let request = moq_clock::timeout(std::time::Duration::from_secs(5), listener.accept()) + let request = kio::clock::timeout(std::time::Duration::from_secs(5), listener.accept()) .await .expect("a stalled upgrade blocked the accept loop"); assert!(request.is_some()); @@ -2785,14 +2787,14 @@ mod tests { // `serve` binds the socket; wait for it. Keep the last error, since a bind // failure is the only clue to why it never showed up. const MAX_DELAY: std::time::Duration = std::time::Duration::from_millis(100); - let deadline = moq_clock::now() + std::time::Duration::from_secs(5); + let deadline = kio::clock::now() + std::time::Duration::from_secs(5); let mut delay = std::time::Duration::from_millis(1); while let Err(err) = tokio::net::UnixStream::connect(&path).await { - assert!(moq_clock::now() < deadline, "unix listener never bound: {err}"); + assert!(kio::clock::now() < deadline, "unix listener never bound: {err}"); // Bound to its own statement so the (non-Send) rng doesn't live across the // await, which would make this future unspawnable. let wait = delay.mul_f64(0.5 + rand::rng().random::() / 2.0); - moq_clock::sleep(wait).await; + kio::clock::sleep(wait).await; delay = (delay * 2).min(MAX_DELAY); } @@ -2806,14 +2808,14 @@ mod tests { .init(Default::default()) .expect("client init") .with_subscriber(subscriber); - let session = moq_clock::timeout(TIMEOUT, client.connect(url).established()) + let session = kio::clock::timeout(TIMEOUT, client.connect(url).established()) .await .expect("connect timeout") .expect("connect"); // Without the server's publisher the session announces nothing, so this is // where the regression shows up. - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announced)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announced)) .await .expect("announce timeout") .expect("origin closed"); @@ -2827,12 +2829,12 @@ mod tests { .subscribe(None) .await .expect("subscribe"); - let mut group = moq_clock::timeout(TIMEOUT, track.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("recv group timeout") .expect("recv group") .expect("track closed early"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read frame timeout") .expect("read frame") diff --git a/rs/moq-tokio/src/tcp.rs b/rs/moq-tokio/src/tcp.rs index ac4ac1616f4..a48e68997b7 100644 --- a/rs/moq-tokio/src/tcp.rs +++ b/rs/moq-tokio/src/tcp.rs @@ -341,7 +341,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; } } } @@ -484,14 +484,14 @@ mod tests { let session = request.ok().await.unwrap(); (server, identity, sni, session) }); - let dialed = moq_clock::timeout(Duration::from_secs(5), client.connect(url).established()) + let dialed = kio::clock::timeout(Duration::from_secs(5), client.connect(url).established()) .await .expect("dial timed out"); if dialed.is_err() { accept.abort(); return None; } - let (server, identity, sni, _session) = moq_clock::timeout(Duration::from_secs(5), accept) + let (server, identity, sni, _session) = kio::clock::timeout(Duration::from_secs(5), accept) .await .expect("accept timed out") .expect("accept task panicked"); @@ -521,16 +521,16 @@ mod tests { .with_reconnect(false) .connect(url.clone()) }; - let untrusted = moq_clock::timeout(Duration::from_secs(5), dial(false).established()).await; + let untrusted = kio::clock::timeout(Duration::from_secs(5), dial(false).established()).await; assert!( matches!(untrusted, Ok(Err(_))), "an untrusted certificate must be refused" ); - let _session = moq_clock::timeout(Duration::from_secs(5), dial(true).established()) + let _session = kio::clock::timeout(Duration::from_secs(5), dial(true).established()) .await .expect("trusted dial timed out") .expect("trusted dial failed"); - let (_server, _accepted) = moq_clock::timeout(Duration::from_secs(5), accept) + let (_server, _accepted) = kio::clock::timeout(Duration::from_secs(5), accept) .await .expect("accept timed out") .expect("accept task panicked"); @@ -551,7 +551,7 @@ mod tests { let blackhole: net::SocketAddr = "192.0.2.1:9".parse().unwrap(); let candidates = crate::resolve::Candidates::fixed([blackhole, addr]); - let session = moq_clock::timeout( + let session = kio::clock::timeout( Duration::from_secs(5), connect_addrs(candidates, &["moq-test"], Duration::from_millis(50)), ) diff --git a/rs/moq-tokio/src/tls.rs b/rs/moq-tokio/src/tls.rs index f0e34daf576..f25bda0f1da 100644 --- a/rs/moq-tokio/src/tls.rs +++ b/rs/moq-tokio/src/tls.rs @@ -1732,13 +1732,13 @@ impl PeerIdentity { } /// The leaf certificate's `notAfter`, if it parses, saturated to the wall range. - pub fn expiry(&self) -> Option { + pub fn expiry(&self) -> Option { let leaf = self.chain.first()?; let (_, cert) = x509_parser::parse_x509_certificate(leaf).ok()?; // Before 1970 reads as the epoch and past 2554 as the last wall time: no // representable now compares differently against the saturated value. let secs = u64::try_from(cert.validity().not_after.timestamp()).unwrap_or(0); - Some(moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(secs))) + Some(kio::clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(secs))) } } @@ -2304,7 +2304,7 @@ mod tests { let parsed = PeerIdentity::from_any(Some(identity)).expect("chain parsed"); let expiry = parsed.expiry().expect("expiry parsed"); assert_eq!( - expiry.saturating_duration_since(moq_clock::Wall::UNIX_EPOCH).as_secs(), + expiry.saturating_duration_since(kio::clock::Wall::UNIX_EPOCH).as_secs(), 2_000_000_000 ); } @@ -2312,10 +2312,10 @@ mod tests { #[cfg(feature = "quic")] #[test] fn peer_expiry_saturates_to_the_wall_range() { - let last = moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); + let last = kio::clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); // rcgen's default notAfter is in 4096. for (seconds, expected) in [ - (-1, moq_clock::Wall::UNIX_EPOCH), + (-1, kio::clock::Wall::UNIX_EPOCH), (18_446_744_074, last), (67_090_118_400, last), ] { diff --git a/rs/moq-tokio/src/transport.rs b/rs/moq-tokio/src/transport.rs index bdc9515dedb..338a3aa9b5d 100644 --- a/rs/moq-tokio/src/transport.rs +++ b/rs/moq-tokio/src/transport.rs @@ -1282,7 +1282,7 @@ mod tests { drop(send); // The write stays blocked forever: the reset must not wait behind it. - moq_clock::timeout(std::time::Duration::from_secs(1), async { + kio::clock::timeout(std::time::Duration::from_secs(1), async { while fake.resets.lock().unwrap().is_empty() { tokio::task::yield_now().await; } @@ -1331,7 +1331,7 @@ mod tests { drop(recv); // The read stays blocked forever: the stop must not wait behind it. - moq_clock::timeout(std::time::Duration::from_secs(1), async { + kio::clock::timeout(std::time::Duration::from_secs(1), async { while stops.lock().unwrap().is_empty() { tokio::task::yield_now().await; } diff --git a/rs/moq-tokio/src/unix.rs b/rs/moq-tokio/src/unix.rs index 71aa79c9b01..b02bb67f6d1 100644 --- a/rs/moq-tokio/src/unix.rs +++ b/rs/moq-tokio/src/unix.rs @@ -376,7 +376,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; } } } diff --git a/rs/moq-tokio/src/webrtc.rs b/rs/moq-tokio/src/webrtc.rs index e6b2c003a02..41afa162dcf 100644 --- a/rs/moq-tokio/src/webrtc.rs +++ b/rs/moq-tokio/src/webrtc.rs @@ -816,7 +816,7 @@ async fn next_write(writes: Option<&mut mpsc::Receiver>) -> Option /// A str0m connection with this socket's host candidates. fn rtc(locals: &[SocketAddr]) -> Result { - let mut rtc = Rtc::builder().build(moq_clock::now().into_std()); + let mut rtc = Rtc::builder().build(kio::clock::now().into_std()); for &addr in locals { let candidate = str0m::Candidate::host(addr, "udp").map_err(|err| Error::Candidate(err.to_string()))?; rtc.add_local_candidate(candidate); diff --git a/rs/moq-tokio/src/webrtc/resolver.rs b/rs/moq-tokio/src/webrtc/resolver.rs index 32ddb0d7c0c..f5d846d564a 100644 --- a/rs/moq-tokio/src/webrtc/resolver.rs +++ b/rs/moq-tokio/src/webrtc/resolver.rs @@ -181,7 +181,7 @@ mod tests { let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; let _in_flight = InFlight(self.in_flight.clone()); self.most_in_flight.fetch_max(now, Ordering::SeqCst); - moq_clock::sleep(DELAY).await; + kio::clock::sleep(DELAY).await; let index: u8 = host .trim_start_matches("host") .trim_end_matches(".local") @@ -223,7 +223,7 @@ mod tests { let (tx, mut commands) = mpsc::channel(1); let resolver = Resolver::spawn(tx, fake.clone()); - let start = moq_clock::now(); + let start = kio::clock::now(); resolver.add((0..10).map(|i| line(i, i)).collect()).await.unwrap(); for i in 0..10 { let candidate = next(&mut commands).await.unwrap(); @@ -244,7 +244,7 @@ mod tests { resolver.add(vec![line(1, 1)]).await.unwrap(); // The third waits for the first to finish, rather than queueing. - let start = moq_clock::now(); + let start = kio::clock::now(); resolver.add(vec![line(2, 2)]).await.unwrap(); assert_eq!(start.elapsed(), DELAY); assert_eq!(fake.most_in_flight.load(Ordering::SeqCst), 1); @@ -282,7 +282,7 @@ mod tests { // The query in flight is cancelled before it answers, the rest of the batch // is skipped, and signaling sees the peer is closed. - moq_clock::sleep(DELAY / 2).await; + kio::clock::sleep(DELAY / 2).await; assert_eq!(fake.in_flight.load(Ordering::SeqCst), 0); assert!(matches!(resolver.add(vec![line(2, 2)]).await, Err(Error::Closed))); assert_eq!(fake.queries(), ["host0.local"]); diff --git a/rs/moq-tokio/src/webrtc/tests.rs b/rs/moq-tokio/src/webrtc/tests.rs index c76e43562c5..f35b8b85688 100644 --- a/rs/moq-tokio/src/webrtc/tests.rs +++ b/rs/moq-tokio/src/webrtc/tests.rs @@ -53,7 +53,7 @@ async fn transfer(offerer: &Offerer, answerer: &Answerer, payload: &[u8]) { .init() .unwrap() .with_subscriber(subscribed); - let (_server, _client) = moq_clock::timeout(TIMEOUT, async { + let (_server, _client) = kio::clock::timeout(TIMEOUT, async { tokio::join!(server, async { client.connect_webrtc(offerer).await.unwrap() }) }) .await @@ -69,7 +69,7 @@ async fn transfer(offerer: &Offerer, answerer: &Answerer, payload: &[u8]) { let mut group = track.recv_group().await.unwrap().unwrap(); group.read_frame().await.unwrap().unwrap() }; - let frame = moq_clock::timeout(TIMEOUT, read).await.expect("transfer timed out"); + let frame = kio::clock::timeout(TIMEOUT, read).await.expect("transfer timed out"); assert!(frame.payload[..] == *payload, "the frame arrived corrupted"); } @@ -108,7 +108,7 @@ async fn channels() -> (Offerer, Answerer, Opened, Opened) { .await .unwrap(); offerer.accept(&answer).await.unwrap(); - let (sent, received) = moq_clock::timeout(TIMEOUT, async { tokio::join!(offerer.channel(), answerer.channel()) }) + let (sent, received) = kio::clock::timeout(TIMEOUT, async { tokio::join!(offerer.channel(), answerer.channel()) }) .await .expect("the channel did not open"); (offerer, answerer, sent.unwrap(), received.unwrap()) @@ -128,7 +128,7 @@ async fn unread_records_do_not_stall_the_writer() { let (_offerer, _answerer, sent, received) = channels().await; let (mut writer, mut reader) = (sent.channel.writer, received.channel.reader); let count = 8 * SEND_WINDOW / RECORD_SIZE as usize; - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { for index in 0..count { writer.send(record(index)).await.unwrap(); } @@ -151,7 +151,7 @@ async fn ignoring_flow_control_closes_the_channel() { let budget = RECEIVE_WINDOW + READ_SLACK; let within = (budget / RECORD_SIZE) as usize; let (mut writer, mut reader) = (sent.channel.writer, received.channel.reader); - moq_clock::timeout(TIMEOUT, async { + kio::clock::timeout(TIMEOUT, async { for index in 0..within + 8 { if writer.send(record(index)).await.is_err() { break; @@ -217,7 +217,7 @@ async fn server_reflexive_candidate_is_offered_and_selected() { .await .unwrap(); - let candidate = moq_clock::timeout(TIMEOUT, offerer.candidate()) + let candidate = kio::clock::timeout(TIMEOUT, offerer.candidate()) .await .expect("gathering timed out") .expect("no server-reflexive candidate"); @@ -266,7 +266,7 @@ async fn unsignaled_protocol_is_refused() { .listen() .await .unwrap(); - let accepted = moq_clock::timeout(TIMEOUT, listener.accept_webrtc(&answerer)) + let accepted = kio::clock::timeout(TIMEOUT, listener.accept_webrtc(&answerer)) .await .expect("the channel did not open"); assert!(matches!( @@ -351,7 +351,7 @@ fn construction_queues_no_output() { idle(rtc); } - let mut offerer = Rtc::builder().build(moq_clock::now().into_std()); + let mut offerer = Rtc::builder().build(kio::clock::now().into_std()); host(&mut offerer, "127.0.0.1:5000"); host(&mut offerer, "[::1]:5000"); let mut api = offerer.sdp_api(); @@ -359,7 +359,7 @@ fn construction_queues_no_output() { let (offer, _pending) = api.apply().unwrap(); idle(&mut offerer); - let mut answerer = Rtc::builder().build(moq_clock::now().into_std()); + let mut answerer = Rtc::builder().build(kio::clock::now().into_std()); host(&mut answerer, "127.0.0.1:5001"); host(&mut answerer, "[::1]:5001"); answerer.sdp_api().accept_offer(offer).unwrap(); diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index 8c501fae1e7..2850c5d4de6 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -169,7 +169,7 @@ where crate::runtime::scope(async move { let timeout = options.timeout.unwrap_or(crate::listen::DEFAULT_TIMEOUT); let deadline = (!timeout.is_zero()) - .then(|| moq_clock::now().checked_add(timeout)) + .then(|| kio::clock::now().checked_add(timeout)) .flatten(); // A vanished peer sends no FIN. Ping and timeout bound the same stale-session // lifetime that QUIC's idle timeout bounds on the native path. @@ -413,7 +413,7 @@ pub(crate) async fn connect( // TODO if let chain match resolved.delay { delay if !delay.is_zero() && !WEBSOCKET_WON.lock().unwrap().contains(&key) => { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; tracing::debug!(peer = %crate::connect::Endpoint(&url), delay_ms = %delay.as_millis(), "QUIC not yet connected, attempting WebSocket fallback"); } _ => {} @@ -757,7 +757,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - moq_clock::sleep(delay).await; + kio::clock::sleep(delay).await; } } } diff --git a/rs/moq-tokio/tests/integration/backend.rs b/rs/moq-tokio/tests/integration/backend.rs index 2503c67f166..395111c4ad0 100644 --- a/rs/moq-tokio/tests/integration/backend.rs +++ b/rs/moq-tokio/tests/integration/backend.rs @@ -178,18 +178,18 @@ async fn connect_test(config: ConnectTest<'_>) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); @@ -201,13 +201,13 @@ async fn connect_test(config: ConnectTest<'_>) { .await .expect("consume_track failed"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") @@ -294,14 +294,14 @@ async fn sni_test() { // The SNI names the second certificate, so that is the one to pin. Hold the // connection: dropping it would tear the session down mid-assertion. - let _matched = moq_clock::timeout(TIMEOUT, dial("alt.localhost", &fingerprints[1])) + let _matched = kio::clock::timeout(TIMEOUT, dial("alt.localhost", &fingerprints[1])) .await .expect("client connect timed out") .expect("client connect failed"); // The same pin with the other SNI must fail: the server serves the first // certificate there, whose fingerprint the client does not accept. - let wrong = moq_clock::timeout(TIMEOUT, dial("localhost", &fingerprints[1])) + let wrong = kio::clock::timeout(TIMEOUT, dial("localhost", &fingerprints[1])) .await .expect("client connect timed out"); assert!(wrong.is_err(), "pinning the wrong certificate must fail the handshake"); @@ -361,13 +361,13 @@ async fn reload_test() { std::fs::rename(&new_cert, &cert).expect("rotate cert"); std::fs::rename(&new_key, &key).expect("rotate key"); - let reloaded = moq_clock::timeout(TIMEOUT, async { + let reloaded = kio::clock::timeout(TIMEOUT, async { loop { let now = certificates.fingerprints(); if now != before { return now; } - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; } }) .await @@ -493,11 +493,11 @@ async fn mtls_test(scheme: &str, reject: bool) { }); // The mTLS cases assert on the connect result itself, so keep it a `Result`. - let connection = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let connection = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out"); - let has_cert = moq_clock::timeout(TIMEOUT, identity_rx) + let has_cert = kio::clock::timeout(TIMEOUT, identity_rx) .await .expect("identity inspection timed out") .expect("server dropped identity result"); @@ -510,7 +510,7 @@ async fn mtls_test(scheme: &str, reject: bool) { if reject { server_handle.abort(); } else { - moq_clock::timeout(TIMEOUT, server_handle) + kio::clock::timeout(TIMEOUT, server_handle) .await .expect("server task timed out") .expect("server task panicked") @@ -579,7 +579,7 @@ async fn iroh_versions_disjoint() { .with_iroh_addrs(server_addrs); let url: url::Url = format!("iroh://{server_endpoint_id}/room").parse().unwrap(); - let result = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let result = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out"); assert!(result.is_err(), "the default set must not reach a wip-only listener"); @@ -687,18 +687,18 @@ async fn iroh_connect_test(version: Option<&str>) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); @@ -710,13 +710,13 @@ async fn iroh_connect_test(version: Option<&str>) { .await .expect("consume_track failed"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track closed prematurely"); - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") @@ -777,7 +777,7 @@ async fn quic_client_close_reaches_server() { }); }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timed out") .expect("no incoming connection"); @@ -788,7 +788,7 @@ async fn quic_client_close_reaches_server() { .unwrap() .expect("client thread panicked"); - let err = moq_clock::timeout(TIMEOUT, session.closed()) + let err = kio::clock::timeout(TIMEOUT, session.closed()) .await .expect("the server never heard the close"); assert!(!err.to_string().contains("timed out"), "{err}"); @@ -861,7 +861,7 @@ async fn quic_client_close_drains_finished_track() { }); }); - let mut request = moq_clock::timeout(TIMEOUT, server.accept()) + let mut request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timed out") .expect("no incoming connection"); @@ -888,33 +888,33 @@ async fn quic_client_close_drains_finished_track() { } }); - moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); - let mut track = moq_clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) + let mut track = kio::clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) .await .expect("subscribe timed out") .expect("subscribe failed"); started.await.expect("client started closing"); - let mut group = moq_clock::timeout(TIMEOUT, track.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track ended before the group"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") .expect("group ended before the frame"); assert!(frame.payload[..] == expected[..], "the frame arrives whole"); - let end = moq_clock::timeout(TIMEOUT, track.recv_group()) + let end = kio::clock::timeout(TIMEOUT, track.recv_group()) .await .expect("the track end timed out"); match end { @@ -998,7 +998,7 @@ async fn quic_client_close_drains_migrated_predecessor() { }); }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timed out") .expect("no incoming connection"); @@ -1011,15 +1011,15 @@ async fn quic_client_close_drains_migrated_predecessor() { .await .expect("server handshake failed"); - moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); - let mut track = moq_clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) + let mut track = kio::clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) .await .expect("subscribe timed out") .expect("subscribe failed"); @@ -1038,7 +1038,7 @@ async fn quic_client_close_drains_migrated_predecessor() { .expect("group ended before the frame"); (frame.payload, track.recv_group().await.map(|group| group.is_some())) }); - moq_clock::timeout(TIMEOUT, subscribed_rx) + kio::clock::timeout(TIMEOUT, subscribed_rx) .await .expect("the subscription never reached the client") .expect("client thread panicked"); @@ -1047,7 +1047,7 @@ async fn quic_client_close_drains_migrated_predecessor() { .drain() .send(moq_tokio::moq_net::goaway::Goaway::new()) .expect("send goaway"); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("the replacement never dialed") .expect("no incoming connection"); @@ -1056,12 +1056,12 @@ async fn quic_client_close_drains_migrated_predecessor() { .ok() .await .expect("server handshake failed"); - moq_clock::timeout(TIMEOUT, migrated_rx) + kio::clock::timeout(TIMEOUT, migrated_rx) .await .expect("the client never migrated") .expect("client thread panicked"); - let (payload, end) = moq_clock::timeout(TIMEOUT, received) + let (payload, end) = kio::clock::timeout(TIMEOUT, received) .await .expect("the track timed out") .expect("reader panicked"); @@ -1126,7 +1126,7 @@ async fn quic_client_close_keeps_predecessor_handover() { // Close while the old session is still inside its handover window. while connection.status().await.expect("connection stopped") != moq_tokio::Status::Migrating {} - let start = moq_clock::now(); + let start = kio::clock::now(); let err = connection.close().await.expect_err("the predecessor cannot drain"); let elapsed = start.elapsed(); client.close().await; @@ -1134,7 +1134,7 @@ async fn quic_client_close_keeps_predecessor_handover() { }) }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timed out") .expect("no incoming connection"); @@ -1147,21 +1147,21 @@ async fn quic_client_close_keeps_predecessor_handover() { .await .expect("server handshake failed"); - moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); - let broadcast = moq_clock::timeout(TIMEOUT, consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); - let mut track = moq_clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) + let mut track = kio::clock::timeout(TIMEOUT, broadcast.track("video").unwrap().subscribe(None)) .await .expect("subscribe timed out") .expect("subscribe failed"); // Receiving is what sends the subscription, so read in the background. let _received = tokio::spawn(async move { track.recv_group().await.map(|group| group.is_some()) }); - moq_clock::timeout(TIMEOUT, subscribed_rx) + kio::clock::timeout(TIMEOUT, subscribed_rx) .await .expect("the subscription never reached the client") .expect("client thread panicked"); diff --git a/rs/moq-tokio/tests/integration/broadcast.rs b/rs/moq-tokio/tests/integration/broadcast.rs index 934ad2d19fd..5ef6505e9ea 100644 --- a/rs/moq-tokio/tests/integration/broadcast.rs +++ b/rs/moq-tokio/tests/integration/broadcast.rs @@ -84,20 +84,20 @@ async fn broadcast_test(scheme: &str, client_version: Option<&str>, server_versi }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); // Wait for the broadcast announcement. - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); @@ -111,14 +111,14 @@ async fn broadcast_test(scheme: &str, client_version: Option<&str>, server_versi .expect("consume_track failed"); // Read one group. - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track closed prematurely"); // Read one frame and verify the payload. - let frame = moq_clock::timeout(TIMEOUT, group_sub.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group_sub.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") @@ -195,18 +195,18 @@ async fn lite05_timestamp_roundtrip(scheme: &str) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); @@ -218,14 +218,14 @@ async fn lite05_timestamp_roundtrip(scheme: &str) { .await .expect("consume_track failed"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track closed prematurely"); for &expected_us in &frames { - let mut frame_sub = moq_clock::timeout(TIMEOUT, group_sub.next_frame()) + let mut frame_sub = kio::clock::timeout(TIMEOUT, group_sub.next_frame()) .await .expect("next_frame timed out") .expect("next_frame failed") @@ -308,32 +308,32 @@ async fn lite05_fetch_roundtrip(scheme: &str) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); // Fetch group 0 directly, without subscribing. No live producer holds the group // on the client, so this issues a wire FETCH upstream. - let mut group_sub = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(0, None).await }) + let mut group_sub = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(0, None).await }) .await .expect("fetch timed out") .expect("fetch failed"); assert_eq!(group_sub.sequence, 0); for &expected_us in &frames { - let mut frame_sub = moq_clock::timeout(TIMEOUT, group_sub.next_frame()) + let mut frame_sub = kio::clock::timeout(TIMEOUT, group_sub.next_frame()) .await .expect("next_frame timed out") .expect("next_frame failed") @@ -346,7 +346,7 @@ async fn lite05_fetch_roundtrip(scheme: &str) { } // The fetched group ends cleanly (stream FIN → no more frames). - let end = moq_clock::timeout(TIMEOUT, group_sub.next_frame()) + let end = kio::clock::timeout(TIMEOUT, group_sub.next_frame()) .await .expect("next_frame timed out") .expect("next_frame failed"); @@ -419,40 +419,40 @@ async fn transport_fetch_roundtrip(version: &str) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); - let fetched = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(1, None).await }) + let fetched = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(1, None).await }) .await .expect("fetch timed out"); let mut group = fetched.expect("fetch failed"); assert_eq!(group.sequence, 1); for frame in 0..2 { - let payload = moq_clock::timeout(TIMEOUT, group.read_frame()) + let payload = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read timed out") .expect("read failed") .expect("group ended early"); assert_eq!(payload.payload, bytes::Bytes::from(format!("1-{frame}"))); } - let end = moq_clock::timeout(TIMEOUT, group.read_frame()) + let end = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read timed out") .expect("read failed"); assert!(end.is_none(), "the group ends after its frames"); - let refused = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(7, None).await }) + let refused = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(7, None).await }) .await .expect("fetch timed out"); assert!( @@ -540,35 +540,35 @@ async fn lite05_fetch_during_subscribe(scheme: &str) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("client connect timed out") .expect("client connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timed out") .expect("origin closed"); assert_eq!(update.prefix.as_str(), "test"); assert!(active, "expected announce, got retraction"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timed out") .expect("announced broadcast resolves"); // Subscribe (starts at the latest group) and read the live group, which // establishes the upstream subscription and leaves it active. - let mut track_sub = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().subscribe(None).await }) + let mut track_sub = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().subscribe(None).await }) .await .expect("subscribe timed out") .expect("subscribe failed"); - let mut live = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut live = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") .expect("track closed prematurely"); assert_eq!(live.sequence, 1); - let frame = moq_clock::timeout(TIMEOUT, live.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, live.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") @@ -578,12 +578,12 @@ async fn lite05_fetch_during_subscribe(scheme: &str) { // While the subscription is still held and active, fetch the older group. The // relay doesn't have it cached (subscription started at the latest), so this // must issue a wire FETCH concurrently with the live subscription. - let mut fetched = moq_clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(0, None).await }) + let mut fetched = kio::clock::timeout(TIMEOUT, async { bc.track("video").unwrap().fetch_group(0, None).await }) .await .expect("fetch timed out") .expect("fetch failed"); assert_eq!(fetched.sequence, 0); - let frame = moq_clock::timeout(TIMEOUT, fetched.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, fetched.read_frame()) .await .expect("fetch read_frame timed out") .expect("fetch read_frame failed") @@ -645,17 +645,17 @@ async fn broadcast_moq_lite_05_untimed_track() { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("connect timeout") .expect("connect failed"); - let (update, active) = moq_clock::timeout(TIMEOUT, next_update(&mut announcements)) + let (update, active) = kio::clock::timeout(TIMEOUT, next_update(&mut announcements)) .await .expect("announce timeout") .expect("origin closed"); assert!(active, "expected announce"); - let bc = moq_clock::timeout(TIMEOUT, sub_consumer.request(&update.prefix, None)) + let bc = kio::clock::timeout(TIMEOUT, sub_consumer.request(&update.prefix, None)) .await .expect("request timed out") .expect("announced broadcast resolves"); @@ -667,13 +667,13 @@ async fn broadcast_moq_lite_05_untimed_track() { .await .expect("consume_track failed"); - let mut group_sub = moq_clock::timeout(TIMEOUT, track_sub.recv_group()) + let mut group_sub = kio::clock::timeout(TIMEOUT, track_sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed"); - let frame_sub = moq_clock::timeout(TIMEOUT, group_sub.next_frame()) + let frame_sub = kio::clock::timeout(TIMEOUT, group_sub.next_frame()) .await .expect("next_frame timeout") .expect("next_frame failed") @@ -741,7 +741,7 @@ async fn broadcast_moq_transport_22_current_group_join() { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("connect timed out") .expect("connect failed"); @@ -749,17 +749,17 @@ async fn broadcast_moq_transport_22_current_group_join() { let (announced, announced_active) = next_announce(&mut announcements).await; assert_eq!(announced.prefix.as_str(), "test"); assert!(announced_active, "expected an announce"); - let remote = moq_clock::timeout(TIMEOUT, sub_consumer.request(&announced.prefix, None)) + let remote = kio::clock::timeout(TIMEOUT, sub_consumer.request(&announced.prefix, None)) .await .expect("request timed out") .expect("announced broadcast resolves"); - let mut subscriber = moq_clock::timeout(TIMEOUT, async { remote.track("video").unwrap().subscribe(None).await }) + let mut subscriber = kio::clock::timeout(TIMEOUT, async { remote.track("video").unwrap().subscribe(None).await }) .await .expect("subscribe timed out") .expect("subscribe failed"); - let mut joined = moq_clock::timeout(TIMEOUT, subscriber.recv_group()) + let mut joined = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) .await .expect("recv_group timed out") .expect("recv_group failed") @@ -767,7 +767,7 @@ async fn broadcast_moq_transport_22_current_group_join() { assert_eq!(joined.sequence, 0); async fn read(group: &mut moq_net::group::Consumer) -> Option> { - moq_clock::timeout(TIMEOUT, group.read_frame()) + kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timed out") .expect("read_frame failed") @@ -793,7 +793,7 @@ async fn broadcast_moq_transport_22_current_group_join() { /// Wait for the next announce event, failing the test on a timeout or a closed origin. async fn next_announce(announcements: &mut moq_net::announce::Consumer) -> (moq_net::announce::Announce, bool) { - moq_clock::timeout(TIMEOUT, next_update(announcements)) + kio::clock::timeout(TIMEOUT, next_update(announcements)) .await .expect("announce timeout") .expect("origin closed") @@ -850,7 +850,7 @@ async fn announce_lifecycle_test(version: &str) { }); let client = client.with_subscriber(sub_origin); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client, url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client, url)) .await .expect("connect timeout") .expect("connect failed"); @@ -913,12 +913,12 @@ async fn announce_lifecycle_test(version: &str) { async fn read_payloads(sub: &mut moq_net::track::Subscriber, count: usize) -> Vec { let mut payloads = Vec::new(); for _ in 0..count { - let mut group = moq_clock::timeout(TIMEOUT, sub.recv_group()) + let mut group = kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("recv_group timeout") .expect("recv_group failed") .expect("track closed"); - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("read_frame timeout") .expect("read_frame failed") @@ -1044,7 +1044,7 @@ async fn broadcast_route_migration() { let client = config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{port}").parse().unwrap(); async move { - moq_clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub), url)) + kio::clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub), url)) .await .expect("connect timeout") .expect("connect failed") @@ -1063,7 +1063,7 @@ async fn broadcast_route_migration() { let subscription = moq_net::track::Subscription::default() .with_range(1..) .with_max_delay(Duration::from_secs(10)); - let broadcast = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timeout") .expect("routed broadcast resolves"); @@ -1184,19 +1184,19 @@ async fn rejoin_skips_a_stale_warm_cache(version: &str) { config.version = vec![version.parse().unwrap()]; let client = config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); - let (_client, session) = moq_clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) + let (_client, session) = kio::clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) .await .expect("connect timeout") .expect("connect failed"); assert!(next_announce(&mut announcements).await.1); - let remote = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let remote = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timeout") .expect("broadcast resolves"); let budget = moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100)); async fn recv(sub: &mut moq_net::track::Subscriber, version: &str) -> u64 { - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .unwrap_or_else(|_| panic!("{version}: recv timeout")) .expect("recv failed") @@ -1214,7 +1214,7 @@ async fn rejoin_skips_a_stale_warm_cache(version: &str) { drop(sub); // The front parks the track and cancels upstream, while the publisher moves on. - moq_clock::timeout(TIMEOUT, crate::unwanted(live.demand())) + kio::clock::timeout(TIMEOUT, crate::unwanted(live.demand())) .await .expect("upstream never canceled") .expect("track open"); @@ -1307,26 +1307,26 @@ async fn rejoin_replays_a_current_warm_cache(version: &str, open: bool) { config.version = vec![version.parse().unwrap()]; let client = config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); - let (_client, session) = moq_clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) + let (_client, session) = kio::clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) .await .expect("connect timeout") .expect("connect failed"); assert!(next_announce(&mut announcements).await.1); - let remote = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let remote = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timeout") .expect("broadcast resolves"); async fn recv(sub: &mut moq_net::track::Subscriber, ctx: &str) -> moq_net::group::Consumer { - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .unwrap_or_else(|_| panic!("{ctx}: recv_group timeout")) .expect("recv_group failed") .expect("track closed") } async fn read(group: &mut moq_net::group::Consumer, ctx: &str) -> String { - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .unwrap_or_else(|_| panic!("{ctx}: read_frame timeout")) .expect("read_frame failed") @@ -1364,7 +1364,7 @@ async fn rejoin_replays_a_current_warm_cache(version: &str, open: bool) { drop(reading); drop(sub); // The front parks the track and cancels upstream before the next round rejoins. - moq_clock::timeout(TIMEOUT, crate::unwanted(live.demand())) + kio::clock::timeout(TIMEOUT, crate::unwanted(live.demand())) .await .unwrap_or_else(|_| panic!("{ctx}: upstream never canceled")) .expect("track open"); @@ -1437,7 +1437,7 @@ async fn route_reannounce_test(version: Option<&str>) { } let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) .await .expect("connect timeout") .expect("connect failed"); @@ -1447,7 +1447,7 @@ async fn route_reannounce_test(version: Option<&str>) { assert!(active, "expected announce"); let initial = update.route; - let broadcast = moq_clock::timeout(TIMEOUT, sub_consumer.request("test", None)) + let broadcast = kio::clock::timeout(TIMEOUT, sub_consumer.request("test", None)) .await .expect("request timeout") .expect("routed broadcast resolves"); @@ -1624,7 +1624,7 @@ async fn max_age_test(version: &str, published: Option) -> Option) -> Option(()) }); - let (_client, connection) = moq_clock::timeout(TIMEOUT, connect_once(test_client(), url)) + let (_client, connection) = kio::clock::timeout(TIMEOUT, connect_once(test_client(), url)) .await .expect("connect timed out") .expect("connect failed"); - let err = moq_clock::timeout(TIMEOUT, connection.closed()) + let err = kio::clock::timeout(TIMEOUT, connection.closed()) .await .expect("close timed out") .expect_err("a rejected session must surface as an error"); @@ -3387,7 +3387,7 @@ async fn reconnect_stops_on_a_session_level_rejection() { // default), so `closed` resolving within TIMEOUT proves it stopped on the // rejection itself. let connection = test_client().connect(url); - let err = moq_clock::timeout(TIMEOUT, connection.closed()) + let err = kio::clock::timeout(TIMEOUT, connection.closed()) .await .expect("a rejected session must stop the reconnect loop promptly") .expect_err("a rejected session must surface as an error"); @@ -3416,7 +3416,7 @@ async fn one_shot_surfaces_a_session_level_rejection() { }); let connection = test_client().with_reconnect(false).connect(url); - moq_clock::timeout(TIMEOUT, connection.closed()) + kio::clock::timeout(TIMEOUT, connection.closed()) .await .expect("close timed out") .expect_err("a rejected session must surface as an error"); @@ -3444,14 +3444,14 @@ async fn abort_carries_its_code_to_the_peer() { Ok::<_, anyhow::Error>(()) }); - let connection = moq_clock::timeout(TIMEOUT, test_client().connect(url).established()) + let connection = kio::clock::timeout(TIMEOUT, test_client().connect(url).established()) .await .expect("connect timed out") .expect("connect failed"); connection.abort(moq_net::Error::App(42)); - let reason = moq_clock::timeout(TIMEOUT, reason_rx) + let reason = kio::clock::timeout(TIMEOUT, reason_rx) .await .expect("the peer never saw the close") .expect("server task gone"); diff --git a/rs/moq-tokio/tests/integration/close_code.rs b/rs/moq-tokio/tests/integration/close_code.rs index 7ffeee01cf2..a3517f491fd 100644 --- a/rs/moq-tokio/tests/integration/close_code.rs +++ b/rs/moq-tokio/tests/integration/close_code.rs @@ -81,7 +81,7 @@ async fn client_error(url: &str, websocket: bool) -> moq_tokio::Error { let client = config.init(Default::default()).expect("failed to init client"); let connection = client.with_reconnect(false).connect(url.parse::().unwrap()); - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { match connection.established().await { Ok(connection) => connection.closed().await.expect_err("closed without an error"), Err(err) => err, diff --git a/rs/moq-tokio/tests/integration/max_age.rs b/rs/moq-tokio/tests/integration/max_age.rs index d3ec25f0414..f47a3c08582 100644 --- a/rs/moq-tokio/tests/integration/max_age.rs +++ b/rs/moq-tokio/tests/integration/max_age.rs @@ -126,7 +126,7 @@ async fn relay(version: moq_net::Version, javascript: Option) -> anyhow::R #[tokio::test] async fn max_age_relay_rust() { for version in ["moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { - moq_clock::timeout(TIMEOUT, relay(version.parse().unwrap(), None)) + kio::clock::timeout(TIMEOUT, relay(version.parse().unwrap(), None)) .await .unwrap() .unwrap(); @@ -138,7 +138,7 @@ async fn max_age_relay_rust() { async fn max_age_relay_javascript() { for version in ["moq-lite-07-wip", "moq-transport-18", "moq-transport-22"] { for publish in [false, true] { - moq_clock::timeout(TIMEOUT, relay(version.parse().unwrap(), Some(publish))) + kio::clock::timeout(TIMEOUT, relay(version.parse().unwrap(), Some(publish))) .await .unwrap() .unwrap(); diff --git a/rs/moq-tokio/tests/integration/migrate.rs b/rs/moq-tokio/tests/integration/migrate.rs index ed67b7ab37d..10d63624c89 100644 --- a/rs/moq-tokio/tests/integration/migrate.rs +++ b/rs/moq-tokio/tests/integration/migrate.rs @@ -89,7 +89,7 @@ fn publish(origin: &moq_net::origin::Producer, name: &str, route: moq_net::origi .write_frame(moq_net::Timestamp::ZERO, payload) .expect("write frame"); group.finish().expect("finish group"); - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; } }); } @@ -130,7 +130,7 @@ fn view(origin: &moq_net::origin::Producer, name: &str) -> tokio::sync::mpsc::Un /// Receive `count` sequences, after any already queued. async fn read(sequences: &mut tokio::sync::mpsc::UnboundedReceiver, count: usize, into: &mut Vec) { for _ in 0..count { - let sequence = moq_clock::timeout(TIMEOUT, sequences.recv()) + let sequence = kio::clock::timeout(TIMEOUT, sequences.recv()) .await .expect("no group arrived") .expect("the viewer stopped"); @@ -147,7 +147,7 @@ fn assert_contiguous(who: &str, sequences: &[u64]) { /// Wait for `old` to close, and check it closed cleanly rather than at a cap. async fn assert_closes(old: &moq_net::Session) { - let closed = moq_clock::timeout(TIMEOUT, old.closed()) + let closed = kio::clock::timeout(TIMEOUT, old.closed()) .await .expect("the old session waited for the handover cap"); assert!( @@ -167,7 +167,7 @@ async fn a_migrated_session_closes_once_nothing_flows() { let (port, mut sessions) = relay(&origin, versions.clone()).await; let local = moq_tokio::origin::spawn(); let _connection = connect(&local, port, versions); - let old = moq_clock::timeout(TIMEOUT, sessions.recv()) + let old = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("the client never connected") .expect("the relay stopped"); @@ -183,7 +183,7 @@ async fn a_migrated_session_closes_once_nothing_flows() { old.drain().send(moq_net::goaway::Goaway::new()).expect("send goaway"); // Held, since dropping the last handle closes the replacement. - let _replacement = moq_clock::timeout(TIMEOUT, sessions.recv()) + let _replacement = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("the client never redialed") .expect("the relay stopped"); @@ -206,7 +206,7 @@ async fn a_predecessor_serves_until_its_last_subscription_leaves() { let (port, mut sessions) = relay(&origin, Vec::new()).await; let local = moq_tokio::origin::spawn(); let _connection = connect(&local, port, Vec::new()); - let old = moq_clock::timeout(TIMEOUT, sessions.recv()) + let old = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("the client never connected") .expect("the relay stopped"); @@ -218,7 +218,7 @@ async fn a_predecessor_serves_until_its_last_subscription_leaves() { old.drain().send(moq_net::goaway::Goaway::new()).expect("send goaway"); // Held, since dropping the last handle closes the replacement. - let _replacement = moq_clock::timeout(TIMEOUT, sessions.recv()) + let _replacement = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("the client never redialed") .expect("the relay stopped"); diff --git a/rs/moq-tokio/tests/integration/receive_credit.rs b/rs/moq-tokio/tests/integration/receive_credit.rs index e2ac41fdb0f..a573ef35294 100644 --- a/rs/moq-tokio/tests/integration/receive_credit.rs +++ b/rs/moq-tokio/tests/integration/receive_credit.rs @@ -156,8 +156,8 @@ async fn setup_through( fn rand_seed() -> u64 { let seed = match std::env::var("MOQ_SHAPER_SEED") { Ok(seed) => seed.parse().expect("MOQ_SHAPER_SEED is not a u64"), - Err(_) => moq_clock::wall() - .saturating_duration_since(moq_clock::Wall::UNIX_EPOCH) + Err(_) => kio::clock::wall() + .saturating_duration_since(kio::clock::Wall::UNIX_EPOCH) .as_nanos() as u64, }; println!("MOQ_SHAPER_SEED={seed}"); @@ -167,7 +167,7 @@ fn rand_seed() -> u64 { /// Broadcast `room`, once the peer announces it into `origin`. async fn room(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Consumer { let consumer = origin.consume(); - moq_clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) + kio::clock::timeout(TIMEOUT, consumer.follow("room", None).unwrap().available()) .await .expect("resolve timeout") .expect("broadcast resolves") @@ -175,7 +175,7 @@ async fn room(origin: &moq_net::origin::Producer) -> moq_net::broadcast::Consume /// Subscribe to track `name` of `remote` at `priority`. async fn subscribe(remote: &moq_net::broadcast::Consumer, name: &str, priority: i8) -> moq_net::track::Subscriber { - moq_clock::timeout( + kio::clock::timeout( TIMEOUT, remote .track(name) @@ -203,7 +203,7 @@ impl Setup { /// The next group, which must arrive in time. async fn next_group(sub: &mut moq_net::track::Subscriber) -> moq_net::group::Consumer { - moq_clock::timeout(TIMEOUT, sub.recv_group()) + kio::clock::timeout(TIMEOUT, sub.recv_group()) .await .expect("group timed out") .expect("group") @@ -213,7 +213,7 @@ async fn next_group(sub: &mut moq_net::track::Subscriber) -> moq_net::group::Con /// The next frame's payload, which must arrive in time. async fn next_frame(sub: &mut moq_net::track::Subscriber) -> Bytes { let mut group = next_group(sub).await; - moq_clock::timeout(TIMEOUT, group.read_frame()) + kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("frame timed out") .expect("frame") @@ -224,7 +224,7 @@ async fn next_frame(sub: &mut moq_net::track::Subscriber) -> Bytes { /// The next group's first frame, still arriving. async fn partial_frame(sub: &mut moq_net::track::Subscriber) -> moq_net::frame::Consumer { let mut group = next_group(sub).await; - moq_clock::timeout(TIMEOUT, group.next_frame()) + kio::clock::timeout(TIMEOUT, group.next_frame()) .await .expect("frame header timed out") .expect("frame") @@ -235,7 +235,7 @@ async fn partial_frame(sub: &mut moq_net::track::Subscriber) -> moq_net::frame:: async fn read_partial(frame: &mut moq_net::frame::Consumer, bytes: usize) { let mut seen = 0; while seen < bytes { - let chunk = moq_clock::timeout(TIMEOUT, frame.read_chunk()) + let chunk = kio::clock::timeout(TIMEOUT, frame.read_chunk()) .await .expect("partial payload timed out") .expect("chunk") @@ -374,7 +374,7 @@ async fn lite_frame_past_the_window_gives_way() { let mut partial = partial_frame(&mut low_sub).await; loop { - match moq_clock::timeout(TIMEOUT, partial.read_chunk()) + match kio::clock::timeout(TIMEOUT, partial.read_chunk()) .await .expect("the partial frame neither failed nor grew") { @@ -528,7 +528,7 @@ impl Reversed { }); } for _ in 0..stopped { - moq_clock::timeout(TIMEOUT, rx.recv()) + kio::clock::timeout(TIMEOUT, rx.recv()) .await .expect("stop timed out") .expect("a writer"); @@ -668,7 +668,7 @@ async fn javascript_partial_frame_gives_way(version: &str) { .expect("spawn bun"); let mut commands = child.stdin.take().unwrap(); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("connect timeout") .expect("request"); @@ -700,7 +700,7 @@ async fn javascript_partial_frame_gives_way(version: &str) { commands.write_all(&b"high\n"[..]).await.unwrap(); assert_eq!(next_frame(&mut high).await, vec![2u8; WINDOW / 2], "{version}"); loop { - let chunk = moq_clock::timeout(TIMEOUT, partial.read_chunk()) + let chunk = kio::clock::timeout(TIMEOUT, partial.read_chunk()) .await .expect("stop timed out"); match chunk { @@ -715,7 +715,7 @@ async fn javascript_partial_frame_gives_way(version: &str) { assert_eq!(next_frame(&mut low).await, &b"after"[..], "{version}"); drop(commands); - let status = moq_clock::timeout(TIMEOUT, child.wait()) + let status = kio::clock::timeout(TIMEOUT, child.wait()) .await .expect("sender exit timed out") .expect("sender"); @@ -785,7 +785,7 @@ async fn measure(cell: Cell, profile: Option, bytes: usize) let track = setup.broadcast.create_track(name.as_str(), timed()).unwrap(); // Groups in flight fall behind the live edge, so a zero budget would skip them. let subscription = Subscription::default().with_max_delay(TIMEOUT); - let sub = moq_clock::timeout(TIMEOUT, setup.remote.track(&name).unwrap().subscribe(subscription)) + let sub = kio::clock::timeout(TIMEOUT, setup.remote.track(&name).unwrap().subscribe(subscription)) .await .expect("subscribe timeout") .expect("subscribe"); @@ -794,7 +794,7 @@ async fn measure(cell: Cell, profile: Option, bytes: usize) let rounds = (bytes / cell.frame / cell.streams).max(1); let payload = Bytes::from(vec![7u8; cell.frame]); - let start = moq_clock::now(); + let start = kio::clock::now(); let tasks: Vec<_> = tracks .into_iter() .map(|(track, mut sub)| { @@ -808,7 +808,7 @@ async fn measure(cell: Cell, profile: Option, bytes: usize) for _ in 0..rounds { inflight.acquire().await.unwrap().forget(); let mut group = track.append_group().unwrap(); - sent.lock().unwrap().insert(group.sequence, moq_clock::now()); + sent.lock().unwrap().insert(group.sequence, kio::clock::now()); group.write_frame(Timestamp::ZERO, payload.clone()).unwrap(); group.finish().unwrap(); } @@ -818,7 +818,7 @@ async fn measure(cell: Cell, profile: Option, bytes: usize) let mut latency = Vec::with_capacity(rounds); for _ in 0..rounds { let mut group = next_group(&mut sub).await; - let frame = moq_clock::timeout(TIMEOUT, group.read_frame()) + let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) .await .expect("frame timed out") .expect("frame") diff --git a/rs/moq-tokio/tests/integration/reconnect.rs b/rs/moq-tokio/tests/integration/reconnect.rs index 9aeb10da54b..36deaa7b3c2 100644 --- a/rs/moq-tokio/tests/integration/reconnect.rs +++ b/rs/moq-tokio/tests/integration/reconnect.rs @@ -28,10 +28,10 @@ async fn a_transient_failure_retries_until_the_budget_runs_out() { // Nothing listens on port 1, so every attempt is refused: transient as far as this layer knows. let url: url::Url = "tcp://127.0.0.1:1".parse().expect("failed to parse url"); - let started = moq_clock::now(); + let started = kio::clock::now(); let reconnect = client(backoff).connect(url); - let err = moq_clock::timeout(Duration::from_secs(10), reconnect.closed()) + let err = kio::clock::timeout(Duration::from_secs(10), reconnect.closed()) .await .expect("reconnect loop never gave up") .expect_err("reconnect loop stopped without an error"); @@ -92,7 +92,7 @@ async fn a_handshake_slower_than_the_retry_window_still_lands() { while let Ok((mut client, _)) = proxy.accept().await { let _ = dialed.send(()); tokio::spawn(async move { - moq_clock::sleep(HANDSHAKE).await; + kio::clock::sleep(HANDSHAKE).await; let mut upstream = tokio::net::TcpStream::connect(server_addr) .await .expect("connect to the server"); @@ -113,7 +113,7 @@ async fn a_handshake_slower_than_the_retry_window_still_lands() { session.expect("server stopped accepting"); } res = connection.closed() => panic!("gave up mid-handshake: {res:?}"), - _ = moq_clock::sleep(Duration::from_secs(30)) => panic!("never connected"), + _ = kio::clock::sleep(Duration::from_secs(30)) => panic!("never connected"), } dials.recv().await.expect("proxy stopped"); assert!(dials.try_recv().is_err(), "the first dial was cut short and redialed"); @@ -128,7 +128,7 @@ async fn the_connect_count_advances_on_reconnect() { let url: url::Url = format!("tcp://localhost:{port}/").parse().expect("parse url"); let mut connection = quick_client(Default::default()).connect(url); - let status = moq_clock::timeout(Duration::from_secs(10), connection.status()) + let status = kio::clock::timeout(Duration::from_secs(10), connection.status()) .await .expect("status timed out") .expect("status failed"); @@ -139,9 +139,9 @@ async fn the_connect_count_advances_on_reconnect() { let session = sessions.recv().await.expect("server stopped accepting"); drop(session); - moq_clock::timeout(Duration::from_secs(10), async { + kio::clock::timeout(Duration::from_secs(10), async { while connection.connects() < 2 { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::clock::sleep(Duration::from_millis(10)).await; } }) .await @@ -219,7 +219,7 @@ async fn a_protocol_violation_ends_reconnect() { let result = tokio::select! { result = connection.closed() => result, _ = sessions.recv() => panic!("redialed after a protocol violation"), - _ = moq_clock::sleep(Duration::from_secs(10)) => panic!("protocol failure did not end reconnect"), + _ = kio::clock::sleep(Duration::from_secs(10)) => panic!("protocol failure did not end reconnect"), }; task.abort(); let _ = task.await; @@ -244,7 +244,7 @@ async fn a_redirect_to_another_host_is_refused_by_default() { let url: url::Url = format!("tcp://localhost:{port_a}/").parse().expect("parse url"); let connection = quick_client(Default::default()).connect(url); - let first = moq_clock::timeout(Duration::from_secs(10), sessions_a.recv()) + let first = kio::clock::timeout(Duration::from_secs(10), sessions_a.recv()) .await .expect("first dial timed out") .expect("server A stopped accepting"); @@ -254,7 +254,7 @@ async fn a_redirect_to_another_host_is_refused_by_default() { .send(moq_net::goaway::Goaway::redirect(format!("tcp://127.0.0.1:{port_b}/"))) .expect("send goaway"); - let err = moq_clock::timeout(Duration::from_secs(10), connection.closed()) + let err = kio::clock::timeout(Duration::from_secs(10), connection.closed()) .await .expect("the refusal never ended the connection") .expect_err("a refused redirect must end with an error"); @@ -278,7 +278,7 @@ async fn follow_still_honors_a_cross_host_redirect() { let url: url::Url = format!("tcp://localhost:{port_a}/").parse().expect("parse url"); let _connection = quick_client(moq_tokio::Redirect::Follow).connect(url); - let first = moq_clock::timeout(Duration::from_secs(10), sessions_a.recv()) + let first = kio::clock::timeout(Duration::from_secs(10), sessions_a.recv()) .await .expect("first dial timed out") .expect("server A stopped accepting"); @@ -288,7 +288,7 @@ async fn follow_still_honors_a_cross_host_redirect() { .send(moq_net::goaway::Goaway::redirect(format!("tcp://127.0.0.1:{port_b}/"))) .expect("send goaway"); - moq_clock::timeout(Duration::from_secs(10), sessions_b.recv()) + kio::clock::timeout(Duration::from_secs(10), sessions_b.recv()) .await .expect("never followed the redirect") .expect("server B stopped accepting"); @@ -303,7 +303,7 @@ async fn a_refused_redirect_skips_configured_fallbacks() { let fallback: url::Url = format!("tcp://127.0.0.1:{port_b}/").parse().expect("fallback URL"); let addrs = moq_tokio::connect::Addrs::new(primary).or(fallback); let connection = quick_client(Default::default()).connect(addrs); - let first = moq_clock::timeout(Duration::from_secs(10), sessions_a.recv()) + let first = kio::clock::timeout(Duration::from_secs(10), sessions_a.recv()) .await .expect("first dial timed out") .expect("server A stopped accepting"); @@ -316,7 +316,7 @@ async fn a_refused_redirect_skips_configured_fallbacks() { .send(moq_net::goaway::Goaway::redirect("tcp://127.0.0.1:1/")) .expect("send goaway"); - let err = moq_clock::timeout(Duration::from_secs(10), connection.closed()) + let err = kio::clock::timeout(Duration::from_secs(10), connection.closed()) .await .expect("the refusal never ended the connection") .expect_err("a refused redirect must end with an error"); @@ -336,7 +336,7 @@ async fn an_empty_goaway_preserves_configured_fallbacks() { let fallback: url::Url = format!("tcp://127.0.0.1:{port_b}/").parse().expect("fallback URL"); let addrs = moq_tokio::connect::Addrs::new(primary).or(fallback); let _connection = quick_client(Default::default()).connect(addrs); - let first = moq_clock::timeout(Duration::from_secs(10), sessions_a.recv()) + let first = kio::clock::timeout(Duration::from_secs(10), sessions_a.recv()) .await .expect("first dial timed out") .expect("server A stopped accepting"); @@ -346,7 +346,7 @@ async fn an_empty_goaway_preserves_configured_fallbacks() { assert!(task_a.await.expect_err("listener was aborted").is_cancelled()); first.drain().send(moq_net::goaway::Goaway::new()).expect("send goaway"); - moq_clock::timeout(Duration::from_secs(10), sessions_b.recv()) + kio::clock::timeout(Duration::from_secs(10), sessions_b.recv()) .await .expect("configured fallback was discarded") .expect("server B stopped accepting"); @@ -424,7 +424,7 @@ async fn rides_out_a_drain(backoff: moq_tokio::Backoff, drained: usize) { session.expect("server stopped accepting"); } res = connection.closed() => panic!("gave up during the drain: {res:?}"), - _ = moq_clock::sleep(Duration::from_secs(30)) => panic!("never landed after the drain"), + _ = kio::clock::sleep(Duration::from_secs(30)) => panic!("never landed after the drain"), } } @@ -437,16 +437,16 @@ const LIFE: Duration = Duration::from_millis(100); /// the client leaves it, as a draining relay does. fn bounce( mut sessions: tokio::sync::mpsc::UnboundedReceiver, - log: tokio::sync::mpsc::UnboundedSender, + log: tokio::sync::mpsc::UnboundedSender, uri: impl Fn(usize) -> String + Send + 'static, ) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { for n in 0.. { let Some(session) = sessions.recv().await else { return }; - let _ = log.send(moq_clock::now()); + let _ = log.send(kio::clock::now()); let uri = uri(n); tokio::spawn(async move { - moq_clock::sleep(LIFE).await; + kio::clock::sleep(LIFE).await; let _ = session.drain().send(moq_net::goaway::Goaway::redirect(uri)); session.closed().await; }); @@ -461,7 +461,7 @@ async fn ping_pong( rotate: bool, ) -> ( url::Url, - tokio::sync::mpsc::UnboundedReceiver, + tokio::sync::mpsc::UnboundedReceiver, Vec>, ) { let (port_a, sessions_a, task_a) = spawn_server().await; @@ -498,13 +498,13 @@ fn bounced_backoff(max: Duration, timeout: Duration) -> moq_tokio::Backoff { /// How long the client took to redial after each of `hops` GOAWAYs: the time between two /// accepts, less the [`LIFE`] the first one served before its GOAWAY. async fn redial_waits( - accepts: &mut tokio::sync::mpsc::UnboundedReceiver, + accepts: &mut tokio::sync::mpsc::UnboundedReceiver, hops: usize, ) -> Vec { let mut last = accepts.recv().await.expect("never connected"); let mut waits = Vec::new(); for hop in 0..hops { - let next = moq_clock::timeout(Duration::from_secs(10), accepts.recv()) + let next = kio::clock::timeout(Duration::from_secs(10), accepts.recv()) .await .unwrap_or_else(|_| panic!("hop {hop}: never redialed")) .expect("the relays stopped"); @@ -568,7 +568,7 @@ async fn a_redirect_loop_stops_at_the_retry_window() { /// and ends the connection, so this fails on a backoff the hops should never take. async fn migrates_without_backing_off( connection: moq_tokio::Connection, - accepts: &mut tokio::sync::mpsc::UnboundedReceiver, + accepts: &mut tokio::sync::mpsc::UnboundedReceiver, hops: usize, ) { tokio::select! { diff --git a/rs/moq-tokio/tests/integration/reset_secret.rs b/rs/moq-tokio/tests/integration/reset_secret.rs index 96f6fbada7a..c883c05224e 100644 --- a/rs/moq-tokio/tests/integration/reset_secret.rs +++ b/rs/moq-tokio/tests/integration/reset_secret.rs @@ -81,7 +81,7 @@ impl Fixture { /// Connect, crash the server and restart it on the same port, then report how the /// client's connection ended once it next sent something. -fn restart(reset_secret: bool) -> Result { +fn restart(reset_secret: bool) -> Result { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let fixture = Fixture::new(); let client = tokio::runtime::Builder::new_current_thread() @@ -124,7 +124,7 @@ fn restart(reset_secret: bool) -> Result Option { .await .expect("write"); - moq_clock::timeout(Duration::from_secs(10), send.stopped()) + kio::clock::timeout(Duration::from_secs(10), send.stopped()) .await .expect("the stream was not stopped") .expect("stopped") diff --git a/rs/moq-tokio/tests/integration/subscription_end_integrity.rs b/rs/moq-tokio/tests/integration/subscription_end_integrity.rs index 75c8370ba21..342ad178f4c 100644 --- a/rs/moq-tokio/tests/integration/subscription_end_integrity.rs +++ b/rs/moq-tokio/tests/integration/subscription_end_integrity.rs @@ -112,12 +112,12 @@ async fn round(drop_session: bool) -> (usize, Option) { // connection's flow-control window when it disconnects. if let Some(tx) = drained.take() { let _ = tx.send(()); - moq_clock::sleep(STALL).await; + kio::clock::sleep(STALL).await; } } }); - let request = moq_clock::timeout(TIMEOUT, server.accept()) + let request = kio::clock::timeout(TIMEOUT, server.accept()) .await .expect("accept timeout") .expect("no incoming connection"); @@ -127,13 +127,13 @@ async fn round(drop_session: bool) -> (usize, Option) { .await .expect("publisher session"); - moq_clock::timeout(TIMEOUT, crate::wanted(track.demand())) + kio::clock::timeout(TIMEOUT, crate::wanted(track.demand())) .await .expect("no subscriber appeared") .expect("track closed"); write_group(&track); - moq_clock::timeout(TIMEOUT, drained_rx) + kio::clock::timeout(TIMEOUT, drained_rx) .await .expect("the head group never arrived") .expect("reader gone"); @@ -152,7 +152,7 @@ async fn round(drop_session: bool) -> (usize, Option) { Some(session) }; - let result = moq_clock::timeout(TIMEOUT, reader) + let result = kio::clock::timeout(TIMEOUT, reader) .await .expect("the subscription never ended") .expect("reader panicked"); diff --git a/rs/moq-tokio/tests/integration/tokens.rs b/rs/moq-tokio/tests/integration/tokens.rs index 515a715e823..b237926bded 100644 --- a/rs/moq-tokio/tests/integration/tokens.rs +++ b/rs/moq-tokio/tests/integration/tokens.rs @@ -88,7 +88,7 @@ fn config(version: &str, tokens: &[&str]) -> moq_tokio::connect::Config { } async fn next(server: &mut Server) -> Seen { - moq_clock::timeout(Duration::from_secs(10), server.seen.recv()) + kio::clock::timeout(Duration::from_secs(10), server.seen.recv()) .await .expect("no handshake arrived") .unwrap() @@ -125,7 +125,7 @@ async fn lite_05_presents_the_token_in_the_url() { token: None, } ); - moq_clock::timeout(Duration::from_secs(10), connection.tokens().answered()) + kio::clock::timeout(Duration::from_secs(10), connection.tokens().answered()) .await .expect("the credential was never answered") .expect("the credential was refused"); @@ -144,7 +144,7 @@ async fn a_refused_credential_redials_with_its_replacement() { tokens.set(vec!["new".parse().unwrap()]); server.release.notify_one(); assert_eq!(next(&mut server).await.token.as_deref(), Some("new")); - moq_clock::timeout(Duration::from_secs(10), tokens.answered()) + kio::clock::timeout(Duration::from_secs(10), tokens.answered()) .await .expect("the replacement was never answered") .expect("the replacement was refused"); @@ -180,7 +180,7 @@ async fn refused_credential_is_terminal(config: moq_tokio::connect::Config) { ); server.release.notify_one(); // A lite client is live before the server's answer, so the refusal may close it after. - let err = moq_clock::timeout(Duration::from_secs(10), async { + let err = kio::clock::timeout(Duration::from_secs(10), async { match connection.established().await { Ok(connection) => connection.closed().await.expect_err("closed without an error"), Err(err) => err, diff --git a/rs/moq-tokio/tests/integration/unannounce.rs b/rs/moq-tokio/tests/integration/unannounce.rs index 450899b928c..bb07235b85b 100644 --- a/rs/moq-tokio/tests/integration/unannounce.rs +++ b/rs/moq-tokio/tests/integration/unannounce.rs @@ -19,13 +19,13 @@ async fn release(unannounce: bool, settle: bool) { if unannounce { broadcast.unannounce(); if settle { - moq_clock::sleep(Duration::from_secs(1)).await; + kio::clock::sleep(Duration::from_secs(1)).await; } } drop(sub); drop(consumer); - moq_clock::timeout(Duration::from_secs(600), crate::unwanted(track.demand())) + kio::clock::timeout(Duration::from_secs(600), crate::unwanted(track.demand())) .await .expect("demand released") .unwrap(); diff --git a/rs/moq-tokio/tests/integration/worker.rs b/rs/moq-tokio/tests/integration/worker.rs index def9086c6b1..fe73385c5c0 100644 --- a/rs/moq-tokio/tests/integration/worker.rs +++ b/rs/moq-tokio/tests/integration/worker.rs @@ -178,7 +178,7 @@ async fn stopping_the_group_closes_its_sessions() { let session = client.connect(url).established().await.expect("connect"); group.shutdown().await; - moq_clock::timeout(std::time::Duration::from_secs(5), session.closed()) + kio::clock::timeout(std::time::Duration::from_secs(5), session.closed()) .await .expect("the session must see the close") .expect_err("a stopped server ends the session"); @@ -270,7 +270,7 @@ async fn spawner_abort_reaches_the_worker() { has_started.await.expect("future started"); task.abort(); - let waited = moq_clock::timeout(std::time::Duration::from_secs(5), was_dropped).await; + let waited = kio::clock::timeout(std::time::Duration::from_secs(5), was_dropped).await; assert!(waited.expect("abort reached the worker").is_err()); group.shutdown().await; } @@ -303,7 +303,7 @@ async fn spawner_abort_races_the_handoff() { // the oneshot the forwarding task has yet to read. task.abort(); - let waited = moq_clock::timeout(std::time::Duration::from_secs(5), was_dropped).await; + let waited = kio::clock::timeout(std::time::Duration::from_secs(5), was_dropped).await; assert!(waited.expect("abort reached the worker").is_err()); group.shutdown().await; } @@ -592,16 +592,16 @@ async fn completing_a_member_stops_its_siblings() { drop(members); assert_eq!( - moq_clock::timeout(std::time::Duration::from_secs(10), done) + kio::clock::timeout(std::time::Duration::from_secs(10), done) .await .expect("completing member hangs") .expect("completing member failed"), "done" ); - moq_clock::timeout(std::time::Duration::from_secs(10), group.finished()) + kio::clock::timeout(std::time::Duration::from_secs(10), group.finished()) .await .expect("the group must report the end of serving"); - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), sibling) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), sibling) .await .expect("a stopped sibling must not hang"); @@ -638,14 +638,14 @@ async fn cancelling_a_member_stops_its_siblings() { drop(members); task_a.abort(); - moq_clock::timeout(std::time::Duration::from_secs(10), group.finished()) + kio::clock::timeout(std::time::Duration::from_secs(10), group.finished()) .await .expect("an abort must end the group"); // The aborted handle reports cancellation; the sibling is stopped with it. - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), task_a) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), task_a) .await .expect("an aborted member must not hang"); - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), task_b) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), task_b) .await .expect("a cancelled sibling must not hang"); @@ -682,15 +682,15 @@ async fn a_panicking_member_stops_its_siblings() { }); drop(members); - let err = moq_clock::timeout(std::time::Duration::from_secs(10), panics) + let err = kio::clock::timeout(std::time::Duration::from_secs(10), panics) .await .expect("a panicking member must not hang") .expect_err("a panic must reach its handle"); assert!(err.is_panic(), "expected a panic, got cancellation"); - moq_clock::timeout(std::time::Duration::from_secs(10), group.finished()) + kio::clock::timeout(std::time::Duration::from_secs(10), group.finished()) .await .expect("a panic must end the group"); - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), sibling) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), sibling) .await .expect("a panicking sibling must not hang"); @@ -719,7 +719,7 @@ async fn shutdown_with_work_in_flight_joins() { group.shutdown().await; for task in tasks { - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), task) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), task) .await .expect("shutdown must stop every member"); } @@ -752,7 +752,7 @@ async fn dropping_the_group_with_work_in_flight_stops() { drop(group); for task in tasks { - let _ = moq_clock::timeout(std::time::Duration::from_secs(10), task) + let _ = kio::clock::timeout(std::time::Duration::from_secs(10), task) .await .expect("dropping the group must stop every member"); } @@ -834,7 +834,7 @@ async fn rotated_identity_reaches_every_worker() { } } }; - let result = moq_clock::timeout(std::time::Duration::from_secs(10), probe).await; + let result = kio::clock::timeout(std::time::Duration::from_secs(10), probe).await; group.shutdown().await; result.expect("every worker must serve both snapshots"); } diff --git a/rs/moq-transcode/Cargo.toml b/rs/moq-transcode/Cargo.toml index 093eda73b8e..2b0bbfc726a 100644 --- a/rs/moq-transcode/Cargo.toml +++ b/rs/moq-transcode/Cargo.toml @@ -45,7 +45,7 @@ tracing = { workspace = true } [dev-dependencies] anyhow = { workspace = true } -moq-clock = { workspace = true, features = ["sim"] } +kio = { workspace = true, features = ["runtime", "sim"] } moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs", "websocket"] } # The tests encode with OpenH264, the one encoder a GPU-less host has, so they # turn it on without making it a default of the library. diff --git a/rs/moq-transcode/src/active.rs b/rs/moq-transcode/src/active.rs index bdf827c66ba..b3290996f39 100644 --- a/rs/moq-transcode/src/active.rs +++ b/rs/moq-transcode/src/active.rs @@ -373,7 +373,7 @@ mod tests { } } - #[moq_clock::test] + #[kio::test] async fn reports_the_ladder_then_each_edge() { let active = Producer::default(); let rung = resolved("video/360p", 360); @@ -401,7 +401,7 @@ mod tests { /// A pipeline is billable when it produces, not when it attaches: a viewer /// subscribing to a rung whose source never sends a frame costs nothing, and /// a transcoder that encodes nothing must not look like one saturating a GPU. - #[moq_clock::test] + #[kio::test] async fn attaching_without_producing_is_not_encoding() { let active = Producer::default(); let rung = resolved("video/360p", 360); @@ -411,7 +411,7 @@ mod tests { let rendition = cursor.next().await.unwrap().rendition; let guard = active.attach(&rung); - moq_clock::sleep(Duration::from_millis(20)).await; + kio::clock::sleep(Duration::from_millis(20)).await; assert!(cursor.try_next().is_none(), "attaching reported an edge"); assert_eq!(rendition.frames(), 0); @@ -427,7 +427,7 @@ mod tests { /// A fetch overlapping the live session is one rendition, not two: a second /// pipeline is not an edge. Its output still counts, because it really did /// encode those frames. - #[moq_clock::test] + #[kio::test] async fn concurrent_pipelines_are_one_rendition() { let active = Producer::default(); let low = resolved("video/240p", 240); @@ -466,7 +466,7 @@ mod tests { /// A fresh cursor must report what is already encoding, or a caller that only /// ever awaits `next` never learns about a rendition that started first. - #[moq_clock::test] + #[kio::test] async fn a_fresh_cursor_reports_the_current_set() { let active = Producer::default(); let rung = resolved("video/480p", 480); @@ -480,7 +480,7 @@ mod tests { // Caught up: it waits for a real change rather than spinning. assert!(cursor.try_next().is_none()); assert!( - moq_clock::timeout(Duration::from_millis(50), cursor.next()) + kio::clock::timeout(Duration::from_millis(50), cursor.next()) .await .is_err() ); @@ -491,7 +491,7 @@ mod tests { /// encoded, so it still bills. This is the group-fetch path, which lives for /// milliseconds. The caller can only bill it because the ladder handed it the /// handle up front. - #[moq_clock::test] + #[kio::test] async fn a_transient_pipeline_is_metered_without_an_edge() { let active = Producer::default(); let rung = resolved("video/360p", 360); @@ -515,7 +515,7 @@ mod tests { /// A caller bills by subtracting two reads, so the counters have to keep /// their totals across an idle gap rather than restarting with the next /// pipeline. - #[moq_clock::test] + #[kio::test] async fn the_counters_survive_an_idle_gap() { let active = Producer::default(); let rung = resolved("video/360p", 360); @@ -540,7 +540,7 @@ mod tests { /// A cursor has to be able to tell "nothing is encoding" from "the transcoder /// is gone", or a metering loop parks forever on a dead transcode. - #[moq_clock::test] + #[kio::test] async fn the_cursor_closes_with_the_producer() { let active = Producer::default(); let mut cursor = active.consume(); diff --git a/rs/moq-transcode/src/catalog.rs b/rs/moq-transcode/src/catalog.rs index 9575d64932b..79d6a64541d 100644 --- a/rs/moq-transcode/src/catalog.rs +++ b/rs/moq-transcode/src/catalog.rs @@ -1011,7 +1011,7 @@ mod tests { let ago = Duration::from_secs(60); let _ = moq_net::time::Instant::now(); tokio::time::advance(ago).await; - let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, moq_clock::wall() - ago).unwrap(); + let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, kio::clock::wall() - ago).unwrap(); let mut input = moq_net::broadcast::Info::default().produce(); let source = moq_mux::catalog::Producer::new(&mut input, moq_mux::catalog::Config::default().with_clock(clock)).unwrap(); diff --git a/rs/moq-transcode/src/lib.rs b/rs/moq-transcode/src/lib.rs index 6defd76cf37..1fbc4ccb2c6 100644 --- a/rs/moq-transcode/src/lib.rs +++ b/rs/moq-transcode/src/lib.rs @@ -479,7 +479,7 @@ mod tests { // Paces the source: a real sleep, since the rungs encode off the // executor and cannot be sequenced by paused-time idle detection. // Also the window the subscribers attach in, before group 0. - moq_clock::sleep(std::time::Duration::from_millis(100)).await; + kio::clock::sleep(std::time::Duration::from_millis(100)).await; let mut group = track.create_group(sequence.into()).unwrap(); for index in 0..frames { let timestamp = (sequence * frames + index) * 33_333; @@ -1084,7 +1084,7 @@ mod tests { assert_eq!(replacement.coded_height, Some(120)); // The retired name aborts rather than finishing: its source did not finish. - let ended = moq_clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) + let ended = kio::clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) .await .expect("the retired rung never ended its track"); assert!( @@ -1179,7 +1179,7 @@ mod tests { // The retired rung ends its track, so a subscriber reselects rather than // stalling. It aborts, since its source did not finish. - let ended = moq_clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) + let ended = kio::clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) .await .expect("the retired rung never ended its track"); assert!( @@ -1191,7 +1191,7 @@ mod tests { // The rung the new picture still fits keeps serving: its subscriber sees // nothing at all, since the source has no media. assert!( - moq_clock::timeout(std::time::Duration::from_millis(100), kept.recv_group()) + kio::clock::timeout(std::time::Duration::from_millis(100), kept.recv_group()) .await .is_err(), "a rung that still fits was retired anyway" @@ -1253,7 +1253,7 @@ mod tests { // Group 0 is still being written from a source group that is still open, so // retiring now has to leave it running until that source group ends. source.resize(160, 90); - moq_clock::timeout( + kio::clock::timeout( std::time::Duration::from_secs(5), await_catalog(&mut catalogs, |snapshot| { !snapshot.video.renditions.contains_key("video/120p") @@ -1263,7 +1263,7 @@ mod tests { .expect("the ladder never retired the rung"); group.finish().unwrap(); - let finished = moq_clock::timeout(std::time::Duration::from_secs(5), async { + let finished = kio::clock::timeout(std::time::Duration::from_secs(5), async { while fetched.read_frame().await?.is_some() {} fetched.finished().await }) @@ -1317,7 +1317,7 @@ mod tests { while demand.wanted_changed().await?.is_none() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(std::time::Duration::from_secs(5), wanted) + kio::clock::timeout(std::time::Duration::from_secs(5), wanted) .await .expect("the rung never asked for its source") .unwrap(); @@ -1328,7 +1328,7 @@ mod tests { while demand.wanted_changed().await?.is_some() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(std::time::Duration::from_secs(5), unwanted) + kio::clock::timeout(std::time::Duration::from_secs(5), unwanted) .await .expect("the idle rung kept its source wanted") .unwrap(); @@ -1469,7 +1469,7 @@ mod tests { rung.info().await.unwrap(); let fetching = rung.fetch_group(7, None); - let mut abandoned = moq_clock::timeout(std::time::Duration::from_secs(5), source_fetches.requested_fill()) + let mut abandoned = kio::clock::timeout(std::time::Duration::from_secs(5), source_fetches.requested_fill()) .await .expect("the fetch never reached the source") .expect("the source track closed"); @@ -1478,7 +1478,7 @@ mod tests { // Leave before a single source frame exists. Encoding can only happen // if the handler keeps this fetch. drop(fetching); - moq_clock::timeout(std::time::Duration::from_secs(5), async { + kio::clock::timeout(std::time::Duration::from_secs(5), async { while abandoned.wanted_changed().await.is_some() {} }) .await @@ -1487,7 +1487,7 @@ mod tests { // The handler dropped the output request with the caller, so this is a // fresh request rather than a join of the one still encoding. let retry = rung.fetch_group(7, None); - let fresh = moq_clock::timeout(std::time::Duration::from_secs(5), source_fetches.requested_fill()) + let fresh = kio::clock::timeout(std::time::Duration::from_secs(5), source_fetches.requested_fill()) .await .expect("the retry never fetched the source") .expect("the source track closed"); @@ -1500,7 +1500,7 @@ mod tests { write_keyframe(&mut group); group.finish().unwrap(); - let mut fetched = moq_clock::timeout(std::time::Duration::from_secs(5), retry) + let mut fetched = kio::clock::timeout(std::time::Duration::from_secs(5), retry) .await .expect("the retry stalled") .expect("the retry was answered by the abandoned fetch"); @@ -1585,7 +1585,7 @@ mod tests { // The only demand ends with output group 0 still open. drop(fetching); - moq_clock::sleep(std::time::Duration::from_secs(1)).await; + kio::clock::sleep(std::time::Duration::from_secs(1)).await; assert!( source_demand.wanted().is_some(), "the live path left its source mid-group" @@ -1689,7 +1689,7 @@ mod tests { while source_demand.wanted_changed().await?.is_some() {} moq_net::Result::Ok(()) }; - moq_clock::timeout(std::time::Duration::from_secs(10), unwanted) + kio::clock::timeout(std::time::Duration::from_secs(10), unwanted) .await .expect("the live path opened a group nobody asked for") .unwrap(); @@ -1795,7 +1795,7 @@ mod tests { // 160x120, but their decoder is rebuilt so none of them survives. source.describe(Some(bytes::Bytes::from_static(&[0x01, 0x42, 0x00, 0x1e]))); - let derived = moq_clock::timeout( + let derived = kio::clock::timeout( std::time::Duration::from_secs(5), await_catalog(&mut catalogs, |snapshot| { snapshot.video.renditions.contains_key("video/120p.2") @@ -1813,7 +1813,7 @@ mod tests { "the replacement should serve the same picture under a new name" ); - let ended = moq_clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) + let ended = kio::clock::timeout(std::time::Duration::from_secs(5), retired.recv_group()) .await .expect("the retired rung never ended its track"); assert!( @@ -1933,7 +1933,7 @@ mod tests { }; let output = moq_net::broadcast::Info::default().produce(); - let result = moq_clock::timeout( + let result = kio::clock::timeout( std::time::Duration::from_secs(5), run(broadcast.consume(), output, config), ) @@ -1984,7 +1984,7 @@ mod tests { // `run` should observe the end and return rather than block in the drain. drop(source); - let result = moq_clock::timeout(std::time::Duration::from_secs(5), transcoder).await; + let result = kio::clock::timeout(std::time::Duration::from_secs(5), transcoder).await; result.expect("run did not shut down within 5s").unwrap().unwrap(); } diff --git a/rs/moq-transcode/src/rung.rs b/rs/moq-transcode/src/rung.rs index 00de80bcaa5..ad5948fcee5 100644 --- a/rs/moq-transcode/src/rung.rs +++ b/rs/moq-transcode/src/rung.rs @@ -986,7 +986,7 @@ mod tests { let permit = Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap(); spawn_fill(&mut tasks, rung, fill, permit); let wait = std::time::Duration::from_secs(5); - let first = moq_clock::timeout(wait, source_fills.requested_fill()) + let first = kio::clock::timeout(wait, source_fills.requested_fill()) .await .expect("group 7 is fetched from the source") .unwrap(); @@ -994,7 +994,7 @@ mod tests { reader.update(ascending(8..)).unwrap(); assert!(reader.poll_recv_group(&waiter).is_pending()); - let next = moq_clock::timeout(wait, source_fills.requested_fill()) + let next = kio::clock::timeout(wait, source_fills.requested_fill()) .await .expect("the fill waited behind group 7, which nobody reads") .unwrap(); diff --git a/rs/moq-uring/Cargo.toml b/rs/moq-uring/Cargo.toml index 24eac2595de..5d500566e21 100644 --- a/rs/moq-uring/Cargo.toml +++ b/rs/moq-uring/Cargo.toml @@ -20,18 +20,17 @@ quic = ["dep:moq-congestion", "dep:moq-quic", "dep:rustls", "dep:rustls-platform # qlog crate and its serde_json encoder into moq-quic, which a production build has # no use for. qlog = ["moq-quic?/qlog"] -# Workers created inside a tokio runtime with a `moq_clock::Manual` clock installed +# Workers created inside a tokio runtime with a `kio::clock::Manual` clock installed # run on that clock, so a test decides when their time passes. For test builds. -_manual = ["moq-clock/manual"] +_manual = ["kio/manual"] [target.'cfg(target_os = "linux")'.dependencies] bytes = "1" http = "1" io-uring = { workspace = true } -kio = { workspace = true } +# The worker is a kio clock backend: its turn's instant is the ambient clock. +kio = { workspace = true, features = ["runtime"] } libc = { workspace = true } -# The worker is a moq-clock backend: its turn's instant is the ambient clock. -moq-clock = { workspace = true } moq-congestion = { workspace = true, optional = true } moq-net = { workspace = true } moq-quic = { workspace = true, features = ["rustls-aws-lc-rs"], optional = true } diff --git a/rs/moq-uring/MIGRATE.md b/rs/moq-uring/MIGRATE.md index 1b7f9489404..b889d2beff2 100644 --- a/rs/moq-uring/MIGRATE.md +++ b/rs/moq-uring/MIGRATE.md @@ -26,11 +26,11 @@ Pass a received `Packet::dst_ip()` as `src_ip` to answer from the address the pe moq-net dropped `connect_lite`, `accept_lite`, and `accept_request_lite`, and every session now needs a `Send` transport. Wrap the worker's session as `transport::Local::new(transport::Session::new(conn, address))` and call `connect`, `accept`, or `accept_request`. -### Timers run on moq-clock +### Timers run on `kio::clock` -The worker is a moq-clock backend, so its deadlines are `moq_clock::Instant`s instead of `std::time::Instant`s. -`Timer::set` takes an `Option`, and `quic::handshake::Info::deadline` is one. -Read the worker's time with `moq_clock::now()` inside it. +The worker is a `kio::clock` backend, so its deadlines are `kio::clock::Instant`s instead of `std::time::Instant`s. +`Timer::set` takes an `Option`, and `quic::handshake::Info::deadline` is one. +Read the worker's time with `kio::clock::now()` inside it. ### Datagrams take `SendOptions` (#5770, #5872) diff --git a/rs/moq-uring/README.md b/rs/moq-uring/README.md index c3491b6bd52..bd47fb53c30 100644 --- a/rs/moq-uring/README.md +++ b/rs/moq-uring/README.md @@ -2,7 +2,7 @@ Experimental Linux io\_uring support for the native MoQ stack: a thread-per-core `Worker` that owns a `SINGLE_ISSUER | DEFER_TASKRUN | -COOP_TASKRUN | TASKRUN_FLAG` ring, a userspace timer queue on moq-clock, a +COOP_TASKRUN | TASKRUN_FLAG` ring, a userspace timer queue on `kio::clock`, a local (`!Send`) task set, and the UDP sockets bound through it. - **Receive**: one persistent multishot `recvmsg` per socket, fed from a @@ -15,7 +15,7 @@ local (`!Send`) task set, and the UDP sockets bound through it. - **Send**: `sendmsg` with an explicit `UDP_SEGMENT` control message per call, staged in a fixed pool of buffers owned by id and released on completion (the shape a later `SENDMSG_ZC` needs). -- **Timers**: a `moq_clock::Deadlines` queue the worker advances once per +- **Timers**: a `kio::clock::Deadlines` queue the worker advances once per turn, from its one clock read; the earliest deadline rides `io_uring_enter` as an absolute timeout. Zero timeout SQEs. The queue is the worker's ambient clock, and `Handle::run` drives MoQ with it and a single timer. diff --git a/rs/moq-uring/benches/timers.rs b/rs/moq-uring/benches/timers.rs index a5132630377..5fbe5705cab 100644 --- a/rs/moq-uring/benches/timers.rs +++ b/rs/moq-uring/benches/timers.rs @@ -25,7 +25,7 @@ fn benchmark(c: &mut criterion::Criterion) { for armed in [1, 64, 1024, 16384] { // The rest of the table, spread across a minute so the re-armed timer // lands among them. - let now = moq_clock::now(); + let now = kio::clock::now(); let _others: Vec<_> = (0..armed) .map(|i| { let mut timer = handle.timer(); diff --git a/rs/moq-uring/src/clock.rs b/rs/moq-uring/src/clock.rs index 3712bfd7250..f4fc4b652b5 100644 --- a/rs/moq-uring/src/clock.rs +++ b/rs/moq-uring/src/clock.rs @@ -1,7 +1,7 @@ //! The worker's clock: the only module that reads the host clock. //! //! The worker samples it once per turn and hands that instant to its -//! [`moq_clock::Deadlines`] queue, which it enters as the thread's ambient clock, +//! [`kio::clock::Deadlines`] queue, which it enters as the thread's ambient clock, //! so everything it runs reads the sample instead of the host clock. The host //! clock is `CLOCK_MONOTONIC`, read directly so the park can hand the next //! deadline to the kernel as an absolute timeout without a second read. @@ -9,7 +9,7 @@ use std::task::Context; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; /// Where a worker's time comes from. #[derive(Clone)] @@ -21,7 +21,7 @@ pub(crate) enum Clock { /// The host clock alongside bounds teardown, which must end however long /// the test leaves its clock alone. #[cfg(feature = "_manual")] - Installed(moq_clock::Installed, Host), + Installed(kio::clock::Installed, Host), } /// How the worker waits for its next deadline while parked. @@ -42,7 +42,7 @@ impl Clock { /// The clock installed on the current tokio runtime, or else the host's. pub fn new() -> Self { #[cfg(feature = "_manual")] - if let Some(clock) = moq_clock::Installed::current() { + if let Some(clock) = kio::clock::Installed::current() { return Self::Installed(clock, Host::calibrate()); } Self::Host(Host::calibrate()) @@ -69,7 +69,7 @@ impl Clock { /// How to park for `deadline`. A manual clock keeps its alarm in `alarm`, so /// advancing it wakes the worker through `cx`. - pub fn wait(&self, deadline: Option, alarm: &mut Option, cx: &mut Context<'_>) -> Wait { + pub fn wait(&self, deadline: Option, alarm: &mut Option, cx: &mut Context<'_>) -> Wait { match self { Self::Host(host) => { let _ = (alarm, cx); @@ -96,23 +96,23 @@ impl Clock { } } -/// `CLOCK_MONOTONIC`, mapped onto moq-clock's instants at one calibration point. +/// `CLOCK_MONOTONIC`, mapped onto `kio::clock`'s instants at one calibration point. /// -/// moq-clock's host clock reads the same monotonic clock from an origin it keeps +/// `kio::clock`'s host clock reads the same monotonic clock from an origin it keeps /// to itself, so the two differ by a constant that one reading of each pins down /// to within the gap between them. #[derive(Clone, Copy)] pub(crate) struct Host { /// A monotonic reading. monotonic: Duration, - /// moq-clock's instant at that reading. + /// `kio::clock`'s instant at that reading. instant: Instant, } impl Host { fn calibrate() -> Self { let before = monotonic(); - let instant = moq_clock::now(); + let instant = kio::clock::now(); let after = monotonic(); Self { monotonic: before + (after - before) / 2, @@ -142,18 +142,18 @@ fn monotonic() -> Duration { mod tests { use super::*; - /// The calibrated clock agrees with moq-clock's host clock, which reads the same + /// The calibrated clock agrees with `kio::clock`'s host clock, which reads the same /// monotonic clock from another origin. #[test] - fn host_tracks_moq_clock() { + fn host_tracks_kio_clock() { // Off by at most the gap between the two calibration reads, which a // preemption can stretch, so measure it rather than assume one. let start = monotonic(); let host = Host::calibrate(); let slack = monotonic() - start; - let before = moq_clock::now(); + let before = kio::clock::now(); let now = host.now(); - let after = moq_clock::now(); + let after = kio::clock::now(); assert!( before <= now + slack && now <= after + slack, "{before:?} <= {now:?} <= {after:?}" @@ -166,7 +166,7 @@ mod tests { #[test] fn host_time_passes_on_a_standing_manual_clock() { let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); - let manual = moq_clock::Manual::new().install(runtime.handle()); + let manual = kio::clock::Manual::new().install(runtime.handle()); let _entered = runtime.enter(); let clock = Clock::new(); let start = clock.host_now(); diff --git a/rs/moq-uring/src/quic/driver/connection.rs b/rs/moq-uring/src/quic/driver/connection.rs index 0ac224dcdbd..1797482ff6d 100644 --- a/rs/moq-uring/src/quic/driver/connection.rs +++ b/rs/moq-uring/src/quic/driver/connection.rs @@ -1,6 +1,6 @@ //! The connection: shared state, the driver task, and the session handle. -use moq_clock::Instant; +use kio::clock::Instant; use std::cell::RefCell; use std::net::SocketAddr; use std::rc::{Rc, Weak}; diff --git a/rs/moq-uring/src/quic/handshake.rs b/rs/moq-uring/src/quic/handshake.rs index 0ad01d9bdf4..28cdf598968 100644 --- a/rs/moq-uring/src/quic/handshake.rs +++ b/rs/moq-uring/src/quic/handshake.rs @@ -7,7 +7,7 @@ use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; /// How an endpoint bounds the handshakes it accepts. #[derive(Clone, Debug, Default)] diff --git a/rs/moq-uring/src/quic/qlog.rs b/rs/moq-uring/src/quic/qlog.rs index f835a3c3bdd..f9c86c39976 100644 --- a/rs/moq-uring/src/quic/qlog.rs +++ b/rs/moq-uring/src/quic/qlog.rs @@ -80,8 +80,8 @@ impl Sink { let dir = dir.into(); let process = std::process::id(); let sink = NEXT_SINK.fetch_add(1, Ordering::Relaxed); - let started = moq_clock::wall() - .saturating_duration_since(moq_clock::Wall::UNIX_EPOCH) + let started = kio::clock::wall() + .saturating_duration_since(kio::clock::Wall::UNIX_EPOCH) .as_millis(); // A read-only or missing directory is reported here, where the diff --git a/rs/moq-uring/src/shared.rs b/rs/moq-uring/src/shared.rs index 65d16938dc3..5c7f9a19209 100644 --- a/rs/moq-uring/src/shared.rs +++ b/rs/moq-uring/src/shared.rs @@ -5,7 +5,7 @@ //! ring (submitting inline when the queue is full), while completions are only //! reaped by the worker loop. -use moq_clock::Instant; +use kio::clock::Instant; use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::io; @@ -58,7 +58,7 @@ pub(crate) struct Shared { pub clock: Clock, /// The worker's timers, at the instant of its current turn. Entered as the /// ambient clock while the worker polls. - pub deadlines: moq_clock::Deadlines, + pub deadlines: kio::clock::Deadlines, /// Whether a turn is running, so `deadlines` already holds its instant. pub turning: Cell, /// Tasks handed to [`crate::Handle::spawn`], drained by the worker loop. diff --git a/rs/moq-uring/src/timer.rs b/rs/moq-uring/src/timer.rs index eeed61508fc..bd23cde6e55 100644 --- a/rs/moq-uring/src/timer.rs +++ b/rs/moq-uring/src/timer.rs @@ -1,6 +1,6 @@ //! Userspace timers on the worker's deadline queue, never a timeout SQE. //! -//! Every armed deadline lives in the worker's [`moq_clock::Deadlines`]. The +//! Every armed deadline lives in the worker's [`kio::clock::Deadlines`]. The //! worker advances it to each turn's instant, firing the due prefix, and parks //! with the earliest remaining deadline as the absolute `io_uring_enter` //! timeout, so timers cost zero submissions and re-arming is a pure memory @@ -9,7 +9,7 @@ use std::sync::Arc; use std::task::Poll; -use moq_clock::{Deadline, Deadlines, Instant}; +use kio::clock::{Deadline, Deadlines, Instant}; use crate::metrics::Counters; diff --git a/rs/moq-uring/src/udp.rs b/rs/moq-uring/src/udp.rs index dfd2d45c693..6192c0b565e 100644 --- a/rs/moq-uring/src/udp.rs +++ b/rs/moq-uring/src/udp.rs @@ -464,7 +464,7 @@ pub(crate) struct SockShared { /// datagrams go out alone: the route or driver cannot segment. gso: Cell, /// When a lost send was last logged, so a flood of them logs once per interval. - lost_logged: Cell>, + lost_logged: Cell>, closed: Cell, rx: RefCell, tx: RefCell, @@ -555,7 +555,7 @@ impl SockShared { tracing::debug!(%err, to = %op.to, "send lost"); return; } - let now = moq_clock::now(); + let now = kio::clock::now(); if self .lost_logged .get() diff --git a/rs/moq-uring/src/worker.rs b/rs/moq-uring/src/worker.rs index 4713c578497..e200000c8c6 100644 --- a/rs/moq-uring/src/worker.rs +++ b/rs/moq-uring/src/worker.rs @@ -7,7 +7,7 @@ use std::task::{Context, Poll}; use std::time::Duration; use io_uring::{EnterFlags, IoUring, opcode, types}; -use moq_clock::Instant; +use kio::clock::Instant; use crate::clock::{Clock, Wait}; use crate::metrics::Metrics; @@ -110,7 +110,7 @@ pub struct Worker { /// parked wakes the worker to re-park for it. owner: kio::Waiter, /// A manual clock's wake for the next deadline; the host clock needs none. - alarm: Option, + alarm: Option, } impl Worker { @@ -153,7 +153,7 @@ impl Worker { } let clock = Clock::new(); - let deadlines = moq_clock::Deadlines::new(clock.now()); + let deadlines = kio::clock::Deadlines::new(clock.now()); let unpark = Unpark::new(metrics.clone()); // A wake CQE can join a larger batch after warmup. Reserve the kernel's // actual queue size so copying those completions does not allocate. @@ -198,8 +198,8 @@ impl Worker { /// is fatal to the worker. /// /// While it runs, the worker's clock is the thread's ambient - /// [`moq_clock`] clock: [`moq_clock::now`] reads the instant the current - /// turn sampled, and [`moq_clock::sleep`] arms this worker's timers. + /// [`kio::clock`] clock: [`kio::clock::now`] reads the instant the current + /// turn sampled, and [`kio::clock::sleep`] arms this worker's timers. pub fn block_on(&mut self, future: F) -> Result { let mut future = std::pin::pin!(future); let waker = self.shared.unpark.waker(); @@ -530,7 +530,7 @@ impl Worker { /// current instant until this drops. struct Turn { shared: Rc, - _ambient: moq_clock::Entered, + _ambient: kio::clock::Entered, } impl Turn { @@ -665,7 +665,7 @@ pub(crate) struct Owner { /// the driver that owns it is torn down by the same drop that would need /// it. #[cfg_attr(not(feature = "quic"), allow(dead_code, reason = "only the `quic` feature uses it"))] - deadlines: moq_clock::Deadlines, + deadlines: kio::clock::Deadlines, #[cfg_attr(not(feature = "quic"), allow(dead_code, reason = "only the `quic` feature uses it"))] metrics: std::sync::Arc, } @@ -797,9 +797,9 @@ mod tests { } /// A worker on a manual clock, which only `advance` moves. - fn manual() -> Option<(Worker, moq_clock::Installed)> { + fn manual() -> Option<(Worker, kio::clock::Installed)> { let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); - let clock = moq_clock::Manual::new().install(runtime.handle()); + let clock = kio::clock::Manual::new().install(runtime.handle()); let _entered = runtime.enter(); Some((worker()?, clock)) } @@ -1022,11 +1022,11 @@ mod tests { let handle = worker.handle(); let at = worker .block_on(async move { - let at = moq_clock::now() + Duration::from_millis(50); + let at = kio::clock::now() + Duration::from_millis(50); let mut timer = handle.timer(); timer.set(Some(at)); timer.wait().await; - assert!(moq_clock::now() >= at, "fired before the turn reached it"); + assert!(kio::clock::now() >= at, "fired before the turn reached it"); at }) .unwrap(); @@ -1053,8 +1053,8 @@ mod tests { }); let woke = worker .block_on(async move { - moq_clock::sleep(Duration::from_secs(5)).await; - moq_clock::now() + kio::clock::sleep(Duration::from_secs(5)).await; + kio::clock::now() }) .unwrap(); advancer.join().unwrap(); @@ -1069,14 +1069,14 @@ mod tests { let handle = worker.handle(); let (now, timed_out) = worker .block_on(async move { - let now = moq_clock::now(); + let now = kio::clock::now(); // Due at once, so this needs no advance. - let timed_out = moq_clock::timeout(Duration::ZERO, std::future::pending::<()>()).await; + let timed_out = kio::clock::timeout(Duration::ZERO, std::future::pending::<()>()).await; assert_eq!(handle.now(), now); (now, timed_out.is_err()) }) .unwrap(); - assert_eq!(now, moq_clock::Instant::ZERO + Duration::from_secs(1)); + assert_eq!(now, kio::clock::Instant::ZERO + Duration::from_secs(1)); assert!(timed_out); } @@ -1087,7 +1087,7 @@ mod tests { let Some((mut worker, clock)) = manual() else { return }; clock.advance(Duration::from_secs(5)); let (wall, origin) = worker - .block_on(async { (moq_clock::wall(), moq_clock::origin()) }) + .block_on(async { (kio::clock::wall(), kio::clock::origin()) }) .unwrap(); assert_eq!(wall, clock.wall(), "the worker read the host's wall time"); assert_eq!(origin.0, clock.now()); @@ -1187,7 +1187,7 @@ mod tests { result: 0, flags: 0, }; - let before = moq_clock::Instant::ZERO; + let before = kio::clock::Instant::ZERO; let deadline = before + Duration::from_millis(1); let mut now = [before, deadline].into_iter(); @@ -1774,7 +1774,7 @@ mod tests { fn metrics_count_an_unpolled_expiry_as_fired() { let metrics = Metrics::default(); let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); - let clock = moq_clock::Manual::new().install(runtime.handle()); + let clock = kio::clock::Manual::new().install(runtime.handle()); let _entered = runtime.enter(); let Some(mut worker) = worker_with(Config { metrics: metrics.clone(), diff --git a/rs/moq-uring/tests/integration/endpoint.rs b/rs/moq-uring/tests/integration/endpoint.rs index 3c9f1a5833f..e4e9b864e9f 100644 --- a/rs/moq-uring/tests/integration/endpoint.rs +++ b/rs/moq-uring/tests/integration/endpoint.rs @@ -682,9 +682,9 @@ fn connections_share_one_tx_buffer_fairly() { .expect("second client socket"); let mut second_config = dial_config(); second_config.transport.idle_timeout = Duration::from_millis(500); - let started = moq_clock::now(); + let started = kio::clock::now(); let second = quic::client::connect(second_sock, &second_config, server, "localhost").await; - let elapsed = moq_clock::now() - started; + let elapsed = kio::clock::now() - started; running.set(false); let second = second.expect("the second connection must not starve"); assert!( diff --git a/rs/moq-uring/tests/integration/local_addr.rs b/rs/moq-uring/tests/integration/local_addr.rs index 116c04eb887..e2665c93f50 100644 --- a/rs/moq-uring/tests/integration/local_addr.rs +++ b/rs/moq-uring/tests/integration/local_addr.rs @@ -180,7 +180,7 @@ fn a_wildcard_endpoint_handshakes_on_a_secondary_address() { let request = moq_tokio::quic::web::proto::ConnectRequest::new( url::Url::parse(&format!("https://{addr}/")).expect("url"), ); - moq_clock::timeout(TIMEOUT, crate::support::web_connect(request, Default::default())) + kio::clock::timeout(TIMEOUT, crate::support::web_connect(request, Default::default())) .await .expect("handshake stalled") .expect("connect"); diff --git a/rs/moq-uring/tests/integration/web.rs b/rs/moq-uring/tests/integration/web.rs index 9c7b7b0dd24..000c249bcc8 100644 --- a/rs/moq-uring/tests/integration/web.rs +++ b/rs/moq-uring/tests/integration/web.rs @@ -436,7 +436,7 @@ fn tokio_client_err(url: String) -> std::thread::JoinHandle) -> Result frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { @@ -179,7 +179,7 @@ async fn ensure_camera_access(media: &AVMediaType) -> Result<(), Error> { }); unsafe { AVCaptureDevice::requestAccessForMediaType_completionHandler(media, &handler) }; - return match moq_clock::timeout(ACCESS_TIMEOUT, rx).await { + return match kio::clock::timeout(ACCESS_TIMEOUT, rx).await { Ok(Ok(true)) => Ok(()), Ok(Ok(false)) => Err(Error::PermissionDenied( "camera access; enable it in System Settings > Privacy & Security > Camera".to_string(), diff --git a/rs/moq-video/src/capture/channel.rs b/rs/moq-video/src/capture/channel.rs index c0463b423ae..707bd080932 100644 --- a/rs/moq-video/src/capture/channel.rs +++ b/rs/moq-video/src/capture/channel.rs @@ -8,7 +8,7 @@ //! the [`Stream`](super::Stream) drops, the device is released, and no //! blocking thread is left pinned. -use moq_clock::Instant; +use kio::clock::Instant; use std::sync::{Arc, Mutex}; use tokio::sync::Notify; diff --git a/rs/moq-video/src/capture/mod.rs b/rs/moq-video/src/capture/mod.rs index 23b1cb229fc..4ce7ce838fe 100644 --- a/rs/moq-video/src/capture/mod.rs +++ b/rs/moq-video/src/capture/mod.rs @@ -413,7 +413,7 @@ impl Synthetic { } /// Deliver a frame acquired at `captured`. - pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: moq_clock::Instant) { + pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: kio::clock::Instant) { self.chan.push_at(surface, captured); } diff --git a/rs/moq-video/src/capture/pipewire.rs b/rs/moq-video/src/capture/pipewire.rs index f7899415779..d7313c7bab6 100644 --- a/rs/moq-video/src/capture/pipewire.rs +++ b/rs/moq-video/src/capture/pipewire.rs @@ -175,7 +175,7 @@ async fn start(config: &Config, capture: Capture, session: Option) _session: session, }; - let geo = match moq_clock::timeout(FORMAT_TIMEOUT, geo_rx).await { + let geo = match kio::clock::timeout(FORMAT_TIMEOUT, geo_rx).await { Ok(Ok(result)) => result?, Ok(Err(_)) => { return Err(Error::Codec(anyhow::anyhow!( @@ -190,7 +190,7 @@ async fn start(config: &Config, capture: Capture, session: Option) } }; - let first = match moq_clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { + let first = match kio::clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { Ok(Ok(Some(frame))) => frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { diff --git a/rs/moq-video/src/capture/screencapture.rs b/rs/moq-video/src/capture/screencapture.rs index 675a00b72c9..17c75cccf4b 100644 --- a/rs/moq-video/src/capture/screencapture.rs +++ b/rs/moq-video/src/capture/screencapture.rs @@ -191,7 +191,7 @@ async fn open(config: &Config, filter: &SCContentFilter, size: (u32, u32)) -> Re }; let label = config.source.label(); - let first = match moq_clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { + let first = match kio::clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { Ok(Ok(Some(frame))) => frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { @@ -376,7 +376,7 @@ async fn shareable_content() -> Result, Error> { }); unsafe { SCShareableContent::getShareableContentWithCompletionHandler(&handler) }; - match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { + match kio::clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(Ok(content))) => Ok(content.0), Ok(Ok(Err(msg))) => Err(Error::Codec(anyhow::anyhow!("shareable content: {msg}"))), Ok(Err(_)) => Err(Error::Codec(anyhow::anyhow!("shareable content handler dropped"))), @@ -398,7 +398,7 @@ async fn start_capture(stream: &SCStream) -> Result<(), Error> { }); unsafe { stream.startCaptureWithCompletionHandler(Some(&handler)) }; - match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { + match kio::clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(None)) => Ok(()), Ok(Ok(Some(msg))) => Err(Error::Codec(anyhow::anyhow!("start capture: {msg}"))), Ok(Err(_)) => Err(Error::Codec(anyhow::anyhow!("start-capture handler dropped"))), diff --git a/rs/moq-video/src/capture/settle.rs b/rs/moq-video/src/capture/settle.rs index 8336fc40de6..9a526bb999f 100644 --- a/rs/moq-video/src/capture/settle.rs +++ b/rs/moq-video/src/capture/settle.rs @@ -8,7 +8,7 @@ //! again. So hold instead: once the geometry moves, stop capturing but keep //! polling, and only end once it has stayed put. -use moq_clock::Instant; +use kio::clock::Instant; use std::time::Duration; /// How long a new geometry has to hold still before the stream ends. diff --git a/rs/moq-video/src/capture/wgc.rs b/rs/moq-video/src/capture/wgc.rs index 5064aa9d1cf..84ab832cfef 100644 --- a/rs/moq-video/src/capture/wgc.rs +++ b/rs/moq-video/src/capture/wgc.rs @@ -4,7 +4,7 @@ use std::sync::{Condvar, Mutex}; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::Timestamp; diff --git a/rs/moq-video/src/capture/wgc/native.rs b/rs/moq-video/src/capture/wgc/native.rs index 452a5083bca..cbd25a4158e 100644 --- a/rs/moq-video/src/capture/wgc/native.rs +++ b/rs/moq-video/src/capture/wgc/native.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use windows::Foundation::{Metadata::ApiInformation, TypedEventHandler}; use windows::Graphics::Capture::{ diff --git a/rs/moq-video/src/capture/x11.rs b/rs/moq-video/src/capture/x11.rs index 1c296c63405..52ca675934b 100644 --- a/rs/moq-video/src/capture/x11.rs +++ b/rs/moq-video/src/capture/x11.rs @@ -7,7 +7,7 @@ //! memory. It is the only Linux backend for `Source::Display`, so a display //! that X11 cannot reach is refused rather than handed to the portal. -use moq_clock::Instant; +use kio::clock::Instant; use std::os::fd::AsRawFd; use std::ptr::NonNull; use std::sync::Arc; diff --git a/rs/moq-video/src/decode/backend/v4l2.rs b/rs/moq-video/src/decode/backend/v4l2.rs index 38e2379dc68..2f68e9043c1 100644 --- a/rs/moq-video/src/decode/backend/v4l2.rs +++ b/rs/moq-video/src/decode/backend/v4l2.rs @@ -32,7 +32,7 @@ //! sequence follows the kernel's stateful decoder documentation and an //! implementation that also ran on a Pi Zero 2 W and a Pi 3. -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::VecDeque; use std::time::Duration; diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index cc85bc7369e..b3b2ff6fddd 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -5,7 +5,7 @@ use std::pin::Pin; use std::task::{Context, Poll, ready}; use hang::catalog::VideoConfig; -use moq_clock::Instant; +use kio::clock::Instant; use moq_mux::container::Read as Encoded; use super::decoder::Config; @@ -218,7 +218,7 @@ impl Consumer { fn poll_read( &mut self, cx: &mut Context<'_>, - sleep: &mut Option>>, + sleep: &mut Option>>, ) -> Poll, Error>> { loop { let deadline = match self.selector.next(Instant::now()) { @@ -265,7 +265,7 @@ impl Consumer { let Some(deadline) = deadline else { return Poll::Pending; }; - let sleep = sleep.get_or_insert_with(|| Box::pin(moq_clock::sleep_until(deadline))); + let sleep = sleep.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(deadline))); sleep.as_mut().reset(deadline); ready!(sleep.as_mut().poll(cx)); } @@ -988,15 +988,15 @@ mod tests { .unwrap(); let mut read = Box::pin(consumer.next_frame()); - let deadline = moq_clock::Instant::now() + std::time::Duration::from_secs(1); + let deadline = kio::clock::Instant::now() + std::time::Duration::from_secs(1); loop { tokio::select! { _result = &mut read => panic!("flush returned before cancellation"), - _ = moq_clock::sleep(std::time::Duration::from_millis(1)) => { + _ = kio::clock::sleep(std::time::Duration::from_millis(1)) => { if probe::flush_entered() { break; } - if moq_clock::Instant::now() >= deadline { + if kio::clock::Instant::now() >= deadline { probe::release_flush(); panic!("flush never reached the codec thread"); } @@ -1152,7 +1152,7 @@ mod tests { /// Read one frame, as (seconds, the lane it was shown from). async fn read(consumer: &mut Consumer) -> (u64, Lane) { - let frame = moq_clock::timeout(std::time::Duration::from_secs(10), consumer.next_frame()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(10), consumer.next_frame()) .await .expect("a frame within ten seconds") .unwrap() @@ -1164,13 +1164,13 @@ mod tests { /// Let the decoders run with nothing new to show until the max-delay one /// has caught up, or fail after ten seconds of trying. async fn catch_up(consumer: &mut Consumer) { - let deadline = moq_clock::Instant::now() + std::time::Duration::from_secs(10); + let deadline = kio::clock::Instant::now() + std::time::Duration::from_secs(10); while consumer.selector.source() != Lane::Max { assert!( - moq_clock::Instant::now() < deadline, + kio::clock::Instant::now() < deadline, "the max-delay decoder never caught up" ); - if let Ok(frame) = moq_clock::timeout(std::time::Duration::from_millis(20), consumer.next_frame()).await { + if let Ok(frame) = kio::clock::timeout(std::time::Duration::from_millis(20), consumer.next_frame()).await { panic!( "nothing new was published, yet read returned {:?}", frame.map(|f| f.map(|f| f.timestamp)) @@ -1244,7 +1244,7 @@ mod tests { let mut live = group(&mut track, 2, &[8]); shown.push(read(&mut consumer).await); assert!( - moq_clock::timeout(std::time::Duration::from_millis(100), consumer.next_frame()) + kio::clock::timeout(std::time::Duration::from_millis(100), consumer.next_frame()) .await .is_err() ); @@ -1413,7 +1413,7 @@ mod tests { ) .await; for _ in 0..3 { - match moq_clock::timeout(std::time::Duration::from_secs(10), consumer.next_frame()).await { + match kio::clock::timeout(std::time::Duration::from_secs(10), consumer.next_frame()).await { Ok(Ok(Some(_))) => continue, Ok(Err(err)) => { assert!(err.to_string().contains("corrupt"), "unexpected error: {err}"); diff --git a/rs/moq-video/src/decode/select.rs b/rs/moq-video/src/decode/select.rs index 10391deb12f..b8767605544 100644 --- a/rs/moq-video/src/decode/select.rs +++ b/rs/moq-video/src/decode/select.rs @@ -20,7 +20,7 @@ use std::collections::VecDeque; use std::time::Duration; -use moq_clock::Instant; +use kio::clock::Instant; use super::Read; diff --git a/rs/moq-video/src/encode/backend/v4l2.rs b/rs/moq-video/src/encode/backend/v4l2.rs index 4f82dbf5500..4efa14a4e43 100644 --- a/rs/moq-video/src/encode/backend/v4l2.rs +++ b/rs/moq-video/src/encode/backend/v4l2.rs @@ -34,7 +34,7 @@ //! from an implementation that also ran on a Pi Zero 2 W and a Pi 3; those two //! have not been re-run with this port. -use moq_clock::Instant; +use kio::clock::Instant; use std::collections::VecDeque; use std::time::Duration; diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index 450915bc807..491afa628ac 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -1227,10 +1227,10 @@ mod tests { /// published timestamp may land up to `SAMPLING` early, never late. #[cfg(all(feature = "capture", feature = "openh264"))] mod clock { - use moq_clock::Wall; + use kio::clock::Wall; use std::time::Duration; - use moq_clock::Instant; + use kio::clock::Instant; use super::*; use crate::capture::Synthetic; @@ -1268,7 +1268,7 @@ mod tests { impl Fixture { /// Start the capture loop on a broadcast whose clock began `behind` ago, at `wall`. async fn start(behind: Duration, wall: Wall) -> Self { - let epoch = moq_clock::now() + let epoch = kio::clock::now() .checked_sub(behind) .expect("a monotonic clock that far back"); let clock = moq_mux::Clock::at(epoch, wall).unwrap(); @@ -1429,13 +1429,13 @@ mod tests { async fn a_late_first_frame_publishes_its_acquisition() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall()).await; + let fixture = Fixture::start(Duration::from_secs(5), kio::clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); let captured = Instant::now(); // Delivered well after acquisition: dequeue time must not leak into the timestamp. - moq_clock::sleep(Duration::from_millis(50)).await; + kio::clock::sleep(Duration::from_millis(50)).await; camera.push_at(surface(), captured); let published = read(&mut track).await; @@ -1452,14 +1452,14 @@ mod tests { async fn a_device_clock_restart_continues_forward() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; + let fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); // The device numbers from zero, and real time keeps pace with it. camera.push_native(surface(), us(0)); let first = read(&mut track).await; - moq_clock::sleep(Duration::from_millis(40)).await; + kio::clock::sleep(Duration::from_millis(40)).await; camera.push_native(surface(), us(40_000)); let second = read(&mut track).await; assert_eq!(second - first, 40_000, "the device's spacing survives"); @@ -1468,7 +1468,7 @@ mod tests { camera.push_native(surface(), us(0)); let restarted = read(&mut track).await; assert!(restarted >= second, "{restarted}us rewound behind {second}us"); - moq_clock::sleep(Duration::from_millis(40)).await; + kio::clock::sleep(Duration::from_millis(40)).await; camera.push_native(surface(), us(40_000)); let resumed = read(&mut track).await; assert_eq!(resumed - restarted, 40_000, "the device's spacing resumes"); @@ -1495,7 +1495,7 @@ mod tests { tokio::task::LocalSet::new() .run_until(async { let idle = Duration::from_millis(300); - let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; + let fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); @@ -1506,7 +1506,7 @@ mod tests { drop(track); drop(camera); - moq_clock::sleep(idle).await; + kio::clock::sleep(idle).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); @@ -1531,7 +1531,7 @@ mod tests { async fn a_reopen_onto_a_new_level_follows_the_new_track() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; + let fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall()).await; let probed = fixture .catalog .snapshot() @@ -1586,7 +1586,7 @@ mod tests { tokio::task::LocalSet::new() .run_until(async { // Whole seconds, so the advertised mapping holds it exactly. - let now = moq_clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); + let now = kio::clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); let wall = Wall::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); let fixture = Fixture::start(Duration::from_secs(1), wall).await; let advertised = fixture.catalog.snapshot().clock; @@ -1614,7 +1614,7 @@ mod tests { async fn hls_records_keep_the_live_timestamps() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; + let fixture = Fixture::start(Duration::from_secs(1), kio::clock::wall()).await; // The encoder's GOP hint declares the duration up front. let hls = fixture.catalog.snapshot().video.renditions["video"] .hls @@ -1632,7 +1632,7 @@ mod tests { live.push(published); drop(track); // Idle past the minimum segment, so each run is listed as its own segment. - moq_clock::sleep(moq_mux::hls::DEFAULT_DURATION + Duration::from_millis(100)).await; + kio::clock::sleep(moq_mux::hls::DEFAULT_DURATION + Duration::from_millis(100)).await; } let (mut catalog, consumer) = fixture.finish().await; @@ -1746,7 +1746,7 @@ mod tests { async fn capture_groups(steps: Vec) -> (moq_net::track::Info, Vec>) { use moq_mux::container::Container as _; - let started = moq_clock::Instant::now(); + let started = kio::clock::Instant::now(); let result = local(async { let mut broadcast = moq_net::broadcast::Info::new().produce(); let consumer = broadcast.consume(); @@ -2085,7 +2085,7 @@ mod tests { estimate.set(Some(Rate::from_kbps(500))).unwrap(); tokio::select! { res = &mut run => panic!("the capture ended: {res:?}"), - () = moq_clock::sleep(Duration::from_secs(60)) => {} + () = kio::clock::sleep(Duration::from_secs(60)) => {} } assert_eq!(probe::bitrates(), Vec::::new()); @@ -2158,7 +2158,7 @@ mod tests { // Nothing has refused a cut: the probe never finished, or its backend can force one. control.cut().unwrap(); drop(control); - moq_clock::timeout(Duration::from_secs(1), run) + kio::clock::timeout(Duration::from_secs(1), run) .await .expect("dropping the controls ends the driver") .unwrap(); @@ -2314,7 +2314,7 @@ mod tests { probe::refuse_once(ceiling.as_bps()); // A minute without a wake is far past anything the ramp still needs. - while let Ok(next) = moq_clock::timeout(Duration::from_secs(60), next_target(&mut rate)).await { + while let Ok(next) = kio::clock::timeout(Duration::from_secs(60), next_target(&mut rate)).await { apply_target(&mut sink, &mut rate, next).await; } let bitrates = probe::bitrates(); diff --git a/rs/moq-video/src/frame.rs b/rs/moq-video/src/frame.rs index a0bc69eb9bd..08f8eadd838 100644 --- a/rs/moq-video/src/frame.rs +++ b/rs/moq-video/src/frame.rs @@ -180,11 +180,11 @@ pub(crate) fn wait_dma_buf_readable(fd: BorrowedFd<'_>) -> std::io::Result<()> { events: libc::POLLIN, revents: 0, }; - let deadline = moq_clock::now() + DMA_BUF_FENCE_TIMEOUT; + let deadline = kio::clock::now() + DMA_BUF_FENCE_TIMEOUT; loop { // A signal restarts the wait against the same deadline rather than // granting a fresh budget, so the total stall stays bounded. - let remaining = deadline.saturating_duration_since(moq_clock::now()); + let remaining = deadline.saturating_duration_since(kio::clock::now()); if remaining.is_zero() { return Err(std::io::Error::from(std::io::ErrorKind::TimedOut)); } diff --git a/rs/moq-video/src/frame/cuda_test.rs b/rs/moq-video/src/frame/cuda_test.rs index 66d5760b6b8..2983a84fef5 100644 --- a/rs/moq-video/src/frame/cuda_test.rs +++ b/rs/moq-video/src/frame/cuda_test.rs @@ -314,7 +314,7 @@ struct Stage { impl Stage { fn measure(&mut self, f: impl FnOnce() -> T) -> T { - let (wall, cpu) = (moq_clock::now(), cpu_now()); + let (wall, cpu) = (kio::clock::now(), cpu_now()); let out = f(); self.wall.push(wall.elapsed()); self.cpu.push(cpu_now() - cpu); @@ -384,7 +384,7 @@ async fn vulkan_cuda_three_view_workload() { let (mut encode_hd, mut encode_sd, mut complete) = (Stage::default(), Stage::default(), Stage::default()); let mut bytes = (0usize, 0usize); let mut late = 0u64; - let mut started = moq_clock::now(); + let mut started = kio::clock::now(); for tick_index in 0..WARMUP + TICKS { // Discard the warmup: the first ticks pay for PTX JIT, NVENC's lazy @@ -399,9 +399,9 @@ async fn vulkan_cuda_three_view_workload() { complete = Stage::default(); bytes = (0, 0); late = 0; - started = moq_clock::now(); + started = kio::clock::now(); } - let deadline = moq_clock::now() + tick; + let deadline = kio::clock::now() + tick; let timestamp = moq_net::Timestamp::from_micros(tick_index * 33_333).unwrap(); for (producer, slot, hd, small, signal) in &mut views { @@ -430,7 +430,7 @@ async fn vulkan_cuda_three_view_workload() { .expect("encode SD"); bytes.1 += packets.iter().map(|p| p.payload.len()).sum::(); - let (wall, cpu) = (moq_clock::now(), cpu_now()); + let (wall, cpu) = (kio::clock::now(), cpu_now()); let returned = completion.wait().await.expect("completion worker stopped"); complete.wall.push(wall.elapsed()); complete.cpu.push(cpu_now() - cpu); @@ -443,8 +443,8 @@ async fn vulkan_cuda_three_view_workload() { *slot = Some(returned); } - match deadline.checked_duration_since(moq_clock::now()) { - Some(idle) => moq_clock::sleep(idle).await, + match deadline.checked_duration_since(kio::clock::now()) { + Some(idle) => kio::clock::sleep(idle).await, None => late += 1, } } diff --git a/rs/moq-video/src/render/renderer.rs b/rs/moq-video/src/render/renderer.rs index 0f1be1d8096..e16ff470831 100644 --- a/rs/moq-video/src/render/renderer.rs +++ b/rs/moq-video/src/render/renderer.rs @@ -570,7 +570,7 @@ mod tests { let mut stream = crate::capture::open(&capture).await.expect("portal screen capture"); for index in 0..16 { - let frame = moq_clock::timeout(std::time::Duration::from_secs(5), stream.read()) + let frame = kio::clock::timeout(std::time::Duration::from_secs(5), stream.read()) .await .unwrap_or_else(|_| panic!("timed out waiting for frame {index}")) .unwrap_or_else(|error| panic!("capture failed before frame {index}: {error}")) diff --git a/rs/qmux/Cargo.toml b/rs/qmux/Cargo.toml index 9a016188d3e..2ae6ef4927b 100644 --- a/rs/qmux/Cargo.toml +++ b/rs/qmux/Cargo.toml @@ -23,8 +23,7 @@ wss = ["ws", "dep:rustls", "tokio-tungstenite/rustls-tls-native-roots"] [dependencies] bytes = { workspace = true } futures = { workspace = true, optional = true } -kio = { workspace = true } -moq-clock = { workspace = true } +kio = { workspace = true, features = ["runtime"] } moq-net = { workspace = true } # The stream state machine, shared with QUIC. `mux` drives it over a reliable transport. moq-quic = { workspace = true, features = ["mux"] } diff --git a/rs/qmux/examples/bench.rs b/rs/qmux/examples/bench.rs index 2b26e3ed6c9..8d47db24607 100644 --- a/rs/qmux/examples/bench.rs +++ b/rs/qmux/examples/bench.rs @@ -258,9 +258,9 @@ async fn measure( } // Let every stream open and the allocator settle before the window starts. - moq_clock::sleep(duration / 4).await; - let (start, cpu, count) = (moq_clock::now(), process_cpu()?, done.load(Ordering::Relaxed)); - moq_clock::sleep(duration).await; + kio::clock::sleep(duration / 4).await; + let (start, cpu, count) = (kio::clock::now(), process_cpu()?, done.load(Ordering::Relaxed)); + kio::clock::sleep(duration).await; let sample = Sample { round_trips: done.load(Ordering::Relaxed) - count, cpu: process_cpu()? - cpu, diff --git a/rs/qmux/examples/common/mod.rs b/rs/qmux/examples/common/mod.rs index f667d7a51af..6570c741768 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); - moq_clock::timeout(TIMEOUT, async { + kio::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(); - moq_clock::timeout(TIMEOUT, async { + kio::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 16f18ebf3aa..2409214b21f 100644 --- a/rs/qmux/examples/interop-client.rs +++ b/rs/qmux/examples/interop-client.rs @@ -19,7 +19,7 @@ async fn run(session: Session, version: Version) -> anyhow::Result<()> { } // Rust -> TypeScript. - let mut send = moq_clock::timeout(TIMEOUT, session.open_uni(SendOptions::default())) + let mut send = kio::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(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 = moq_clock::timeout(TIMEOUT, session.accept_uni()) + let mut recv = kio::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(session: Session, version: Version) -> anyhow::Result<()> { } // Exercise both halves of one bidirectional stream and FIN propagation. - let (mut send, mut recv) = moq_clock::timeout(TIMEOUT, session.open_bi(SendOptions::default())) + let (mut send, mut recv) = kio::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(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 = moq_clock::timeout(TIMEOUT, session.recv_datagram()) + let datagram = kio::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(session: Session, version: Version) -> anyhow::Result<()> { bail!("QMux00 unexpectedly negotiated datagram support"); } - let closed = moq_clock::timeout(TIMEOUT, session.closed()) + let closed = kio::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 b5f5aa56a96..218d6e6aa9a 100644 --- a/rs/qmux/examples/interop-server.rs +++ b/rs/qmux/examples/interop-server.rs @@ -22,7 +22,7 @@ async fn run(session: Session, version: Version) -> anyhow::Result<()> { } // TypeScript -> Rust, with the default Rust windows. - let mut recv = moq_clock::timeout(TIMEOUT, session.accept_uni()) + let mut recv = kio::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(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 = moq_clock::timeout(TIMEOUT, session.open_uni(SendOptions::default())) + let mut send = kio::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) = moq_clock::timeout(TIMEOUT, session.accept_bi()) + let (mut send, mut recv) = kio::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(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 = moq_clock::timeout(TIMEOUT, session.recv_datagram()) + let datagram = kio::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(session: Session, version: Version) -> anyhow::Result<()> { bail!("QMux00 unexpectedly negotiated datagram support"); } - let closed = moq_clock::timeout(TIMEOUT, session.closed()) + let closed = kio::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.rs b/rs/qmux/src/session.rs index f2e401d2cad..4017ffbf75f 100644 --- a/rs/qmux/src/session.rs +++ b/rs/qmux/src/session.rs @@ -12,7 +12,7 @@ use std::task::Poll; use std::time::Duration; use bytes::{Buf, Bytes}; -use moq_clock::Instant; +use kio::clock::Instant; use moq_net::transport::{self as net, Address, poll}; use moq_quic::stream::{Dir, Id as StreamId}; use moq_quic::{ @@ -188,7 +188,7 @@ impl Inner { // Register first: a handle mutating the connection after this sweep re-polls us. waiter.register(&mut state.driver); loop { - let now = moq_clock::now(); + let now = kio::clock::now(); if state.conn.poll_timeout().is_some_and(|at| now >= at) { state.conn.handle_timeout(now); } @@ -226,7 +226,7 @@ impl Inner { state.conn.set_backpressured(true); } loop { - let now = moq_clock::now(); + let now = kio::clock::now(); if state.conn.is_closed() && timer.closing.is_none() { timer.closing = Some(now + CLOSE_TIMEOUT); } @@ -277,7 +277,7 @@ impl Inner { /// The writer's timers. #[derive(Default)] struct Timer { - sleep: Option, + sleep: Option, /// When a closing session gives up on delivering its close frame. closing: Option, /// The current write is stalled on the transport. @@ -290,7 +290,7 @@ impl Timer { let Some(deadline) = deadline else { return false; }; - if moq_clock::now() >= deadline { + if kio::clock::now() >= deadline { return true; } let sleep = match &mut self.sleep { @@ -300,7 +300,7 @@ impl Timer { } sleep } - None => self.sleep.insert(moq_clock::sleep_until(deadline)), + None => self.sleep.insert(kio::clock::sleep_until(deadline)), }; waiter.poll_future(Pin::new(sleep)).is_ready() } @@ -358,12 +358,12 @@ async fn run_writer(inner: Arc, mut writer: W, reader: tokio:: if result.is_ok() { let bound = timer .closing - .map_or(CLOSE_TIMEOUT, |at| at.saturating_duration_since(moq_clock::now())); + .map_or(CLOSE_TIMEOUT, |at| at.saturating_duration_since(kio::clock::now())); let close = async { let _ = reader.await; writer.close().await }; - let _ = moq_clock::timeout(bound, close).await; + let _ = kio::clock::timeout(bound, close).await; } inner.writer_done(result); } @@ -383,7 +383,7 @@ async fn run_reader(inner: Arc, mut reader: R) { Ok(record) => { state.received_bytes += record.len() as u64; inner.wire.set_received_bytes(state.received_bytes); - state.conn.handle_record(record, moq_clock::now()); + state.conn.handle_record(record, kio::clock::now()); } Err(Error::FrameTooLarge) => state.conn.handle_oversized(), Err(Error::FlowControlError) => state.conn.handle_violation(violation( @@ -459,7 +459,7 @@ impl Session { /// Start a session over the transport without waiting for the handshake, for callers /// that resolved the protocol out of band (the WebSocket subprotocol, say). pub(crate) fn new(transport: T, side: Side, config: Config) -> Result { - let conn = mux::Connection::new(config.to_mux()?, side, moq_clock::now()); + let conn = mux::Connection::new(config.to_mux()?, side, kio::clock::now()); let inner = Arc::new(Inner { state: Mutex::new(State { conn, diff --git a/rs/qmux/src/session/tests.rs b/rs/qmux/src/session/tests.rs index 4101c332489..5afd0f8dbfd 100644 --- a/rs/qmux/src/session/tests.rs +++ b/rs/qmux/src/session/tests.rs @@ -192,7 +192,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); - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; assert!(matches!(send.finish(), Err(Error::StreamStop(11)))); assert!(matches!(send.closed().await, Err(Error::StreamStop(11)))); } @@ -206,7 +206,7 @@ async fn dropping_an_unfinished_send_resets_it() { write_all(&mut send, Bytes::from_static(b"partial")).await; drop(send); let mut recv = server.accept_uni().await.unwrap(); - let read = moq_clock::timeout(Duration::from_secs(5), read_all(&mut recv)).await; + let read = kio::clock::timeout(Duration::from_secs(5), read_all(&mut recv)).await; assert!(matches!(read, Ok(Err(Error::StreamReset(0)))), "{read:?}"); } @@ -283,7 +283,7 @@ async fn a_request_before_the_handshake_waits_for_credit() { /// Poll `future` once, after letting every other task run. async fn futures_poll_once(future: &mut F) -> Option { - moq_clock::sleep(Duration::from_millis(10)).await; + kio::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), @@ -352,7 +352,7 @@ async fn websocket_keep_alive_runs_during_continuous_output() { if b_write.write_all(&buf[..n]).await.is_err() { return; } - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } }); tokio::spawn(async move { tokio::io::copy(&mut b_read, &mut a_write).await }); @@ -370,7 +370,7 @@ async fn websocket_keep_alive_runs_during_continuous_output() { let sender = Session::new(a, Side::Client, config.clone()).unwrap(); let _receiver = Session::new(b, Side::Server, config).unwrap(); while sender.max_datagram_size() == 0 { - moq_clock::sleep(Duration::from_millis(1)).await; + kio::clock::sleep(Duration::from_millis(1)).await; } // Far past the 500ms deadline, queueing more each tick than one batch carries @@ -450,10 +450,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 _ = moq_clock::timeout(Duration::from_millis(100), send.write(&payload(1 << 20, 0))).await; - moq_clock::sleep(Duration::from_millis(100)).await; + let _ = kio::clock::timeout(Duration::from_millis(100), send.write(&payload(1 << 20, 0))).await; + kio::clock::sleep(Duration::from_millis(100)).await; - let start = moq_clock::now(); + let start = kio::clock::now(); client.close(5, "stalled"); let err = client.closed().await; assert!(matches!(err, Error::ConnectionClosed { code: 5, .. }), "got {err:?}"); @@ -471,7 +471,7 @@ async fn a_silent_peer_times_out() { up.send(Flow::Drop).unwrap(); down.send(Flow::Drop).unwrap(); - let start = moq_clock::now(); + let start = kio::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)); @@ -481,7 +481,7 @@ async fn a_silent_peer_times_out() { #[tokio::test(start_paused = true)] async fn an_idle_session_stays_up() { let (client, _server) = pair(config(Version::QMux01), config(Version::QMux01)).await; - let closed = moq_clock::timeout(Duration::from_secs(120), client.closed()).await; + let closed = kio::clock::timeout(Duration::from_secs(120), client.closed()).await; assert!(closed.is_err(), "closed with {closed:?}"); } @@ -489,7 +489,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 = moq_clock::now(); + let start = kio::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/socket.rs b/rs/qmux/src/socket.rs index 99228421d8f..593ce824a91 100644 --- a/rs/qmux/src/socket.rs +++ b/rs/qmux/src/socket.rs @@ -42,7 +42,7 @@ pub type SharedSocketStats = Arc; #[cfg(any(target_os = "linux", test))] pub(crate) struct RateFilter { /// Strictly decreasing rates from front to back; the front is the maximum. - samples: std::collections::VecDeque<(moq_clock::Instant, u64)>, + samples: std::collections::VecDeque<(kio::clock::Instant, u64)>, } #[cfg(any(target_os = "linux", test))] @@ -51,8 +51,8 @@ impl RateFilter { pub(crate) const WINDOW: Duration = Duration::from_secs(10); /// Fold in one sample and return the current estimate, if there is one yet. - pub(crate) fn update(&mut self, now: moq_clock::Instant, rate: u64, app_limited: bool) -> Option { - let expired = |at: &moq_clock::Instant| now.saturating_duration_since(*at) > Self::WINDOW; + pub(crate) fn update(&mut self, now: kio::clock::Instant, rate: u64, app_limited: bool) -> Option { + let expired = |at: &kio::clock::Instant| now.saturating_duration_since(*at) > Self::WINDOW; let usable = rate > 0 && (!app_limited || self.samples.front().is_none_or(|(_, max)| rate >= *max)); // A rejected sample changes nothing, not even expiry: it is no evidence the // path got slower, so only a usable sample may retire an old maximum. @@ -307,7 +307,7 @@ mod unix { // The kernel reports bytes per second; the trait wants bits. let rate = info.delivery_rate.saturating_mul(8); let mut filter = self.rate.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - filter.update(moq_clock::now(), rate, app_limited) + filter.update(kio::clock::now(), rate, app_limited) } #[cfg(not(target_os = "linux"))] @@ -344,7 +344,7 @@ mod unix { #[cfg(test)] mod rate_filter_tests { use super::*; - use moq_clock::Instant; + use kio::clock::Instant; fn at(start: Instant, ms: u64) -> Instant { start + Duration::from_millis(ms) @@ -352,7 +352,7 @@ mod rate_filter_tests { #[test] fn app_limited_samples_do_not_lower_the_estimate() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); assert_eq!(f.update(t, 80_000_000, true), Some(80_000_000)); // A live stream mostly trickles: these samples measure the sender, not the path. @@ -363,7 +363,7 @@ mod rate_filter_tests { #[test] fn app_limited_samples_can_raise_the_estimate() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); assert_eq!(f.update(t, 1_000_000, true), Some(1_000_000)); assert_eq!(f.update(at(t, 100), 50_000_000, true), Some(50_000_000)); @@ -371,7 +371,7 @@ mod rate_filter_tests { #[test] fn measured_samples_lower_it_after_the_window() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); assert_eq!(f.update(t, 80_000_000, false), Some(80_000_000)); // A real, lower measurement waits for the older maximum to expire. @@ -381,7 +381,7 @@ mod rate_filter_tests { #[test] fn app_limited_samples_do_not_expire_the_maximum() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); f.update(t, 80_000_000, false); f.update(at(t, 1_000), 5_000_000, false); @@ -394,7 +394,7 @@ mod rate_filter_tests { #[test] fn the_window_keeps_the_largest_recent_measurement() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); f.update(t, 30_000_000, false); f.update(at(t, 4_000), 20_000_000, false); @@ -406,7 +406,7 @@ mod rate_filter_tests { #[test] fn zero_rate_keeps_the_estimate() { - let t = moq_clock::now(); + let t = kio::clock::now(); let mut f = RateFilter::default(); // The kernel reports zero until it has a sample. assert_eq!(f.update(t, 0, false), None); diff --git a/rs/qmux/src/transport.rs b/rs/qmux/src/transport.rs index dbfc3f88087..f5984597272 100644 --- a/rs/qmux/src/transport.rs +++ b/rs/qmux/src/transport.rs @@ -821,7 +821,7 @@ mod ws_transport { use bytes::Bytes; use futures::stream::SplitSink; - use moq_clock::{Interval, MissedTickBehavior, Sleep}; + use kio::clock::{Interval, MissedTickBehavior, Sleep}; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio_tungstenite::tungstenite; @@ -901,7 +901,7 @@ 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); + let mut interval = kio::clock::interval_at(kio::clock::now() + config.interval, config.interval); // Skip catch-up bursts after a long pause; we just want one Ping per tick. interval.set_missed_tick_behavior(MissedTickBehavior::Delay); Self { interval } @@ -919,13 +919,13 @@ mod ws_transport { fn new(config: KeepAlive) -> Self { let timeout = config.timeout; Self { - deadline: moq_clock::sleep(timeout), + deadline: kio::clock::sleep(timeout), timeout, } } fn observe_recv(&mut self) { - self.deadline.reset(moq_clock::now() + self.timeout); + self.deadline.reset(kio::clock::now() + self.timeout); } } @@ -1196,7 +1196,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. - moq_clock::sleep(Duration::from_millis(150)).await; + kio::clock::sleep(Duration::from_millis(150)).await; assert_eq!( rx.recv().await.expect("channel open").expect("no timeout"), @@ -1222,7 +1222,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 = moq_clock::timeout(Duration::from_secs(1), rx.recv()) + let result = kio::clock::timeout(Duration::from_secs(1), rx.recv()) .await .expect("keep-alive deadline should fire on a silent peer"); assert!( @@ -1244,7 +1244,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 = moq_clock::timeout(Duration::from_millis(100), rx.recv()).await; + let pending = kio::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 73578e28fe6..1aeedd88928 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(); - moq_clock::timeout(Duration::from_secs(1), session.closed()) + kio::clock::timeout(Duration::from_secs(1), session.closed()) .await .expect("the socket waited to buffer a frame larger than a record"); } diff --git a/sh/dispatch-query.test.py b/sh/dispatch-query.test.py index 4b46dd72084..67e605a073f 100644 --- a/sh/dispatch-query.test.py +++ b/sh/dispatch-query.test.py @@ -391,7 +391,7 @@ def test_terminating_the_run_stops_the_running_phase(self): "rs lint-changed "*) echo $$ >"{pid}"; echo >"{started}"; exec sleep 600 ;; esac ''') - self.change("rs/moq-clock/src/lib.rs") + self.change("rs/kio/src/clock/mod.rs") for jobs in ("1", "3"): with self.subTest(jobs=jobs): run = subprocess.Popen(["bash", "sh/dispatch.sh", "ci", "origin/main"], @@ -413,7 +413,7 @@ def test_terminating_the_run_stops_the_running_phase(self): os.kill(int(pid.read_text()), 0) def test_ci_runs_one_lint_preamble_and_one_test_pass(self): - self.change("rs/moq-clock/src/lib.rs") + self.change("rs/kio/src/clock/mod.rs") calls = self.run_ci() self.assertTrue(any(call.startswith("rs lint-changed ") for call in calls), calls) self.assertFalse(any(call.startswith("rs check-changed ") for call in calls), calls) @@ -423,7 +423,7 @@ def test_ci_runs_one_lint_preamble_and_one_test_pass(self): next(i for i, call in enumerate(calls) if call.startswith("rs test-changed "))) def test_rust_lane_runs_only_the_lint_and_the_test_build(self): - self.change("rs/moq-clock/src/lib.rs") + self.change("rs/kio/src/clock/mod.rs") calls = [call.split()[1] for call in self.run_ci() if call.startswith("rs ")] self.assertEqual(calls, ["lint-changed", "test-changed"]) diff --git a/test/interop/clients/rust/finish.rs b/test/interop/clients/rust/finish.rs index 1854dc20f88..3c13ac09920 100644 --- a/test/interop/clients/rust/finish.rs +++ b/test/interop/clients/rust/finish.rs @@ -115,7 +115,7 @@ async fn main() -> anyhow::Result<()> { let mut command = String::new(); stdin.read_line(&mut command).await?; ensure!(command == "read\n", "finish read phase was not released"); - moq_clock::timeout(args.timeout, async { + kio::clock::timeout(args.timeout, async { let mut routes = consumer.announced(); let broadcast = consumer.follow(&args.broadcast, None)?.available().await?; let mut catalogs =