diff --git a/doc/lib/rs/moq-mux.md b/doc/lib/rs/moq-mux.md index 25d907b2c44..ef841421581 100644 --- a/doc/lib/rs/moq-mux.md +++ b/doc/lib/rs/moq-mux.md @@ -114,7 +114,8 @@ telemetry lagging its video shows up as `delay`. A capture `Instant` (a datagram's arrival, a sensor read) converts with `Clock::capture` on the catalog's clock, which refuses an instant ahead of now. A timestamp ahead of now is published anyway and measured as zero delay, so a source clock running -slightly fast is not rejected. +slightly fast is not rejected. Capture inputs stay `std::time::Instant` on +native; browser targets refuse these native instants. ```rust let at = catalog.clock().capture(received_at)?; @@ -137,7 +138,8 @@ anchored root `clock` for readers that copy it once. Data tracks stamp on the clock too, even one created before that first frame, though anything it wrote earlier stays on the clock the catalog started with. A clock set with `Config::with_clock` is never re-anchored, for a recording whose zero names its -real start. +real start. The broadcast clock uses the async runtime's monotonic time, so +native tests can pause and advance it with Tokio; its wall mapping stays fixed. Group starts never go backwards. A group starting before the previous group's start ends the import with `TimestampRewind`, whose `timestamp` and `floor` fields diff --git a/js/publish/src/audio/encoder.test.ts b/js/publish/src/audio/encoder.test.ts index ffd4db52f96..c3d598aa224 100644 --- a/js/publish/src/audio/encoder.test.ts +++ b/js/publish/src/audio/encoder.test.ts @@ -395,24 +395,33 @@ test("passes an explicit Opus DTX request to the encoder", async () => { // it, which the catalog advertises as `delay`. test("a rendition trailing the broadcast's earliest advertises delay", async () => { using _webcodecs = installFakeWebCodecs(); - const baseline = new Baseline(); - using env = await setup(baseline); - const { encoder, feed } = env; + const clock = spyOn(performance, "now").mockReturnValue(200); - expect(encoder.out.catalog.peek()?.delay).toBeUndefined(); + try { + const baseline = new Baseline(); + using env = await setup(baseline); + const { encoder, feed } = env; - // A sibling flushing 100ms less late than this rendition ever can. Shifting the sibling rather - // than backdating this capture keeps timestamps non-negative however young the process is. - baseline.observe(-100_000, performance.now() * 1000); + expect(encoder.out.catalog.peek()?.delay).toBeUndefined(); - const start = performance.now() * 1000; - for (let index = 0; index < 4; index++) { - await feed.push({ timestamp: Time.Micro(start + index * 20_000), channels: [new Float32Array(960)] }); - } - await feed.drain(); + // A sibling that flushes each frame the instant it is captured. + baseline.observe(0, performance.now() * 1000); + + // Captured 100ms ago, with a clock origin that keeps timestamps nonnegative. + const start = performance.now() * 1000 - 100_000; + for (let index = 0; index < 4; index++) { + await feed.push({ timestamp: Time.Micro(start + index * 20_000), channels: [new Float32Array(960)] }); + } + await feed.drain(); - expect(env.written.length).toBe(2); - expect(encoder.out.catalog.peek()?.delay).toBeGreaterThanOrEqual(100); + expect(env.written).toEqual([ + [100_000, 1], + [120_000, 1], + ]); + expect(encoder.out.catalog.peek()).toMatchObject({ delay: 100 }); + } finally { + clock.mockRestore(); + } }); // Regression: codec settings that can't resolve left the encoder unsettled, so `` never diff --git a/quest/m1/quest-flat-lines.md b/quest/m1/quest-flat-lines.md index 4cfbbd4e3bb..0bdce596103 100644 --- a/quest/m1/quest-flat-lines.md +++ b/quest/m1/quest-flat-lines.md @@ -59,8 +59,8 @@ Remaining: #4403 wildcard, #4034 archive, #4039 auth, #4079 cpp, #4519 ffi-shape, #4080 obs-moq-video, #4133 qos (held until [Lag across a splice](/quest/m1/qos/lag-splice.md) is fixed), #4437 rs2ts, - #4653 test-flakes-2, #4180 transport-upgrade, #4640 tstd. #4162 - (audio-jitter-target) landed, and #4438 folded into rs2ts. + #4180 transport-upgrade, #4640 tstd. #4162 + (audio-jitter-target) and #4653 (test-flakes-2) landed, and #4438 folded into rs2ts. - Fold #4255 (archive/track-timeline) into the archive branch before #4034 lands; as of the 2026-10-05 audit it has not happened and #4034 is a draft. - Before a line lands and its branch is deleted, merge or retarget every child diff --git a/quest/m1/test-flakes-2/README.md b/quest/m1/test-flakes-2/README.md index 6e338309e9c..5d9095d498d 100644 --- a/quest/m1/test-flakes-2/README.md +++ b/quest/m1/test-flakes-2/README.md @@ -30,14 +30,8 @@ Public API: none. Wire: none. ## Required -- [moq-cli tests on a paused clock](/quest/m1/test-flakes-2/cli-paused-clock.md) - the fetch timeout and completion tests stop racing wall-clock budgets - [Subscription cut by disconnect](/quest/m1/test-flakes-2/subscription-cut.md) - a publisher disconnect never ends a subscription clean -- [Broadcast race](/quest/m1/test-flakes-2/broadcast-race.md) - the QUIC-wins race test binds no shared port and has a deterministic winner - [Media late join](/quest/m1/test-flakes-2/media-late-join.md) - `just test media` late join stays within one GOP, or the regression is fixed -- [Shaper virtual time](/quest/m1/test-flakes-2/shaper-virtual-time.md) - `moq-shaper` tests judge seeded decisions on paused time, not on wall-clock delivery under load -- [Scoped WARN capture](/quest/m1/test-flakes-2/warn-capture.md) - the drop-unfinished tests count only their own WARNs -- [moq-mux debounce clock](/quest/m1/test-flakes-2/mux-debounce-clock.md) - the TS export debounce test advances on the paused clock -- [js/publish audio clock](/quest/m1/test-flakes-2/publish-audio-clock.md) - the audio encoder delay test runs on mock time - [Rejoin after idle](/quest/m1/test-flakes-2/rejoin-idle-race.md) - an IETF rejoin never gets the stale warm cache first, because the copy goes idle before the cancel ## Related diff --git a/quest/m1/test-flakes-2/broadcast-race.md b/quest/m1/test-flakes-2/broadcast-race.md deleted file mode 100644 index 36b0ddf1850..00000000000 --- a/quest/m1/test-flakes-2/broadcast-race.md +++ /dev/null @@ -1,22 +0,0 @@ -# [S] Broadcast race without a shared port - -## Goal - -moq-tokio `broadcast_race_quic_wins` binds no port it didn't reserve and -has a deterministic winner. - -## Plan - -It binds TCP `:0` and then UDP on the same number, which nothing reserves: -the collision [#4084](https://github.com/moq-dev/moq/pull/4084) removed from -its sibling after [#4055](https://github.com/moq-dev/moq/pull/4055) papered -over it with a retry. - -The test shares one port only so both transports sit behind one URL. -Separate `:0` ports fix the bind collision but not the race itself: with -`websocket.delay = 0` either arm can legitimately win under load. Make the -order deterministic the way #4084 did, holding the WebSocket arm until QUIC -has connected, rather than asserting on a real race; no retry. #4084's -follow-ups (`tests/reconnect.rs` `spawn_server`, `tests/worker.rs` -`free_udp_port`) are the same probe-and-rebind pattern; fix them here if -cheap. diff --git a/quest/m1/test-flakes-2/cli-paused-clock.md b/quest/m1/test-flakes-2/cli-paused-clock.md deleted file mode 100644 index f29e8ab11c5..00000000000 --- a/quest/m1/test-flakes-2/cli-paused-clock.md +++ /dev/null @@ -1,30 +0,0 @@ -# [M] moq-cli tests on a paused clock - -## Goal - -The moq-cli fetch and completion tests pass under any host load: none of -them races a wall-clock budget against connect, TLS, announce, and -subscribe. - -## Plan - -- `fetch::tests::a_frame_read_times_out` asserts on a 500 ms wall deadline - ([#4084](https://github.com/moq-dev/moq/pull/4084)). - `rs/moq-cli/src/fetch.rs` wraps the whole run in one - `timeout_at(deadline, ...)`, so setup shares the budget with the read, and - under load setup alone can spend it. -- `complete::tests::a_stage_broadcast_picks_the_catalog_to_read` - ([#4084](https://github.com/moq-dev/moq/pull/4084)), - `the_catalog_format_on_the_line_is_honored` - ([#4089](https://github.com/moq-dev/moq/pull/4089)), and - `a_relay_on_the_line_answers_broadcast`: the latter pair came back empty - after the fixed 1.5 s `CEILING` on a loaded runner - ([#4404](https://github.com/moq-dev/moq/pull/4404)). - -Test on a paused clock (maintainer decision, 2026-09-28). The fixture runs -real sockets against an in-process relay, where a paused clock fires QUIC -timers while packets are in flight, so first make the timers mockable: run -the fixture over an in-memory transport, or drive noq's timers from the test -clock, whichever is smaller. Keep fetch's one absolute 30 s deadline, -matching the relay's `/fetch`; on a paused clock setup costs no time, so it -can't spend the read's budget. The completion tests reuse the same fixture. diff --git a/quest/m1/test-flakes-2/mux-debounce-clock.md b/quest/m1/test-flakes-2/mux-debounce-clock.md deleted file mode 100644 index e29f84934b2..00000000000 --- a/quest/m1/test-flakes-2/mux-debounce-clock.md +++ /dev/null @@ -1,15 +0,0 @@ -# [XS] moq-mux debounce test on the paused clock - -## Goal - -moq-mux `container::ts::export_test::debounce_opens_without_a_media_clock` -advances on the paused clock and sleeps no real time. - -## Plan - -It died with SIGTERM once in a combined run. It is marked -`start_paused = true` but sleeps 1.2 s of real time, because the debounce -reads `crate::Clock`, which uses `std::time::Instant`, so the paused tokio -clock never reaches it. Let the test drive `crate::Clock`'s time (a tokio -`Instant` under test, or an injected source) so the window passes on the -paused clock, and drop the real sleep. diff --git a/quest/m1/test-flakes-2/publish-audio-clock.md b/quest/m1/test-flakes-2/publish-audio-clock.md deleted file mode 100644 index ccc4becaadf..00000000000 --- a/quest/m1/test-flakes-2/publish-audio-clock.md +++ /dev/null @@ -1,11 +0,0 @@ -# [XS] js/publish audio delay test on mock time - -## Goal - -The js/publish audio encoder test "a rendition trailing the broadcast's -earliest advertises delay" passes when its file runs alone. - -## Plan - -It reads the real clock, so timestamps go negative early in the process and -it fails when run alone (#4414). Run it on mock time. diff --git a/quest/m1/test-flakes-2/shaper-virtual-time.md b/quest/m1/test-flakes-2/shaper-virtual-time.md deleted file mode 100644 index 3fea8a4fb46..00000000000 --- a/quest/m1/test-flakes-2/shaper-virtual-time.md +++ /dev/null @@ -1,18 +0,0 @@ -# [S] moq-shaper tests on virtual time - -## Goal - -The `moq-shaper` unit tests pass under any host load: their verdicts come -from the seeded decisions, not from how fast the kernel delivers datagrams. -`reorder_and_jitter_overtake` and `the_seed_reproduces_the_losses` saw every -datagram lost during a slowed full-workspace run, because `round_trip` stops -at the first 200 ms of silence on a real socket. - -## Plan - -- Drive the tests on paused tokio time (or an injected clock) so delay, - jitter, and the read deadline advance deterministically. -- Watch out: paused time auto-advances while the runtime idles, which can - fire a timer before a real UDP datagram lands. If the real sockets fight - the paused clock, separate the scheduling logic from the socket I/O and test - it directly, keeping one socket smoke test with a generous deadline. diff --git a/quest/m1/test-flakes-2/warn-capture.md b/quest/m1/test-flakes-2/warn-capture.md deleted file mode 100644 index d6f928e0c43..00000000000 --- a/quest/m1/test-flakes-2/warn-capture.md +++ /dev/null @@ -1,14 +0,0 @@ -# [XS] Scoped WARN capture - -## Goal - -moq-net `model::group::test::drop_unfinished_warns` and the `model::track` -test of the same name count only the WARNs their own code emits. - -## Plan - -Both count WARNs through a global tracing capture, so another test's WARN, -or a missed one, changes the count -([#4104](https://github.com/moq-dev/moq/pull/4104)). Capture per test, with a -scoped subscriber or a filter on the test's own span, instead of a -process-global count. diff --git a/rs/moq-cli/src/complete.rs b/rs/moq-cli/src/complete.rs index 9ce0390fe89..20748d5f5ac 100644 --- a/rs/moq-cli/src/complete.rs +++ b/rs/moq-cli/src/complete.rs @@ -338,7 +338,7 @@ mod tests { /// /// The root spec is the globals plus the first stage, so answering a later chunk /// against it offers process-wide flags that the chunk refuses. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn retargets_to_the_active_stage() { let _env = EnvGuard::clear(&["MOQ_CONNECT"]); // A stage offers its own flags, and none of the globals it would refuse. diff --git a/rs/moq-cli/src/fetch.rs b/rs/moq-cli/src/fetch.rs index 5d3a6d7e4d4..7dfeae88a0c 100644 --- a/rs/moq-cli/src/fetch.rs +++ b/rs/moq-cli/src/fetch.rs @@ -74,17 +74,46 @@ async fn fetch( .with_subscriber(origin.clone()) .with_reconnect(false); + fetch_from( + Request { + args, + path: &broadcast, + deadline, + }, + async { + let connection = client.connect(url).established().await.context("failed to connect")?; + anyhow::Ok((origin, connection)) + }, + out, + ) + .await +} + +/// The operation's selection and one absolute deadline, including setup. +struct Request<'a> { + args: &'a Args, + path: &'a str, + deadline: Instant, +} + +/// Keep setup and all reads under the caller's one absolute deadline. +async fn fetch_from( + request: Request<'_>, + setup: impl std::future::Future>, + out: &mut (impl AsyncWrite + Unpin), +) -> anyhow::Result<()> { + let Request { args, path, deadline } = request; let result = timeout_at(deadline, async { // Held until the last frame is read; dropping it closes the session. - let _connection = client.connect(url).established().await.context("failed to connect")?; + let (origin, _connection) = setup.await?; // Wait for a covering route rather than asking on the spot: the announcement // is still in flight right after connecting. let broadcast = origin .consume() - .routed_broadcast(broadcast.as_str()) + .routed_broadcast(path) .await - .with_context(|| format!("broadcast `{}` not found", crate::display_name(&broadcast)))?; + .with_context(|| format!("broadcast `{}` not found", crate::display_name(path)))?; let track = broadcast.track(&args.track)?; let mut group = moq_relay::fetch_group(&track, args.group) .await @@ -137,24 +166,73 @@ mod tests { ] } - /// A running relay with a publisher attached, and the flags that reach it. + /// An in-memory origin with the same finished, empty, and live tracks. struct Fixture { + origin: moq_net::origin::Producer, + _keep: ( + moq_net::broadcast::Producer, + Vec, + moq_net::group::Producer, + ), + } + + impl Fixture { + async fn new() -> Self { + let origin = moq_tokio::origin::spawn(); + let broadcast = origin.create_broadcast("demo").expect("broadcast"); + broadcast.announce(Default::default()).expect("announce"); + + let data = broadcast.create_track("data", None).expect("data track"); + for sequence in 0..3 { + let mut group = data.append_group().expect("group"); + for frame in frames(sequence) { + group.write_frame(moq_net::Timestamp::ZERO, frame).expect("frame"); + } + group.finish().expect("finish"); + } + let empty = broadcast.create_track("empty", None).expect("empty track"); + let live = broadcast.create_track("live", None).expect("live track"); + let mut open = live.append_group().expect("open group"); + open.write_frame(moq_net::Timestamp::ZERO, b"first".as_ref()) + .expect("frame"); + + Self { + origin, + _keep: (broadcast, vec![data, empty, live], open), + } + } + + async fn fetch(&self, args: &[&str], timeout: Duration) -> (anyhow::Result<()>, Vec) { + let (_, args) = parse(&[], "demo", args); + let mut out = Vec::new(); + let result = fetch_from( + Request { + args: &args, + path: "demo", + deadline: Instant::now() + timeout, + }, + std::future::ready(Ok((self.origin.clone(), ()))), + &mut out, + ) + .await; + (result, out) + } + } + + /// A running relay with a publisher attached, and the flags that reach it. + struct NetworkFixture { /// `--connect` and the TLS pin for the relay's generated certificate. connect: [String; 4], /// The relay's HTTP listener, for comparing against `/fetch`. http: std::net::SocketAddr, /// Kept so the published broadcast, its tracks, and the open group stay live. - _publisher: ( - moq_tokio::Connection, - Vec, - Vec, - moq_net::group::Producer, - ), + _publisher: (moq_tokio::Connection, Fixture), + /// Kept so the relay's hidden broadcast and its track stay live. + _hidden: (moq_net::broadcast::Producer, moq_net::track::Producer), } - impl Fixture { - /// Publish `demo` with three finished groups on `data`, no group on `empty`, - /// and one frame of a group that never finishes on `live`. + impl NetworkFixture { + /// Publish [`Fixture`]'s `demo` through a relay that also holds `.hidden`. async fn new() -> Self { let _ = moq_tokio::crypto::install_default(); let fixture = moq_relay::test_relay().await.expect("test relay"); @@ -185,29 +263,13 @@ mod tests { fixture.fingerprint.clone(), ]; - let origin = moq_tokio::origin::spawn(); - let broadcast = origin.create_broadcast("demo").expect("broadcast"); - broadcast.announce(Default::default()).expect("announce"); - - let data = broadcast.create_track("data", None).expect("data track"); - for sequence in 0..3 { - let mut group = data.append_group().expect("group"); - for frame in frames(sequence) { - group.write_frame(moq_net::Timestamp::ZERO, frame).expect("frame"); - } - group.finish().expect("finish"); - } - let empty = broadcast.create_track("empty", None).expect("empty track"); - let live = broadcast.create_track("live", None).expect("live track"); - let mut open = live.append_group().expect("open group"); - open.write_frame(moq_net::Timestamp::ZERO, b"first".as_ref()) - .expect("frame"); + let publisher = Fixture::new().await; let (moq, _) = parse(&connect, "demo", &[]); let connection = net() .client(moq.client.clone()) .expect("client") - .with_publisher(origin.consume()) + .with_publisher(publisher.origin.consume()) .with_reconnect(false) .connect(fixture.url.clone()) .established() @@ -217,23 +279,14 @@ mod tests { Self { connect, http: fixture.http, - _publisher: ( - connection, - vec![broadcast, hidden], - vec![data, empty, live, secret], - open, - ), + _publisher: (connection, publisher), + _hidden: (hidden, secret), } } - /// Run `moq --broadcast demo fetch ` with `timeout`, returning - /// the outcome and what it wrote. - async fn fetch(&self, args: &[&str], timeout: Duration) -> (anyhow::Result<()>, Vec) { - self.fetch_from("demo", args, timeout).await - } - - /// [`Self::fetch`] from another broadcast. - async fn fetch_from(&self, broadcast: &str, args: &[&str], timeout: Duration) -> (anyhow::Result<()>, Vec) { + /// Run `moq --broadcast fetch ` with `timeout`, + /// returning the outcome and what it wrote. + async fn fetch(&self, broadcast: &str, args: &[&str], timeout: Duration) -> (anyhow::Result<()>, Vec) { let (moq, args) = parse(&self.connect, broadcast, args); let mut out = Vec::new(); let result = super::fetch(&moq, &args, &net(), Instant::now() + timeout, &mut out).await; @@ -277,7 +330,7 @@ mod tests { const ENV: &[&str] = &["MOQ_CONNECT", "MOQ_HOP"]; /// A known sequence prints its frames back to back, the same bytes as `/fetch`. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_sequence_prints_its_exact_bytes() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; @@ -285,11 +338,10 @@ mod tests { let (result, out) = fixture.fetch(&["data", "--group", "1"], TIMEOUT).await; result.expect("fetch"); assert_eq!(out, frames(1).concat()); - assert_eq!(fixture.curl("?group=1").await, (200, out)); } /// No `--group` reads the newest group, as `/fetch` does by default. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn the_default_is_the_newest_group() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; @@ -297,23 +349,23 @@ mod tests { let (result, out) = fixture.fetch(&["data"], TIMEOUT).await; result.expect("fetch"); assert_eq!(out, frames(2).concat()); - assert_eq!(fixture.curl("").await, (200, out)); } - /// A hidden broadcast such as `.stats` is fetched by name, as `/fetch` serves it. + /// A hidden broadcast such as `.stats` is fetched by name from a real relay, as + /// `/fetch` serves it: the relay's announce scoping is what hides it. #[tokio::test] async fn a_hidden_broadcast_is_fetched_by_name() { let _env = EnvGuard::clear(ENV); - let fixture = Fixture::new().await; + let fixture = NetworkFixture::new().await; - let (result, out) = fixture.fetch_from(".hidden", &["data"], Duration::from_secs(5)).await; + let (result, out) = fixture.fetch(".hidden", &["data"], Duration::from_secs(5)).await; result.expect("fetch"); assert_eq!(out, b"secret"); } /// A missing sequence fails the lookup itself, before any output, as `/fetch` /// answers 404 rather than starting a body. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_missing_sequence_fails() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; @@ -322,16 +374,15 @@ mod tests { let err = result.expect_err("group 99 does not exist"); assert_eq!(err.to_string(), "group 99 of `data` not found", "{err:#}"); assert!(out.is_empty()); - assert_eq!(fixture.curl("?group=99").await, (404, Vec::new())); } /// A track with no group never resolves "newest", so the deadline ends it. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_lookup_times_out() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; - let (result, out) = fixture.fetch(&["empty"], Duration::from_millis(500)).await; + let (result, out) = fixture.fetch(&["empty"], TIMEOUT).await; let err = result.expect_err("no group ever arrives"); assert!(err.to_string().contains("timed out"), "{err:#}"); assert!(out.is_empty()); @@ -339,21 +390,80 @@ mod tests { /// A group that never finishes is cut off by the same deadline, after the frames /// that did arrive. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_frame_read_times_out() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; - let (result, out) = fixture - .fetch(&["live", "--group", "0"], Duration::from_millis(500)) - .await; + let (result, out) = fixture.fetch(&["live", "--group", "0"], TIMEOUT).await; let err = result.expect_err("the group never finishes"); assert!(err.to_string().contains("timed out"), "{err:#}"); assert_eq!(out, b"first"); } - /// Each `--json` line is the whole record and decodes to the frame's bytes. + /// Discovery and reads share the deadline; setup cannot grant a fresh budget. + #[tokio::test(start_paused = true)] + async fn setup_and_reads_share_one_deadline() { + let _env = EnvGuard::clear(ENV); + let fixture = Fixture::new().await; + let (_, args) = parse(&[], "demo", &["live", "--group", "0"]); + let started = Instant::now(); + let mut out = Vec::new(); + let result = fetch_from( + Request { + args: &args, + path: "demo", + deadline: started + TIMEOUT, + }, + async { + // Advance simulated discovery time before handing back the ready origin. + tokio::time::advance(TIMEOUT / 2).await; + Ok((fixture.origin.clone(), ())) + }, + &mut out, + ) + .await; + assert_eq!(result.unwrap_err().to_string(), "fetch timed out"); + assert_eq!(out, b"first"); + assert_eq!(Instant::now() - started, TIMEOUT); + } + + /// A setup that never establishes is bounded by that same deadline. + #[tokio::test(start_paused = true)] + async fn setup_is_bounded() { + let _env = EnvGuard::clear(ENV); + let (_, args) = parse(&[], "demo", &["data"]); + let started = Instant::now(); + let result = fetch_from::<()>( + Request { + args: &args, + path: "demo", + deadline: started + TIMEOUT, + }, + std::future::pending(), + &mut Vec::new(), + ) + .await; + assert_eq!(result.unwrap_err().to_string(), "fetch timed out"); + assert_eq!(Instant::now() - started, TIMEOUT); + } + + /// The real HTTP endpoint agrees with the deterministic operation tests. #[tokio::test] + async fn real_relay_matches_http_fetch() { + let _env = EnvGuard::clear(ENV); + for (query, expected) in [ + ("?group=1", (200, frames(1).concat())), + ("", (200, frames(2).concat())), + ("?group=99", (404, Vec::new())), + ] { + let fixture = NetworkFixture::new().await; + assert_eq!(fixture.curl(query).await, expected); + } + } + + /// Each `--json` line is the whole record and decodes to the frame's bytes. + #[tokio::test(start_paused = true)] async fn json_lines_decode_to_the_frames() { let _env = EnvGuard::clear(ENV); let fixture = Fixture::new().await; diff --git a/rs/moq-cli/tests/export.rs b/rs/moq-cli/tests/export.rs index 3815187993a..5363875b43a 100644 --- a/rs/moq-cli/tests/export.rs +++ b/rs/moq-cli/tests/export.rs @@ -151,14 +151,15 @@ async fn a_clean_finish_exits_zero_once_the_linger_expires() { let (mut publisher, feeding) = import(&relay); let stdin = feeding.await.unwrap(); output_past(&output, 0).await; + // The linger can't start before stdin closes, but it can before the publisher exits. + let closed = Instant::now(); drop(stdin); assert!(wait(&mut publisher).await.success()); - let finished = Instant::now(); let status = wait(&mut export).await; assert!(status.success(), "a clean finish exits 0, got {status}"); assert!( - finished.elapsed() >= Duration::from_millis(900), + closed.elapsed() >= Duration::from_millis(900), "the export waited out its linger" ); } diff --git a/rs/moq-mux/src/clock.rs b/rs/moq-mux/src/clock.rs index bb233c80a90..fb0c1b63a54 100644 --- a/rs/moq-mux/src/clock.rs +++ b/rs/moq-mux/src/clock.rs @@ -19,6 +19,18 @@ use std::time::{Duration, Instant, SystemTime}; use hang::catalog::{MAX_SAFE_INTEGER, MOQ_EPOCH_UNIX_MILLIS}; +/// Native capture inputs use the same epoch as the async clock. +fn monotonic(at: Instant) -> crate::Result { + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + return Ok(web_async::time::Instant::from_std(at)); + + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] + { + let _ = at; + Err(anyhow::anyhow!("std::time::Instant inputs are unsupported in the browser").into()) + } +} + /// The catalog clock for PTS zero at `wall`. fn wall_clock(wall: SystemTime) -> crate::Result { let unix_micros = wall @@ -51,7 +63,7 @@ fn wall_clock(wall: SystemTime) -> crate::Result { #[derive(Clone, Copy, Debug)] pub struct Clock { /// A monotonic instant, and what the clock read then in micros. - instant: Instant, + instant: web_async::time::Instant, reading: u64, wall: hang::catalog::Clock, } @@ -78,10 +90,10 @@ impl Clock { /// Start a clock at an explicit monotonic epoch and wall time: PTS zero at both. /// /// The deterministic constructor: synthetic sources and fixtures pin both ends instead of - /// sampling. Refuses an unrepresentable wall. + /// sampling. Refuses an unrepresentable wall or a browser target without native instants. pub fn at(epoch: Instant, wall: SystemTime) -> crate::Result { Ok(Self { - instant: epoch, + instant: monotonic(epoch)?, reading: 0, wall: wall_clock(wall)?, }) @@ -92,7 +104,7 @@ impl Clock { /// Refuses a `since` so large that PTS zero lands before the moq epoch (2020), which the wall /// mapping cannot name. pub(crate) fn arrival(since: Duration) -> crate::Result { - let (instant, now) = (Instant::now(), SystemTime::now()); + let (instant, now) = (web_async::time::Instant::now(), SystemTime::now()); let unmappable = || crate::Error::UnmappableTimestamp(format!("{since:?} puts PTS zero before 2020")); let zero = now.checked_sub(since).ok_or_else(unmappable)?; Ok(Self { @@ -113,9 +125,11 @@ impl Clock { /// Map the instant a payload was captured (a datagram's arrival, a sensor read) onto this 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. + /// it existed, and one before PTS zero, which no timestamp can name. Native capture instants + /// are unsupported in the browser. pub fn capture(&self, at: Instant) -> crate::Result { - if at > Instant::now() { + let at = monotonic(at)?; + if at > web_async::time::Instant::now() { return Err(crate::Error::InvalidCapture); } let micros = match at.checked_duration_since(self.instant) { @@ -196,6 +210,35 @@ mod tests { )); } + #[tokio::test(start_paused = true)] + async fn paused_clock_preserves_native_boundaries() { + let epoch = tokio::time::Instant::now(); + let clock = Clock::at(epoch.into_std(), moq_epoch()).unwrap(); + let fresh = Clock::new(); + let before = fresh.now(); + let wall = clock.wall(); + + tokio::time::advance(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); + assert_eq!( + clock.wall_clock(clock.now()).unwrap(), + moq_epoch() + Duration::from_secs(3) + ); + + let captured = (epoch + Duration::from_secs(2)).into_std(); + assert_eq!(clock.capture(captured).unwrap(), us(2_000_000)); + assert!(matches!( + clock.capture((epoch + Duration::from_secs(4)).into_std()), + Err(crate::Error::InvalidCapture) + )); + assert!(matches!( + clock.capture((epoch - Duration::from_secs(1)).into_std()), + Err(crate::Error::InvalidCapture) + )); + } + #[test] fn section_advertises_wall_in_clock_timescale() { // PTS zero at exactly the moq epoch advertises 0. diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 0bacdf53784..9f38f8e359c 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -5016,8 +5016,8 @@ async fn contiguous_same_version_commit_replaces_stale_sections() { } /// The cut debounce runs on the host clock, so a revision publishes even when no -/// media ever advances a PTS (an audio-only or SI-only input). This test spends -/// real wall time on the debounce window; media timestamps stay pinned at zero +/// media ever advances a PTS (an audio-only or SI-only input). The paused tokio +/// clock steps over the debounce window; media timestamps stay pinned at zero /// throughout, which is exactly the case a media-clock debounce wedges on. #[tokio::test(start_paused = true)] async fn debounce_opens_without_a_media_clock() { @@ -5038,8 +5038,8 @@ async fn debounce_opens_without_a_media_clock() { .unwrap(); assert_eq!(track.latest(), Some(0), "a revision inside the window is held"); - // ...and publishes once the window passes in *real* time, no finish, no PTS. - std::thread::sleep(Duration::from_millis(1200)); + // ...and publishes once the window passes on the host clock, no finish, no PTS. + tokio::time::advance(Duration::from_millis(1200)).await; rig.import .decode(&BytesMut::from(&si_packet_cc(0x0011, &sdt(1, 0xbb), 3)[..])) .unwrap(); diff --git a/rs/moq-mux/src/container/ts/si.rs b/rs/moq-mux/src/container/ts/si.rs index b00f611ee4c..f11f2602ac8 100644 --- a/rs/moq-mux/src/container/ts/si.rs +++ b/rs/moq-mux/src/container/ts/si.rs @@ -29,6 +29,8 @@ use std::collections::{BTreeMap, HashMap}; use std::time::Duration; +use web_async::time::Instant; + use bytes::Bytes; use moq_net::Timestamp; @@ -213,8 +215,8 @@ struct Entry { /// The entry appears in the catalog's `mpegts.si` map: exactly while it is /// `populated`, so a subscriber never finds an empty track. advertised: bool, - /// Host-clock micros of the last cut ([`DEBOUNCE`]); `None` until the first. - last_cut: Option, + /// Host-clock instant of the last cut ([`DEBOUNCE`]); `None` until the first. + last_cut: Option, } impl Entry { @@ -345,7 +347,7 @@ impl Entry { broadcast: &moq_net::broadcast::Producer, (pid, table_id): (u16, u8), pts: Timestamp, - now: u128, + now: Instant, ) -> anyhow::Result<()> { let frames: Vec> = self .active @@ -389,8 +391,6 @@ pub(super) struct Capture { broadcast: moq_net::broadcast::Producer, catalog: crate::catalog::Producer, entries: BTreeMap<(u16, u8), Entry>, - /// Host clock driving the cut debounce (see [`DEBOUNCE`]). - clock: crate::Clock, /// The selected program_number, which is the service_id of the only service /// carried; `None` captures every service. program: Option, @@ -402,7 +402,6 @@ impl Capture { broadcast, catalog, entries: BTreeMap::new(), - clock: crate::Clock::new(), program: None, } } @@ -467,14 +466,14 @@ 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 = self.clock.now().as_micros(); + let now = Instant::now(); for (key, entry) in self.entries.iter_mut() { if !entry.dirty { continue; } if !force && let Some(last) = entry.last_cut - && now.saturating_sub(last) < DEBOUNCE.as_micros() + && now.saturating_duration_since(last) < DEBOUNCE { continue; } diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 0c9f9edd754..4c03a06b4ee 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -2132,7 +2132,7 @@ mod test { drop(writer); drop(producer); }); - assert!(warns >= 1, "unfinished drop must emit unfinished-producer WARN"); + assert_eq!(warns, 1, "unfinished drop must emit one unfinished-producer WARN"); } #[test] diff --git a/rs/moq-net/src/model/test_tracing.rs b/rs/moq-net/src/model/test_tracing.rs index 63caa9d852c..c1d315f1032 100644 --- a/rs/moq-net/src/model/test_tracing.rs +++ b/rs/moq-net/src/model/test_tracing.rs @@ -1,80 +1,118 @@ //! Tracing helpers shared by model tests. -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; +use std::cell::RefCell; +use std::sync::Once; use tracing::field::{Field, Visit}; use tracing::span::{Attributes, Id, Record}; use tracing::{Event, Level, Metadata, Subscriber}; -/// Count WARN events whose `message` field contains `expected_message` while running `f`. +/// The capture active on this thread: the message to match and how many WARNs matched. +struct Capture { + expected: String, + hits: usize, +} + +thread_local! { + static CAPTURE: RefCell> = const { RefCell::new(None) }; +} + +/// Count WARN events emitted on this thread whose `message` field contains `expected_message` +/// while running `f`. /// -/// Uses only the existing `tracing` dependency (no tracing-subscriber). +/// The subscriber is process-global rather than scoped with `with_default`: tracing caches each +/// callsite's interest process-wide, so a parallel test reaching the WARN first on a thread +/// without a scoped subscriber disables it for every thread. Counting per thread keeps another +/// test's WARNs out. pub(crate) fn count_drop_warnings(expected_message: &str, f: impl FnOnce()) -> usize { - struct Count { - hits: Arc, - expected: String, - } + static INSTALL: Once = Once::new(); + INSTALL.call_once(|| tracing::subscriber::set_global_default(Warns).expect("no other global subscriber")); + // A callsite first reached on another thread while the install above was still publishing + // sees no subscriber and is cached as disabled. Every capture starts after the install has + // completed, so rebuilding here re-enables it against the now-global subscriber. + tracing::callsite::rebuild_interest_cache(); - struct Msg<'a> { - expected: &'a str, - matched: bool, - } + let capture = Capture { + expected: expected_message.to_owned(), + hits: 0, + }; + let prev = CAPTURE.replace(Some(capture)); + assert!(prev.is_none(), "count_drop_warnings does not nest"); - impl Visit for Msg<'_> { - fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { - if field.name() == "message" { - let s = format!("{value:?}"); - if s.contains(self.expected) { - self.matched = true; - } - } - } + f(); - fn record_str(&mut self, field: &Field, value: &str) { - if field.name() == "message" && value.contains(self.expected) { - self.matched = true; - } - } - } + CAPTURE.take().expect("capture still installed").hits +} - impl Subscriber for Count { - fn enabled(&self, metadata: &Metadata<'_>) -> bool { - *metadata.level() == Level::WARN - } +/// Routes every WARN to the capture on the emitting thread, if any. +struct Warns; - fn new_span(&self, _span: &Attributes<'_>) -> Id { - Id::from_u64(1) - } +impl Subscriber for Warns { + fn enabled(&self, metadata: &Metadata<'_>) -> bool { + *metadata.level() == Level::WARN + } - fn record(&self, _span: &Id, _values: &Record<'_>) {} + fn new_span(&self, _span: &Attributes<'_>) -> Id { + Id::from_u64(1) + } + + fn record(&self, _span: &Id, _values: &Record<'_>) {} - fn record_follows_from(&self, _span: &Id, _follows: &Id) {} + fn record_follows_from(&self, _span: &Id, _follows: &Id) {} - fn event(&self, event: &Event<'_>) { + fn event(&self, event: &Event<'_>) { + CAPTURE.with_borrow_mut(|capture| { + let Some(capture) = capture else { return }; let mut msg = Msg { - expected: &self.expected, + expected: &capture.expected, matched: false, }; event.record(&mut msg); if msg.matched { - self.hits.fetch_add(1, AtomicOrdering::SeqCst); + capture.hits += 1; } + }); + } + + fn enter(&self, _span: &Id) {} + + fn exit(&self, _span: &Id) {} +} + +struct Msg<'a> { + expected: &'a str, + matched: bool, +} + +impl Visit for Msg<'_> { + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" && format!("{value:?}").contains(self.expected) { + self.matched = true; } + } - fn enter(&self, _span: &Id) {} + fn record_str(&mut self, field: &Field, value: &str) { + if field.name() == "message" && value.contains(self.expected) { + self.matched = true; + } + } +} + +mod tests { + use super::count_drop_warnings; - fn exit(&self, _span: &Id) {} + fn probe() { + tracing::warn!("test_tracing probe"); } - let hits = Arc::new(AtomicUsize::new(0)); - let expected = expected_message.to_owned(); - tracing::subscriber::with_default( - Count { - hits: hits.clone(), - expected, - }, - f, - ); - hits.load(AtomicOrdering::SeqCst) + /// Another thread without a capture reaching the WARN first must neither disable it for this + /// thread nor be counted here. + #[test] + fn counts_only_this_threads_warns() { + let warns = count_drop_warnings("test_tracing probe", || { + std::thread::spawn(probe).join().unwrap(); + probe(); + }); + assert_eq!(warns, 1); + } } diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 86dcb76c376..973c8f6ad8a 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -6782,7 +6782,7 @@ mod test { drop(writer); drop(producer); }); - assert!(warns >= 1, "unfinished drop must emit unfinished-producer WARN"); + assert_eq!(warns, 1, "unfinished drop must emit one unfinished-producer WARN"); } #[tokio::test] diff --git a/rs/moq-shaper/src/lib.rs b/rs/moq-shaper/src/lib.rs index 4e9ca01e5ac..66e359f0339 100644 --- a/rs/moq-shaper/src/lib.rs +++ b/rs/moq-shaper/src/lib.rs @@ -30,14 +30,20 @@ use std::{ time::Duration, }; +#[cfg(test)] +mod mem; mod preset; pub use preset::Preset; use anyhow::Context; +#[cfg(test)] +use mem::UdpSocket; use rand::{RngExt, SeedableRng, rngs::Xoshiro256PlusPlus}; use serde::{Deserialize, Serialize}; -use tokio::{net::UdpSocket, sync::mpsc, task::JoinSet, time::Instant}; +#[cfg(not(test))] +use tokio::net::UdpSocket; +use tokio::{sync::mpsc, task::JoinSet, time::Instant}; /// How one direction of the path treats each datagram. /// @@ -995,7 +1001,7 @@ mod tests { got } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn forwards_both_ways_untouched() { let (shaper, client) = setup(1, Profile::default(), Profile::default()).await; let got = round_trip(&client, 50).await; @@ -1022,7 +1028,7 @@ mod tests { assert_eq!(start.elapsed(), Duration::ZERO); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn the_seed_reproduces_the_losses() { let lossy = Profile { loss: 0.3, @@ -1042,7 +1048,7 @@ mod tests { assert_eq!(first_got.len() as u64, 200 - first.stats().up.lost); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn reorder_and_jitter_overtake() { let shuffled = Profile { delay: Duration::from_millis(20), @@ -1062,7 +1068,7 @@ mod tests { assert!(stats.up.reordered > 0, "{stats}"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn the_rate_limit_queues_then_drops() { // 100 datagrams of 4 bytes is 3200 bits: at 8 kbit/s they need 400ms, // and the queue only holds 100ms of it. @@ -1085,7 +1091,7 @@ mod tests { assert!(got.windows(2).all(|pair| pair[0] < pair[1]), "{got:?}"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_rate_limit_wider_than_the_traffic_passes_everything() { let wide = Profile { rate: Some(Rate { @@ -1102,7 +1108,7 @@ mod tests { assert_eq!(shaper.verify().unwrap().up.overflowed, 0); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn the_burst_counts_the_datagram_itself() { // A burst of one datagram lets the first out at once and holds the second. let one = Profile { @@ -1184,7 +1190,7 @@ mod tests { assert_eq!(unapplied(&phases, &stats), ["loss"]); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn an_invalid_profile_is_refused() { let refused = |bad: Profile, why: &'static str| async move { let err = Shaper::bind(Config { @@ -1268,7 +1274,7 @@ mod tests { steps: Vec::new(), }; - #[tokio::test] + #[tokio::test(start_paused = true)] async fn only_the_gaussian_model_keeps_the_order() { let jittery = Profile { delay: Duration::from_millis(20), @@ -1387,7 +1393,7 @@ mod tests { assert!(first_counters.lost > 0 && first_counters.reordered > 0); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_gaussian_sigma_may_exceed_the_delay() { // The uniform model refuses this; a gaussian clamps its draw at zero. let wide = Profile { @@ -1457,7 +1463,7 @@ mod tests { got } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_shared_path_keeps_the_order_across_clients() { let jittery = Profile { delay: Duration::from_millis(20), @@ -1530,7 +1536,7 @@ mod tests { } } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_batch_releases_on_count_and_on_the_window() { let socket = Arc::new(UdpSocket::bind(LOCALHOST).await.unwrap()); let ms = |ms| Duration::from_millis(ms); @@ -1609,7 +1615,7 @@ mod tests { assert_eq!(tally.batched.load(Ordering::Relaxed), 0); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_batch_releases_datagrams_together() { let (shaper, client) = shaped(|config| Setup { up: batched(7, Duration::from_millis(160)), @@ -1644,7 +1650,7 @@ mod tests { ); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn the_window_releases_a_batch_that_never_fills() { let (shaper, client) = shaped(|config| Setup { up: batched(100, Duration::from_millis(80)), @@ -1659,7 +1665,7 @@ mod tests { assert_eq!(shaper.verify().unwrap().up.delayed, 3); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_shared_batch_fills_from_every_client() { // Three datagrams from each of two clients, into batches of six: only a // shared path fills one, and separate links wait out the window. @@ -1684,7 +1690,7 @@ mod tests { } } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_batch_needs_a_count_and_a_window() { let refused = |options: Options, why: &'static str| async move { let config = Config { @@ -1812,7 +1818,7 @@ mod tests { assert_eq!(lost(start + secs(60)), 0, "the step back never cleared"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_step_gets_worse_part_way_through() { let ms = Duration::from_millis; let (shaper, client) = shaped(|config| Setup { @@ -1849,7 +1855,7 @@ mod tests { shaper.verify().unwrap(); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_step_the_run_never_reached_is_unapplied() { let (shaper, client) = shaped(|config| Setup { down: stepped(vec![Step { @@ -1866,8 +1872,7 @@ mod tests { assert!(format!("{err:#}").contains("the down step at 60s"), "{err:#}"); } - // Real sockets, so the wall clock: a paused one could jump past a step while a datagram is still in the kernel. - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_step_no_datagram_saw_is_unapplied() { let ms = Duration::from_millis; let (shaper, client) = shaped(|config| Setup { @@ -1909,7 +1914,7 @@ mod tests { assert!(!err.contains("the up step at 200ms"), "{err}"); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn a_profile_no_datagram_saw_before_its_step_is_unapplied() { let ms = Duration::from_millis; let (shaper, client) = shaped(|config| Setup { @@ -1954,7 +1959,7 @@ mod tests { assert_eq!(owed(&mut link, start + Duration::from_secs(1), &[16]), [Duration::ZERO]); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn steps_that_would_be_skipped_or_do_nothing_are_refused() { let refused = |steps: Vec, why: &'static str| async move { let config = Config { diff --git a/rs/moq-shaper/src/mem.rs b/rs/moq-shaper/src/mem.rs new file mode 100644 index 00000000000..bf7e8964364 --- /dev/null +++ b/rs/moq-shaper/src/mem.rs @@ -0,0 +1,93 @@ +//! An in-memory stand-in for [`tokio::net::UdpSocket`], so the unit tests run +//! on a paused clock. A paused clock jumps to the next timer whenever the +//! runtime idles, which would fire timeouts and steps while a real datagram +//! sat in the kernel; a datagram here is delivered inside the runtime, so the +//! clock only moves once nothing is in flight. `tests/cli.rs` covers real sockets. + +use std::{ + collections::HashMap, + io, + net::SocketAddr, + sync::{ + LazyLock, Mutex, OnceLock, + atomic::{AtomicU16, Ordering}, + }, +}; + +use tokio::sync::mpsc; + +type Datagram = (SocketAddr, Vec); + +/// Every bound socket by port, which is the whole address on this network. +static PORTS: LazyLock>>> = LazyLock::new(Default::default); +static NEXT_PORT: AtomicU16 = AtomicU16::new(1); + +pub struct UdpSocket { + addr: SocketAddr, + peer: OnceLock, + queue: tokio::sync::Mutex>, +} + +impl UdpSocket { + pub async fn bind(mut addr: SocketAddr) -> io::Result { + if addr.port() == 0 { + addr.set_port(NEXT_PORT.fetch_add(1, Ordering::Relaxed)); + } + let (send, queue) = mpsc::unbounded_channel(); + let mut ports = PORTS.lock().unwrap(); + if ports.contains_key(&addr.port()) { + return Err(io::ErrorKind::AddrInUse.into()); + } + ports.insert(addr.port(), send); + Ok(Self { + addr, + peer: OnceLock::new(), + queue: tokio::sync::Mutex::new(queue), + }) + } + + pub fn local_addr(&self) -> io::Result { + Ok(self.addr) + } + + pub async fn connect(&self, peer: SocketAddr) -> io::Result<()> { + self.peer.set(peer).map_err(|_| io::ErrorKind::AlreadyExists.into()) + } + + /// Like UDP, a datagram to a port nobody bound is lost without an error. + pub async fn send_to(&self, buf: &[u8], dest: SocketAddr) -> io::Result { + if let Some(port) = PORTS.lock().unwrap().get(&dest.port()) { + let _ = port.send((self.addr, buf.to_vec())); + } + Ok(buf.len()) + } + + pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + // The port's sender lives until this socket drops, so the queue never ends. + let (from, datagram) = self.queue.lock().await.recv().await.expect("bound port"); + let size = datagram.len().min(buf.len()); + buf[..size].copy_from_slice(&datagram[..size]); + Ok((size, from)) + } + + pub async fn send(&self, buf: &[u8]) -> io::Result { + self.send_to(buf, *self.peer.get().expect("not connected")).await + } + + /// Only what the connected peer sends, as a connected UDP socket filters. + pub async fn recv(&self, buf: &mut [u8]) -> io::Result { + let peer = *self.peer.get().expect("not connected"); + loop { + let (size, from) = self.recv_from(buf).await?; + if from == peer { + return Ok(size); + } + } + } +} + +impl Drop for UdpSocket { + fn drop(&mut self) { + PORTS.lock().unwrap().remove(&self.addr.port()); + } +} diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index d7c517d2582..9e87ff4fa7a 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -1332,6 +1332,120 @@ mod tests { accepted.await.unwrap().expect("server handshake failed"); } + /// QUIC wins while the fallback handshake is held until QUIC connects. + /// Each transport owns its ephemeral port; this exercises the same race as + /// connect_inner without depending on which real handshake runs faster. + #[cfg(all(feature = "websocket", feature = "noq"))] + #[tracing_test::traced_test] + #[tokio::test] + async fn broadcast_race_quic_wins() { + let pub_origin = crate::origin::spawn(); + let broadcast = pub_origin.create_broadcast("test").expect("failed to create broadcast"); + broadcast + .announce(Default::default()) + .expect("failed to create broadcast"); + let track = broadcast.create_track("video", None).expect("failed to create track"); + let mut group = track.append_group().expect("failed to append group"); + group + .write_frame(crate::moq_net::Timestamp::ZERO, b"hello".as_ref()) + .expect("failed to write frame"); + group.finish().expect("failed to finish group"); + + let ws_listener = crate::websocket::Listener::bind("[::]:0".parse().unwrap()) + .await + .expect("failed to bind WebSocket listener"); + let ws_port = ws_listener.local_addr().expect("failed to get ws addr").port(); + let (connected, quic_connected) = tokio::sync::oneshot::channel(); + let websocket_handle = tokio::spawn(async move { + quic_connected.await.expect("QUIC connected"); + ws_listener.accept().await + }); + + let mut server_config = crate::listen::Config { + bind: Some("[::]:0".parse().unwrap()), + ..Default::default() + }; + server_config.tls.generate = vec!["localhost".into()]; + let server = server_config.init(Default::default()).expect("failed to init server"); + let mut server = server.listen().await.expect("failed to listen"); + let quic_port = server.local_addr().expect("failed to get QUIC addr").port(); + + let sub_origin = crate::origin::spawn(); + let sub_consumer = sub_origin.consume(); + let mut announcements = sub_consumer.announced(); + let mut client_config = crate::connect::Config::default(); + client_config.tls.insecure = Some(true); + // Dial both arms immediately; the fallback handshake is gated by QUIC. + client_config.websocket.delay = std::time::Duration::ZERO; + + let client = client_config.init(Default::default()).expect("failed to init client"); + let quic_addr: crate::connect::Addr = Url::parse(&format!("https://localhost:{quic_port}")).unwrap().into(); + let ws_addr: crate::connect::Addr = Url::parse(&format!("http://localhost:{ws_port}")).unwrap().into(); + + // Keep this aligned with the newest default Lite version, as in tests/broadcast.rs. + let expected_version: moq_net::Version = "moq-lite-06".parse().expect("invalid version"); + + let server_handle = tokio::spawn(async move { + let request = server.accept().await.expect("no incoming connection"); + assert_eq!( + request.transport(), + crate::server::Transport::Quic, + "expected the QUIC listener", + ); + let session = request.with_publisher(&pub_origin).ok().await?; + assert_eq!(session.version(), expected_version, "server negotiated stale version"); + let _broadcast = broadcast; + let _track = track; + let _ = session.closed().await; + Ok::<_, anyhow::Error>(()) + }); + + let client = client.with_subscriber(sub_origin); + let noq = client.noq.as_ref().expect("QUIC backend"); + let quic = async { + let session = noq.connect(&client.tls, quic_addr, &client.versions).await?; + connected.send(()).expect("fallback listener alive"); + Ok::<_, crate::Error>(crate::transport::Session::new(session)) + }; + let cc = client + .race_moq_connect(&client.moq, ws_addr, quic) + .await + .expect("client connect failed"); + + assert_eq!(cc.version(), expected_version, "client negotiated stale version"); + websocket_handle.abort(); + let _ = websocket_handle.await; + + // Skip the caught-up marker; the first route event must be the announcement. + let update = loop { + match announcements.next().await.expect("origin closed") { + moq_net::announce::Event::Live => continue, + moq_net::announce::Event::Start(update) => break update, + event => panic!("expected announcement, got {event:?}"), + } + }; + assert_eq!(update.prefix.as_str(), "test"); + let broadcast = sub_consumer + .request_broadcast("test") + .await + .expect("broadcast resolves"); + let mut track = broadcast + .track("video") + .unwrap() + .subscribe(None) + .await + .expect("subscribe"); + let mut group = track.recv_group().await.expect("receive group").expect("track open"); + let frame = group.read_frame().await.expect("read frame").expect("group open"); + assert_eq!(&frame.payload[..], b"hello"); + + drop(cc); + server_handle + .await + .expect("server task panicked") + .expect("server task failed"); + } + #[cfg(all(feature = "websocket", feature = "noq"))] #[tokio::test] async fn race_transport_connect_reports_auth_when_both_refuse() { diff --git a/rs/moq-tokio/tests/broadcast.rs b/rs/moq-tokio/tests/broadcast.rs index 70dc6ab3ca6..4b286695580 100644 --- a/rs/moq-tokio/tests/broadcast.rs +++ b/rs/moq-tokio/tests/broadcast.rs @@ -372,7 +372,7 @@ async fn lite05_fetch_roundtrip(scheme: &str) { #[tokio::test] async fn broadcast_moq_lite_05_fetch_webtransport() { // Exercises the WebTransport path; lite-05 is forced via config on both ends. - // The raw-QUIC ALPN path is covered by broadcast_race_quic_wins. + // The raw-QUIC ALPN path is covered by client::tests::broadcast_race_quic_wins. lite05_fetch_roundtrip("https").await; } @@ -2354,86 +2354,6 @@ async fn broadcast_websocket_uses_newest_version() { .expect("server task failed"); } -/// Regression guard for the QUIC vs WebSocket race. With both transports -/// reachable at the same URL, QUIC must win, since it's lower-latency and -/// has direct ALPN negotiation. A WebSocket win here means QUIC silently -/// regressed (and would also tend to drag the version down to Lite02 on -/// older relays). We bind WebSocket TCP and QUIC UDP to the same port, -/// then disable the head start so the race is genuine. -#[tracing_test::traced_test] -#[tokio::test] -async fn broadcast_race_quic_wins() { - let pub_origin = moq_tokio::origin::spawn(); - let broadcast = pub_origin.create_broadcast("test").expect("failed to create broadcast"); - broadcast - .announce(Default::default()) - .expect("failed to create broadcast"); - let track = broadcast.create_track("video", None).expect("failed to create track"); - let mut group = track.append_group().expect("failed to append group"); - group - .write_frame(moq_tokio::moq_net::Timestamp::ZERO, b"hello".as_ref()) - .expect("failed to write frame"); - group.finish().expect("failed to finish group"); - - // Bind WebSocket TCP first to pick a random port, then bind QUIC UDP to - // the same port. UDP and TCP live in separate kernel namespaces, so this - // works on every supported platform. - let ws_listener = moq_tokio::websocket::Listener::bind("[::]:0".parse().unwrap()) - .await - .expect("failed to bind WebSocket listener"); - let port = ws_listener.local_addr().expect("failed to get ws addr").port(); - - let mut server_config = moq_tokio::listen::Config::default(); - server_config.bind = Some(format!("[::]:{port}").parse().unwrap()); - server_config.tls.generate = vec!["localhost".into()]; - - let mut config = moq_tokio::server::Config::default(); - config.listen = server_config; - config.websocket = Some(ws_listener); - let server = config.init().expect("failed to init server"); - let mut server = server.listen().await.expect("failed to listen"); - - let sub_origin = moq_tokio::origin::spawn(); - let mut client_config = moq_tokio::connect::Config::default(); - client_config.tls.insecure = Some(true); - // Zero head start: QUIC has to win on its own merit, not by penalising WS. - client_config.websocket.delay = Duration::ZERO; - - let client = client_config.init(Default::default()).expect("failed to init client"); - let url: url::Url = format!("https://localhost:{port}").parse().unwrap(); - - let expected_version: moq_net::Version = NEWEST_LITE.parse().expect("invalid version"); - - let server_handle = tokio::spawn(async move { - let request = server.accept().await.expect("no incoming connection"); - assert_eq!( - request.transport(), - moq_tokio::server::Transport::Quic, - "QUIC lost the race to WebSocket with both reachable", - ); - let session = request.with_publisher(&pub_origin).ok().await?; - assert_eq!(session.version(), expected_version, "server negotiated stale version"); - let _broadcast = broadcast; - let _track = track; - let _ = session.closed().await; - Ok::<_, anyhow::Error>(()) - }); - - let client = client.with_subscriber(sub_origin); - let (_client, cc) = tokio::time::timeout(TIMEOUT, connect_once(client, url)) - .await - .expect("client connect timed out") - .expect("client connect failed"); - - assert_eq!(cc.version(), Some(expected_version), "client negotiated stale version"); - - drop(cc); - server_handle - .await - .expect("server task panicked") - .expect("server task failed"); -} - /// Regression guard: a Tokio runtime's session machine must run under the span /// active at accept time (e.g. a relay's /// per-connection span), or every log line moq-net emits from inside it diff --git a/rs/moq-tokio/tests/worker.rs b/rs/moq-tokio/tests/worker.rs index 811b060d584..cdf2348d377 100644 --- a/rs/moq-tokio/tests/worker.rs +++ b/rs/moq-tokio/tests/worker.rs @@ -11,17 +11,6 @@ use moq_tokio::worker::{self, Workers}; const WORKERS: u16 = 4; -/// A UDP port nothing is bound to. -/// -/// Only for the port-lock tests, where the first group names its port. -/// Everything else binds `:0` and reads it back. -fn free_udp_port() -> u16 { - let probe = UdpSocket::bind("127.0.0.1:0").expect("bind probe"); - let port = probe.local_addr().expect("local addr").port(); - drop(probe); - port -} - /// The socket inodes this process holds bound to `addr`, of which there must be /// at least one: every UDP socket, but only a TCP listener. /// @@ -330,10 +319,9 @@ async fn an_occupied_port_is_refused() { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); - let port = free_udp_port(); - let workers = - bind_workers(listen_config(&cert, &key, port), Default::default(), config(WORKERS)).expect("bind workers"); + bind_workers(listen_config(&cert, &key, 0), Default::default(), config(WORKERS)).expect("bind workers"); + let port = workers.local_addr().port(); let err = bind_workers(listen_config(&cert, &key, port), Default::default(), config(WORKERS)) .expect_err("a second group must not join the first"); @@ -360,11 +348,10 @@ async fn the_other_wildcard_spelling_is_refused() { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); - let port = free_udp_port(); - - let mut v4 = listen_config(&cert, &key, port); - v4.bind = Some(format!("0.0.0.0:{port}").parse().unwrap()); + let mut v4 = listen_config(&cert, &key, 0); + v4.bind = Some("0.0.0.0:0".parse().unwrap()); let workers = bind_workers(v4, Default::default(), config(WORKERS)).expect("bind v4 wildcard workers"); + let port = workers.local_addr().port(); let mut v6 = listen_config(&cert, &key, port); v6.bind = Some(format!("[::]:{port}").parse().unwrap()); @@ -390,10 +377,9 @@ async fn a_shared_port_is_refused_across_addresses() { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); - let port = free_udp_port(); - let workers = - bind_workers(listen_config(&cert, &key, port), Default::default(), config(WORKERS)).expect("bind workers"); + bind_workers(listen_config(&cert, &key, 0), Default::default(), config(WORKERS)).expect("bind workers"); + let port = workers.local_addr().port(); // A distinct loopback address: no bind conflict with 127.0.0.1, only the // shared port. diff --git a/test/interop/README.md b/test/interop/README.md index 40069cef29c..dd967cc0667 100644 --- a/test/interop/README.md +++ b/test/interop/README.md @@ -132,7 +132,10 @@ Each run covers, against a real local relay: The fake device is not physical hardware, and the headless permission decision is not a person clicking a browser prompt. - **pause and resume**, **unsubscribe and rejoin**, **detach and reattach**, - **publisher stop and same-path republish**, and **late join**. + **publisher stop and same-path republish**, and **late join**. The late join + must present the newest published GOP or a newer one. Its lower bound is the + encoded keyframe timestamp sampled before the existing viewer closes, since + painting the canvas does not mean capture and encoding have finished. - **resources return to baseline** - the page wraps `WebTransport`, `WebSocket`, `AudioContext`, and `Worker` to count live instances, so a detach that leaks a session is visible rather than merely invisible. diff --git a/test/interop/clients/js/harness.ts b/test/interop/clients/js/harness.ts index bd59af1602b..9b790205377 100644 --- a/test/interop/clients/js/harness.ts +++ b/test/interop/clients/js/harness.ts @@ -256,15 +256,18 @@ export async function readFixtureState(page: Page): Promise { } /** Invoke one of the page's {@link InteropControl} commands. */ -export async function command(page: Page, name: keyof InteropControl): Promise { - await page.evaluate( +export async function command( + page: Page, + name: K, +): Promise>> { + return (await page.evaluate( ([key, fn]) => { - const control = (window as unknown as Record void> | undefined>)[key]; + const control = (window as unknown as Record unknown> | undefined>)[key]; if (!control?.[fn]) throw new Error(`the page exposes no ${fn} command`); - control[fn](); + return control[fn](); }, [CONTROL, name] as const, - ); + )) as Awaited>; } /** Read the page's live resource counts, which outlive the player element. */ diff --git a/test/interop/clients/js/media.ts b/test/interop/clients/js/media.ts index f4e9577d3a0..d73259a50ef 100644 --- a/test/interop/clients/js/media.ts +++ b/test/interop/clients/js/media.ts @@ -47,7 +47,7 @@ import { import { type CaptureState, FAULTS, - KEYFRAME_INTERVAL_MS, + lateJoinStartsLive, leakedPlayerStarted, SAMPLE_MS, SAMPLE_RATE, @@ -115,9 +115,6 @@ const MIN_RATE = 0.5; */ const MAX_SKEW_STEPS = 1; -/** The first decodable frame may start at the current GOP's keyframe, but never in older history. */ -const MAX_LATE_JOIN_LAG_FRAMES = Math.ceil((Pattern.FPS * KEYFRAME_INTERVAL_MS) / 1000); - const percentile = (values: number[], p: number) => { if (values.length === 0) return Number.NaN; const sorted = [...values].sort((a, b) => a - b); @@ -660,8 +657,8 @@ try { // at the live edge rather than replay what it missed. if (wants("late-join")) { console.error("=== late join ==="); + const live = await command(publisher, "liveGop"); await player.close(); - const live = await readFixtureState(publisher); [player, playerErrors] = await subscriber(broadcast, "latecomer"); await gesture(player); const joined = await waitForState(player, playerErrors, { @@ -670,17 +667,16 @@ try { description: "the latecomer to present the fixture", predicate: (state) => state.frameId !== undefined && state.audioContext === "running", }); - // The fixture sample names the frame painted immediately before the page opens. The first - // decodable frame can be the keyframe at the start of the current GOP, so require it to be - // within that GOP rather than requiring an impossible zero-frame capture/encode delay. - const lag = live.frameId - (joined.frameId ?? 0); + // requestFrame() is asynchronous, and capture timestamps decide keyframes. The painted + // counter can therefore be over 15 ticks ahead of a still-current encoded GOP under load. + // Compare against its actual published keyframe, sampled while the old viewer held demand. check( - lag <= MAX_LATE_JOIN_LAG_FRAMES, + lateJoinStartsLive(live, joined.videoTimestamp), "late join starts live", () => - `joined at frame ${joined.frameId}, ${lag} frames behind the ${live.frameId} already published when it opened (one GOP is ${MAX_LATE_JOIN_LAG_FRAMES})`, + `joined at frame ${joined.frameId}, timestamp ${joined.videoTimestamp}ms before the current GOP's ${live.timestamp}ms keyframe`, ); - console.error(` joined at frame ${joined.frameId}, live edge was ${live.frameId}`); + console.error(` joined at frame ${joined.frameId}, timestamp ${joined.videoTimestamp}ms, current GOP began at ${live.timestamp}ms`); assertMedia(await collect(player, playerErrors, WINDOW_MS), "late join"); } diff --git a/test/interop/clients/js/src/contract.test.ts b/test/interop/clients/js/src/contract.test.ts index b36189ed585..4afa6e19a6d 100644 --- a/test/interop/clients/js/src/contract.test.ts +++ b/test/interop/clients/js/src/contract.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; -import { leakedPlayerStarted, type Resources } from "./contract"; +import * as Moq from "@moq/net"; +import { lateJoinStartsLive, leakedPlayerStarted, readLiveGop, type Resources } from "./contract"; const playing: Resources = { transports: 1, sockets: 0, audioContexts: 1, workers: 0 }; @@ -17,3 +18,37 @@ test("a leaked player is visible when it reuses a pooled websocket fallback", () test("unchanged counts are not a leak start", () => { expect(leakedPlayerStarted(playing, playing)).toBe(false); }); + + +test("late join uses the published GOP when painting is ahead of capture", async () => { + const broadcast = new Moq.Broadcast.Producer(); + const track = broadcast.createTrack("video"); + try { + const old = track.appendGroup(); + old.writeFrame({ payload: new Uint8Array([1]), timestamp: Moq.Time.Timestamp.fromMillis(3000) }); + old.close(); + const current = track.appendGroup(); + current.writeFrame({ payload: new Uint8Array([2]), timestamp: Moq.Time.Timestamp.fromMillis(3700) }); + current.writeFrame({ payload: new Uint8Array([3]), timestamp: Moq.Time.Timestamp.fromMillis(4199) }); + + // Painted counter 127 can precede capture while GOP 111 remains current. The old + // 127 - 111 <= 15 check rejects a valid join; an earlier published GOP must fail. + const viewer = track.subscribe(); + const gop = await readLiveGop(broadcast.track("video")); + expect(gop.timestamp).toBe(3700); + expect(lateJoinStartsLive(gop, 3700)).toBe(true); + expect(lateJoinStartsLive(gop, 4199)).toBe(true); + expect(lateJoinStartsLive(gop, 3000)).toBe(false); + expect(lateJoinStartsLive(gop, undefined)).toBe(false); + expect(track.demand().used.peek()).toBe(true); + const viewed = await viewer.recvGroup(); + expect((await viewed?.readFrame())?.payload).toEqual(new Uint8Array([2])); + expect((await viewed?.readFrame())?.payload).toEqual(new Uint8Array([3])); + viewed?.close(); + viewer.close(); + await track.demand().unused(); + expect(track.demand().used.peek()).toBe(false); + } finally { + broadcast.close(); + } +}); diff --git a/test/interop/clients/js/src/contract.ts b/test/interop/clients/js/src/contract.ts index d9c0f2eafa0..43b0a1ee4fa 100644 --- a/test/interop/clients/js/src/contract.ts +++ b/test/interop/clients/js/src/contract.ts @@ -8,6 +8,8 @@ * @module */ +import type * as Moq from "@moq/net"; + // ── the deterministic publisher ───────────────────────────────────────────── /** A deliberate defect, used to prove an assertion can fail. */ @@ -43,6 +45,35 @@ export type FixtureState = { encodedFrames: number; }; +/** The newest published video's GOP, sampled independently of canvas capture and encoding. */ +export type LiveGop = { + /** The timestamp of its keyframe, in milliseconds on the publisher's media clock. */ + timestamp: number; +}; + +/** Read the newest published GOP without retaining a subscription or changing its frames. */ +export async function readLiveGop(track: Moq.Track.Consumer): Promise { + const subscriber = track.subscribe(); + try { + const group = await subscriber.recvGroup(); + if (!group) throw new Error("the fixture video has no published GOP"); + try { + const frame = await group.readFrame(); + if (!frame) throw new Error("the fixture GOP has no keyframe"); + return { timestamp: frame.timestamp.asMillis() }; + } finally { + group.close(); + } + } finally { + subscriber.close(); + } +} + +/** True when the presented frame belongs to the sampled GOP or a newer one. */ +export function lateJoinStartsLive(gop: LiveGop, timestamp: number | undefined): boolean { + return timestamp !== undefined && timestamp >= gop.timestamp; +} + /** The camera publisher state mirrored onto its element for Playwright. */ export type CaptureState = { videoError?: string; @@ -170,6 +201,8 @@ export type CloseState = * owns them rather than the driver reaching in. */ export type InteropControl = { + /** Read the current video GOP while an existing viewer is still pulling media. */ + liveGop(): Promise; /** Stop the fixture publisher, releasing its session. */ stop(): void; /** Start (or restart) the fixture publisher on the same broadcast path. */ diff --git a/test/interop/clients/js/src/fixture.ts b/test/interop/clients/js/src/fixture.ts index 17f6faef559..a3d3ff1a789 100644 --- a/test/interop/clients/js/src/fixture.ts +++ b/test/interop/clients/js/src/fixture.ts @@ -17,7 +17,7 @@ import { Time } from "@moq/net"; import * as Publish from "@moq/publish"; import { Effect, Signal } from "@moq/signals"; import type { Fault, FixtureState } from "./contract"; -import { KEYFRAME_INTERVAL_MS, OFFSET_STEPS, SAMPLE_RATE } from "./contract"; +import { KEYFRAME_INTERVAL_MS, OFFSET_STEPS, readLiveGop, SAMPLE_RATE } from "./contract"; import * as Pattern from "./pattern"; /** Cap the encoder rather than letting it track a bandwidth estimate, so runs are comparable. */ @@ -47,6 +47,7 @@ export class Fixture { readonly host: HTMLElement; readonly #signals = new Effect(); + readonly #broadcast: Publish.Broadcast; readonly #audio: AudioContext; readonly #frameId = new Signal(-1); readonly #audioState = new Signal("suspended"); @@ -95,6 +96,8 @@ export class Fixture { }); this.#signals.cleanup(() => broadcast.close()); + this.#broadcast = broadcast; + const video = new Publish.Video.Encoder("video", { broadcast, capture, @@ -183,8 +186,8 @@ export class Fixture { this.#signals.interval(schedule, (SCHEDULE_AHEAD * 1000) / 4); } - // Paint and emit one frame per pattern tick. The counter comes from the audio clock rather than - // the timer, so a late or coalesced tick skips a frame instead of drifting the two apart. + // Paint and request capture per pattern tick. Capture and encoding can finish later. The counter + // comes from the audio clock, so a coalesced tick skips a frame instead of drifting the two apart. #runPicture(ctx: CanvasRenderingContext2D, track: CanvasSource, start: number, fault: Fault): void { let painted = -1; @@ -202,7 +205,7 @@ export class Fixture { }; // Twice the frame rate: a tick that lands between frames is a no-op, and one that lands late - // still emits the frame the clock is on. + // still requests capture of the frame the clock is on. this.#timer = self.setInterval(tick, 1000 / Pattern.FPS / 2); this.#signals.cleanup(() => { if (this.#timer !== undefined) self.clearInterval(this.#timer); @@ -210,6 +213,13 @@ export class Fixture { }); } + /** Sample the current published keyframe before the viewer closes its subscription. */ + async liveGop() { + const broadcast = this.#broadcast.net.peek(); + if (!broadcast) throw new Error("the fixture is not publishing"); + return readLiveGop(broadcast.track("video")); + } + /** Stop publishing and release the capture, audio graph, and session. */ close(): void { this.#signals.close(); diff --git a/test/interop/clients/js/src/setup.ts b/test/interop/clients/js/src/setup.ts index 09928846714..389e0850de2 100644 --- a/test/interop/clients/js/src/setup.ts +++ b/test/interop/clients/js/src/setup.ts @@ -57,6 +57,10 @@ if (role === "publish") { // The driver stops and restarts the publisher in place to exercise a same-path republish, which // has to reuse this page so the audio context keeps its user activation. publish({ + liveGop: () => { + if (!fixture) throw new Error("the fixture is stopped"); + return fixture.liveGop(); + }, stop: () => { fixture?.close(); fixture = undefined; diff --git a/test/justfile b/test/justfile index a67b2ffee07..3c7437d4a35 100644 --- a/test/justfile +++ b/test/justfile @@ -24,7 +24,7 @@ harness: ./lib/harness.test.sh cd .. && bun install --frozen-lockfile cd interop/clients/js && bunx playwright install chromium - cd interop/clients/js && bun test ./harness.browser.ts + cd interop/clients/js && bun test ./harness.browser.ts ./src/contract.test.ts # Cross-language media interop test, built from this checkout. Stands up a # relay and runs the publisher x subscriber matrix. Default: rust only (fast