From 0768fd801512702a6958185b4726fbdb5c84e139 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 08:15:13 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m1/mock-clock-tests/js-net.md Quest-Claim: d480770a82351cd1 From f64e86b67e5e44c80fa3b2694c96185d03b8f850 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 08:56:48 -0800 Subject: [PATCH 2/3] test(net): js/net tests run on a mocked clock Negative proofs, settle sleeps, and elapsed-time assertions across js/net now run on a Manual clock or await the event they mean, and every bare hostTime() opt-out is gone, so the bun test guard covers them. - mock.ts gains manual(), settlesWithin(), and driveUntil(), shared by every converted file; the helpers that resolved undefined on a timeout (nextUni, nextStream, closeCode) now await the event or advance the mocked clock past their window. - Tests that wait out a production timer (the 1s datagram grace, SETUP's close grace, reload backoff, PUBLISH_NAMESPACE retry) drive the clock instead of sleeping on the host. Co-Authored-By: Claude Opus 5.5 --- js/net/src/auth.test.ts | 14 +- js/net/src/connection/connect.test.ts | 18 ++- js/net/src/connection/reload.test.ts | 62 +++++---- js/net/src/ietf/datagram.test.ts | 26 ++-- js/net/src/ietf/goaway.test.ts | 30 ++--- js/net/src/ietf/join.test.ts | 95 ++++++-------- js/net/src/ietf/malformed.test.ts | 53 ++++---- js/net/src/ietf/publisher.test.ts | 165 +++++------------------- js/net/src/ietf/request_stream.test.ts | 12 +- js/net/src/ietf/subscriber.test.ts | 94 +++----------- js/net/src/ietf/tail.test.ts | 21 +-- js/net/src/integration.test.ts | 105 ++++++--------- js/net/src/lite/connection.test.ts | 19 +-- js/net/src/lite/datagram-tracks.test.ts | 42 ++++-- js/net/src/lite/publisher.test.ts | 159 +++++++++-------------- js/net/src/lite/tail.test.ts | 44 +++---- js/net/src/lite/track_stream.test.ts | 61 ++++----- js/net/src/mock.ts | 49 +++++++ js/net/src/tail.test.ts | 15 ++- js/net/src/track.test.ts | 8 +- quest/m1/mock-clock-tests/README.md | 1 - quest/m1/mock-clock-tests/js-net.md | 35 ----- 22 files changed, 444 insertions(+), 684 deletions(-) delete mode 100644 quest/m1/mock-clock-tests/js-net.md diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index c4705a40575..5b6c885fc95 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -1,6 +1,5 @@ import { describe, expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import type { Getter } from "@moq/signals"; import { Duplicate, type Grant, Handle, type Issued, type Request, type Requests, Unsupported } from "./auth.ts"; import { accept as acceptSession, connect as connectSession, type Established } from "./connection/index.ts"; @@ -11,7 +10,7 @@ import * as IetfMessage from "./ietf/message.ts"; import { AuthMessage as LiteAuthMessage, LiteAuthWire } from "./lite/auth.ts"; import * as Lite from "./lite/index.ts"; import * as LiteMessage from "./lite/message.ts"; -import { createMockTransportPair, type MockTransport } from "./mock.ts"; +import { createMockTransportPair, type MockTransport, manual, settlesWithin } from "./mock.ts"; import { Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; import { Stream, Writer } from "./stream.ts"; @@ -354,7 +353,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { }); test("a revoked grant withdraws its broadcasts without closing the session", async () => { - hostTime(); + using clock = manual(); const origin = new OriginProducer(); const { client, server, transport } = await connect({ publish: origin, protocol }); const requests = server.auth.requests(); @@ -388,12 +387,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { const third = await nextRoute(announced); expect(third?.kind).toBe("start"); - let closed = false; - void transport.closed.then(() => { - closed = true; - }); - await sleep(Nano.fromMilli(Milli(10))); - expect(closed).toBe(false); + expect(await settlesWithin(transport.closed, clock, Milli(10))).toBe(false); announced.close(); client.abort(); diff --git a/js/net/src/connection/connect.test.ts b/js/net/src/connection/connect.test.ts index 9cb012370ed..0f516a9ed4f 100644 --- a/js/net/src/connection/connect.test.ts +++ b/js/net/src/connection/connect.test.ts @@ -6,7 +6,7 @@ import { ConnectTimeout, SessionCode, SessionError } from "../error.ts"; import * as Ietf from "../ietf/index.ts"; import { ClientSetup, ServerSetup } from "../lite/compat.ts"; import { ALPN, ALPN_05, ALPN_06, ALPN_07_WIP, Version as Lite } from "../lite/version.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, driveUntil, manual } from "../mock.ts"; import { Stream } from "../stream.ts"; import { accept } from "./accept.ts"; import { type ConnectProps, connect as connectSession } from "./connect.ts"; @@ -555,14 +555,18 @@ for (const protocol of ["", undefined]) { } test("SETUP refuses a version the client did not name", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(""); const restore = stubWebTransport(pair.client); try { const server = accept({ url, transport: pair.server, version: Lite.DRAFT_05 }).catch(() => undefined); - await expect( - connect(url, { versions: ["moq-lite-07-wip", "moq-lite-06"], websocket: { enabled: false } }), - ).rejects.toThrow("unsupported server version: 0xff0dad05"); + const connecting = connect(url, { + versions: ["moq-lite-07-wip", "moq-lite-06"], + websocket: { enabled: false }, + }); + // The refusal waits out the grace a peer's close code gets. + await driveUntil(clock, connecting); + await expect(connecting).rejects.toThrow("unsupported server version: 0xff0dad05"); (await server)?.abort(); } finally { restore(); @@ -585,7 +589,7 @@ test("a peer without an ALPN is refused when no named version negotiates in SETU const IETF_VERSIONS = Object.values(Ietf.Version).map((v) => [Ietf.versionName(v), v] as const); test.each(IETF_VERSIONS)("a client refuses %s selected in the moql SETUP", async (_, version) => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(""); const restore = stubWebTransport(pair.client); try { @@ -596,6 +600,8 @@ test.each(IETF_VERSIONS)("a client refuses %s selected in the moql SETUP", async if (!stream) throw new Error("no SETUP stream"); await ClientSetup.decode(stream.reader); await new ServerSetup(version).encode(stream.writer); + // The refusal waits out the grace a peer's close code gets. + await driveUntil(clock, connecting); await expect(connecting).rejects.toThrow(`unsupported server version: 0x${version.toString(16)}`); } finally { restore(); diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index d9ba740c8cf..aa71649dc19 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -1,6 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, sleep, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; import { Effect, Signal } from "@moq/signals"; import * as Announce from "../announced.ts"; import { Viewers } from "../bandwidth.ts"; @@ -9,7 +8,7 @@ import { ConnectTimeout, SessionCode, SessionError, StreamCode, toTransport } fr import { WireRoute } from "../hop.ts"; import { ALPN as IetfALPN } from "../ietf/version.ts"; import * as Lite from "../lite/index.ts"; -import { createMockTransportPair, type MockTransport, textFrame } from "../mock.ts"; +import { createMockTransportPair, driveUntil, type MockTransport, manual, textFrame } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Stream } from "../stream.ts"; @@ -129,7 +128,7 @@ test("closing mid-connect aborts the pending attempt", async () => { }); test("a peer that severs immediately keeps escalating the backoff", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/"); let attempts = 0; @@ -155,7 +154,7 @@ test("a peer that severs immediately keeps escalating the backoff", async () => delay: { initial: Milli(1000), multiplier: 2, max: Milli(1000), timeout: Milli(1) }, }); try { - await waitUntil(() => reload.error.peek() !== undefined); + await driveUntil(clock, () => reload.error.peek() !== undefined); expect(reload.closed.peek()).toBeUndefined(); // Giving up this URL does not dispose the loop: a disable/re-enable starts another sequence. @@ -175,7 +174,7 @@ test("a peer that severs immediately keeps escalating the backoff", async () => }); test("an explicitly undefined delay field falls back to its default", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/"); let dials = 0; @@ -197,8 +196,7 @@ test("an explicitly undefined delay field falls back to its default", async () = delay: { initial: undefined, multiplier: undefined, max: undefined, timeout: Milli(0) }, }); try { - await waitUntil(() => dials > 0); - await sleep(Nano.fromMilli(Milli(100))); + await clock.advance(Nano.fromMilli(Milli(100))); // The default initial delay is 1000ms, so the first retry is still pending. expect(dials).toBe(1); } finally { @@ -218,7 +216,7 @@ async function waitUntil(pred: () => boolean): Promise { } test("a follower follows the reconnect on the same handle", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/"); @@ -248,12 +246,12 @@ test("a follower follows the reconnect on the same handle", async () => { const watched = clientOrigin.follow(Path.from("late")); try { - await waitUntil(() => watched.active.peek() !== undefined); + await driveUntil(clock, () => watched.active.peek() !== undefined); const first = watched.active.peek(); // The session dies; the same request follows the next session's announcement. sessions[0]?.abort(); - await waitUntil(() => watched.active.peek() !== undefined && watched.active.peek() !== first); + await driveUntil(clock, () => watched.active.peek() !== undefined && watched.active.peek() !== first); expect(watched.closed.peek()).toBeUndefined(); } finally { watched.close(); @@ -438,7 +436,7 @@ function refusing(refused: string, release: Promise) { } test("a refused credential replaced since its dial redials with the new one", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const { promise: release, resolve } = Promise.withResolvers(); const { dialed, stub } = refusing("old", release); @@ -453,12 +451,12 @@ test("a refused credential replaced since its dial redials with the new one", as delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, }); try { - await waitUntil(() => reload.established.peek() !== undefined); + await driveUntil(clock, () => reload.established.peek() !== undefined); tokens.set(["new"]); resolve(); - await waitUntil(() => dialed.includes("new")); + await driveUntil(clock, () => dialed.includes("new")); expect(dialed).toEqual(["old", "new"]); - await waitUntil(() => reload.established.peek() !== undefined); + await driveUntil(clock, () => reload.established.peek() !== undefined); expect(reload.error.peek()).toBeUndefined(); } finally { reload.close(); @@ -467,7 +465,7 @@ test("a refused credential replaced since its dial redials with the new one", as }); test("new tokens redial a URL that stopped on refusing the old ones", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const { dialed, stub } = refusing("old", Promise.resolve()); globalThis.WebTransport = stub; @@ -481,11 +479,11 @@ test("new tokens redial a URL that stopped on refusing the old ones", async () = delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, }); try { - await waitUntil(() => reload.error.peek() !== undefined); + await driveUntil(clock, () => reload.error.peek() !== undefined); expect(dialed).toEqual(["old"]); tokens.set(["new"]); - await waitUntil(() => dialed.includes("new")); - await waitUntil(() => reload.established.peek() !== undefined); + await driveUntil(clock, () => dialed.includes("new")); + await driveUntil(clock, () => reload.established.peek() !== undefined); expect(reload.error.peek()).toBeUndefined(); } finally { reload.close(); @@ -546,7 +544,7 @@ test("an unauthorized session close during setup stops retrying", async () => { // disjoint. Reading a stream reset off the session table would call every SETUP-stream reset // an auth rejection and suppress reconnect for the life of the page. test("a setup stream reset is not mistaken for an unauthorized session", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/"); let attempts = 0; @@ -576,7 +574,7 @@ test("a setup stream reset is not mistaken for an unauthorized session", async ( }); try { - await waitUntil(() => attempts >= 2); + await driveUntil(clock, () => attempts >= 2); } finally { reload.close(); globalThis.WebTransport = original; @@ -584,7 +582,7 @@ test("a setup stream reset is not mistaken for an unauthorized session", async ( }); test("origins span reconnects: local re-announces, remote re-populates", async () => { - hostTime(); + using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/origins"); @@ -625,17 +623,17 @@ test("origins span reconnects: local re-announces, remote re-populates", async ( try { // First session: the server's broadcast lands in the client origin, and the client's // publish lands in the server's. - await waitUntil(() => wireOf(reader).routes(Path.from("remote"))); - await waitUntil(() => (servers[0] ? wireOf(servers[0].saw).routes(Path.from("mine")) : false)); + await driveUntil(clock, () => wireOf(reader).routes(Path.from("remote"))); + await driveUntil(clock, () => (servers[0] ? wireOf(servers[0].saw).routes(Path.from("mine")) : false)); // Kill the session: the remote entry retracts, the local publish stays put. servers[0]?.session.abort(); - await waitUntil(() => !wireOf(reader).routes(Path.from("remote"))); + await driveUntil(clock, () => !wireOf(reader).routes(Path.from("remote"))); // The reconnect re-announces the (untouched) publish and re-populates the table. - await waitUntil(() => servers.length > 1); - await waitUntil(() => wireOf(reader).routes(Path.from("remote"))); - await waitUntil(() => (servers[1] ? wireOf(servers[1].saw).routes(Path.from("mine")) : false)); + await driveUntil(clock, () => servers.length > 1); + await driveUntil(clock, () => wireOf(reader).routes(Path.from("remote"))); + await driveUntil(clock, () => (servers[1] ? wireOf(servers[1].saw).routes(Path.from("mine")) : false)); } finally { watching.close(); for (const server of servers) server.watching.close(); @@ -1072,7 +1070,7 @@ test("announced accepts a non-prefix scope before any session exists", () => { * a reconnect takes it back until the next session's set lands. */ test("a watcher syncs with the server's initial set, and again after a reconnect", async () => { - hostTime(); + using clock = manual(); // Through the consume origin, and through the handle's own stream without one. for (const [alpn, viaOrigin] of [ [Lite.ALPN_06, true], @@ -1116,12 +1114,12 @@ test("a watcher syncs with the server's initial set, and again after a reconnect try { // Nothing is connected yet, which is not the same as nothing being announced. expect(watching.synced.peek()).toBe(false); - await waitUntil(() => watching.synced.peek()); + await driveUntil(clock, () => watching.synced.peek()); expect([...seen].sort()).toEqual(["a", "b"]); sessions[0]?.abort(); - await waitUntil(() => !watching.synced.peek()); - await waitUntil(() => sessions.length > 1 && watching.synced.peek()); + await driveUntil(clock, () => !watching.synced.peek()); + await driveUntil(clock, () => sessions.length > 1 && watching.synced.peek()); expect([...seen].sort()).toEqual(["a", "b"]); } finally { watching.close(); diff --git a/js/net/src/ietf/datagram.test.ts b/js/net/src/ietf/datagram.test.ts index 2e17f51f4c1..951390840ea 100644 --- a/js/net/src/ietf/datagram.test.ts +++ b/js/net/src/ietf/datagram.test.ts @@ -1,9 +1,8 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli, Nano, sleep, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Milli, yieldNow } from "@moq/clock"; import { accept, connect } from "../connection/index.ts"; import { ProtocolViolation, SessionCode } from "../error.ts"; -import { createMockTransportPair, type MockTransport } from "../mock.ts"; +import { createMockTransportPair, type MockTransport, manual, settlesWithin } from "../mock.ts"; import { Producer as Origin } from "../origin.ts"; import * as Path from "../path.ts"; import { encodeVarint, Stream } from "../stream.ts"; @@ -106,7 +105,7 @@ test("an undefined object status closes the session", async () => { }); test("a defined object status does not close the session", async () => { - hostTime(); + using clock = manual(); const { pair, connection, version, writable } = await session(); try { const bytes = new ObjectDatagram({ @@ -117,16 +116,14 @@ test("a defined object status does not close the session", async () => { }).encode(version); const writer = writable.getWriter(); await writer.write(bytes); - const open = Symbol("open"); - const result = await Promise.race([pair.server.closed, sleep(Nano.fromMilli(Milli(50))).then(() => open)]); - expect(result).toBe(open); + expect(await settlesWithin(pair.server.closed, clock, Milli(50))).toBe(false); } finally { connection.abort(); } }); test("a datagram track round-trips over moq-transport", async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const path = Path.from("live"); const publication = source.route(path, { hidden: true }); @@ -166,7 +163,8 @@ test("a datagram track round-trips over moq-transport", async () => { expect(received?.timestamp?.asMillis()).toBe(9); expect(received?.payload).toEqual(new Uint8Array([7])); datagrams.finish(); - expect(await reader.recv()).toBeUndefined(); + // The end waits out the grace a late datagram gets. + expect(await clock.drive(reader.recv())).toBeUndefined(); } finally { reader.close(); await peers[0].close(); @@ -291,7 +289,7 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { [100, true], ] as const) { test(`${alpn}: a datagram sent right behind its answer arrives (answer ${lag} microtasks late${finish ? ", then the end" : ""})`, async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const publication = source.route(Path.from("live"), { hidden: true }); const datagrams = publication.broadcast.createDatagrams("audio"); @@ -317,7 +315,8 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { await reader.info(); if (!finish) datagrams.append(undefined, Uint8Array.of(2)); expect((await reader.recv())?.payload).toEqual(Uint8Array.of(1)); - if (finish) expect(await reader.recv()).toBeUndefined(); + // The end waits out the grace a late datagram gets. + if (finish) expect(await clock.drive(reader.recv())).toBeUndefined(); else expect((await reader.recv())?.payload).toEqual(Uint8Array.of(2)); } finally { reader.close(); @@ -332,7 +331,7 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { test(`${alpn}: a datagram burst reaches its reader before the end across a receive yield`, async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const publication = source.route(Path.from("live"), { hidden: true }); const datagrams = publication.broadcast.createDatagrams("audio"); @@ -356,7 +355,8 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { for (let i = 0; i < 64; i++) datagrams.append(undefined, Uint8Array.of(i)); datagrams.finish(); for (let i = 0; i < 64; i++) expect((await reader.recv())?.payload).toEqual(Uint8Array.of(i)); - expect(await reader.recv()).toBeUndefined(); + // The end waits out the grace a late datagram gets. + expect(await clock.drive(reader.recv())).toBeUndefined(); } finally { budget.mockRestore(); reader.close(); diff --git a/js/net/src/ietf/goaway.test.ts b/js/net/src/ietf/goaway.test.ts index 086f8550f6f..d74804f3964 100644 --- a/js/net/src/ietf/goaway.test.ts +++ b/js/net/src/ietf/goaway.test.ts @@ -1,8 +1,7 @@ import { expect, test } from "bun:test"; -import { Milli, Nano, sleep } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Milli } from "@moq/clock"; import { SessionCode, StreamCode, StreamError } from "../error.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Stream } from "../stream.ts"; @@ -22,7 +21,7 @@ for (const [version, alpn, requestId] of [ [Version.DRAFT_22, ALPN.DRAFT_22, undefined], ] as const) { test(`a ${alpn} GOAWAY surfaces its URI and deadline without closing the session`, async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(alpn); const control = await Stream.open(pair.client, { version }); const peer = await Stream.accept(pair.server, version); @@ -36,11 +35,6 @@ for (const [version, alpn, requestId] of [ client: true, }); - let closed = false; - void connection.closed.then(() => { - closed = true; - }); - try { await peer.writer.u53(GoAway.id); await new GoAway({ newSessionUri: "", timeout: 5000n, requestId }).encode(peer.writer, version); @@ -49,8 +43,7 @@ for (const [version, alpn, requestId] of [ expect(drain.uri).toBe(""); expect(drain.timeout).toBe(Milli(5000)); - await sleep(Nano.fromMilli(Milli(20))); - expect(closed).toBe(false); + expect(await settlesWithin(connection.closed, clock, Milli(20))).toBe(false); } finally { connection.abort(); } @@ -58,7 +51,7 @@ for (const [version, alpn, requestId] of [ } test("a server rejects a client GOAWAY that names a redirect", async () => { - hostTime(); + using clock = manual(); const version = Version.DRAFT_18; const pair = createMockTransportPair(ALPN.DRAFT_18); const control = await Stream.open(pair.client, { version }); @@ -73,16 +66,10 @@ test("a server rejects a client GOAWAY that names a redirect", async () => { client: false, }); - let closed = false; - void connection.closed.then(() => { - closed = true; - }); - try { await peer.writer.u53(GoAway.id); await new GoAway({ newSessionUri: "https://other.example/", timeout: 0n }).encode(peer.writer, version); - await sleep(Nano.fromMilli(Milli(50))); - expect(closed).toBe(true); + expect(await settlesWithin(connection.closed, clock, Milli(50))).toBe(true); } finally { connection.abort(); } @@ -264,7 +251,7 @@ for (const [version, alpn] of [ for (const end of ["FIN", "reset"] as const) { test(`${alpn} an idle advertisement whose answer ends by ${end} is offered again`, async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(alpn); const control = await Stream.open(pair.server, { version }); await Stream.accept(pair.client, version); @@ -292,7 +279,8 @@ for (const [version, alpn] of [ await new RequestOk().encode(first.writer, version); if (end === "reset") first.writer.reset(new StreamError(StreamCode.Cancel)); else first.writer.close(); - await offered(); + // The offer comes back after the retry backoff. + await clock.drive(offered()); } finally { connection.abort(); origin.close(); diff --git a/js/net/src/ietf/join.test.ts b/js/net/src/ietf/join.test.ts index 78fe947bf94..6692127cc15 100644 --- a/js/net/src/ietf/join.test.ts +++ b/js/net/src/ietf/join.test.ts @@ -1,11 +1,10 @@ import { expect, jest, onTestFinished, test } from "bun:test"; -import { Elapsed, Instant, Manual, Milli, Nano, now, timeout } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Instant, Manual, Milli, Nano, now } from "@moq/clock"; import * as Connection from "../connection/index.ts"; import { StreamCode } from "../error.ts"; import { hooks } from "../internal.ts"; import { GRACE } from "../ledger.ts"; -import { createMockTransportPair, textFrame } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin, textFrame } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Reader, Stream, Writer } from "../stream.ts"; @@ -38,26 +37,29 @@ const GROUP = 3n; const text = (s: string) => new TextEncoder().encode(s); const untext = (b: Uint8Array | undefined) => (b ? new TextDecoder().decode(b) : undefined); -/** Accept the next bidi stream the subscriber opens, or undefined if none comes soon. */ -async function nextStream( - transport: WebTransport, - wait = 200, - version: IetfVersion = VERSION, -): Promise { +/** Accept the next bidi stream the subscriber opens. */ +async function nextStream(transport: WebTransport, version: IetfVersion = VERSION): Promise { const reader = transport.incomingBidirectionalStreams.getReader() as ReadableStreamDefaultReader; try { - const next = await timeout(Nano.fromMilli(Milli(wait)), reader.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - if (!next || next.done) return undefined; + const next = await reader.read(); + if (next.done) throw new Error("the session ended before the subscriber opened a stream"); return new Stream({ readable: next.value.readable, writable: next.value.writable, version }); } finally { reader.releaseLock(); } } +/** Whether the subscriber opens a bidi stream before `clock` advances `duration`. */ +async function opens(transport: WebTransport, clock: Manual, duration = Milli(200)): Promise { + const reader = transport.incomingBidirectionalStreams.getReader(); + try { + return await settlesWithin(reader.read(), clock, duration); + } finally { + reader.releaseLock(); + } +} + /** A subscriber with one track, and the SUBSCRIBE it sent, still unanswered. */ async function subscribed(version: IetfVersion = VERSION, subscription: Partial = {}) { const pair = createMockTransportPair(ALPNS[version]); @@ -72,8 +74,7 @@ async function subscribed(version: IetfVersion = VERSION, subscription: Partial< session.close(); }); - const peer = await nextStream(pair.client, 200, version); - if (!peer) throw new Error("the subscriber never subscribed"); + const peer = await nextStream(pair.client, version); expect(await peer.reader.u53()).toBe(Subscribe.id); const subscribe = await Subscribe.decode(peer.reader, version); const answer = async (largest: MessageLocation | null) => { @@ -95,16 +96,12 @@ async function join( await subscription.answer(largest); const fetching = await nextStream(subscription.client); - let fetch: Fetch | undefined; - if (fetching) { - expect(await fetching.reader.u53()).toBe(Fetch.id); - fetch = await Fetch.decode(fetching.reader, VERSION); - } + expect(await fetching.reader.u53()).toBe(Fetch.id); + const fetch = await Fetch.decode(fetching.reader, VERSION); return { ...subscription, fetching, fetch }; } -async function accept(fetching: Stream | undefined) { - if (!fetching) throw new Error("no joining FETCH"); +async function accept(fetching: Stream) { await fetching.writer.u53(FetchOk.id); await new FetchOk({ endOfTrack: false, endLocation: { group: GROUP, object: 2n } }).encode( fetching.writer, @@ -112,8 +109,7 @@ async function accept(fetching: Stream | undefined) { ); } -async function refuse(fetching: Stream | undefined) { - if (!fetching) throw new Error("no joining FETCH"); +async function refuse(fetching: Stream) { await fetching.writer.u53(RequestError.id); await new RequestError({ errorCode: 0x4, reasonPhrase: "not here" }).encode(fetching.writer, VERSION); } @@ -181,20 +177,20 @@ test("a draft-18 join subscribes at Largest Object and fetches Largest's group", const { subscribe, fetch } = await join(); expect(subscribe.filter).toEqual({ kind: "nextObject" }); expect(subscribe.fill).toBeUndefined(); - expect(fetch?.type).toEqual({ kind: "relativeJoining", subscription: subscribe.requestId, offset: 0n }); - expect(fetch?.groupOrder).toBe("ascending"); - expect(fetch?.requestId).not.toBe(subscribe.requestId); + expect(fetch.type).toEqual({ kind: "relativeJoining", subscription: subscribe.requestId, offset: 0n }); + expect(fetch.groupOrder).toBe("ascending"); + expect(fetch.requestId).not.toBe(subscribe.requestId); }); test("an empty track sends no joining FETCH", async () => { - hostTime(); - const { fetching } = await join(null); - expect(fetching).toBeUndefined(); + using clock = manual(); + const { answer, client } = await subscribed(); + await answer(null); + expect(await opens(client, clock)).toBe(false); }); test("a head that lands before its tail is continued by it", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -207,7 +203,6 @@ test("a head that lands before its tail is continued by it", async () => { test("a tail that lands before its head waits for it", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); const tail = subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); await accept(fetching); @@ -220,7 +215,6 @@ test("a tail that lands before its head waits for it", async () => { test("a catalog written once is readable from the head alone", async () => { const { subscriber, consumer, fetching, fetch } = await join({ groupId: 0n, objectId: 0n }); - if (!fetch) throw new Error("no fetch"); await accept(fetching); // No live stream ever comes: the group was written before the subscription. @@ -233,7 +227,6 @@ test("a catalog written once is readable from the head alone", async () => { test("an empty tail finishes a group the head already holds whole", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -248,9 +241,8 @@ test("an empty tail finishes a group the head already holds whole", async () => for (const outcome of ["a refused joining FETCH", "an empty joining FETCH"] as const) { test(`${outcome} costs only the group's head`, async () => { - hostTime(); + using clock = manual(); const { subscriber, consumer, fetching, fetch, client } = await join(); - if (!fetch) throw new Error("no fetch"); if (outcome === "an empty joining FETCH") { await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, [])); @@ -258,7 +250,7 @@ for (const outcome of ["a refused joining FETCH", "an empty joining FETCH"] as c await refuse(fetching); } // No standalone FETCH follows: a relay that refuses the join has a bug of its own. - expect(await nextStream(client)).toBeUndefined(); + expect(await opens(client, clock)).toBe(false); // The mid-group tail has nothing to stitch onto, so it is dropped; the next group plays. await subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); @@ -279,7 +271,7 @@ test("a reader in sequence order with no delay budget skips headless groups", as await subscriber.handleGroup(...liveStream(GROUP + 1n, 1, ["m1"])); await subscriber.handleGroup(...liveStream(GROUP + 2n, 0, ["n0"])); - const group = await timeout(Nano.fromMilli(Milli(1000)), consumer.ordered().nextGroup()); + const group = await consumer.ordered().nextGroup(); expect(group?.sequence).toBe(GROUP + 2n); }); @@ -315,17 +307,12 @@ test("a tail parked on a refused joining FETCH is dropped", async () => { }); test("a joining FETCH has no deadline of its own", async () => { - hostTime(); - jest.useFakeTimers(); - onTestFinished(() => jest.useRealTimers()); + using clock = manual(); const { subscriber, consumer, fetching, fetch, client } = await join(); - if (!fetch) throw new Error("no fetch"); const tail = subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); // Well past any request deadline: the FETCH is still out, and nothing else was sent. - jest.advanceTimersByTime(60_000); - jest.useRealTimers(); - expect(await nextStream(client)).toBeUndefined(); + expect(await opens(client, clock, Milli(60_000))).toBe(false); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -343,7 +330,7 @@ test("a joining FETCH reset after FETCH_OK costs only the head", async () => { const tail = subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); await accept(fetching); // No fetch stream ever comes. - fetching?.writer.reset(new Error("gone")); + fetching.writer.reset(new Error("gone")); await tail; await subscriber.handleGroup(...liveStream(GROUP + 1n, 0, ["n0"])); await peer.writer.u53(PublishDone.id); @@ -360,7 +347,6 @@ test("a joining FETCH reset after FETCH_OK costs only the head", async () => { test("SUBSCRIPTION_ENDED cancels a head nothing claimed", async () => { const { subscriber, consumer, fetching, fetch, peer } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); const group = await consumer.ordered().nextGroup(); @@ -395,7 +381,6 @@ test("MALFORMED_TRACK fails the track as malformed, not as a relay bug", async ( test("a whole group that precedes the head wins the sequence", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleGroup(...liveStream(GROUP, 0, ["w0", "w1", "w2"])); @@ -407,7 +392,6 @@ test("a whole group that precedes the head wins the sequence", async () => { test("a whole group for a headed sequence is refused, with its head", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -420,7 +404,6 @@ test("a whole group for a headed sequence is refused, with its head", async () = test("a head that does not meet its tail is refused", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -454,7 +437,6 @@ async function deltaHead(requestId: bigint, payloads: string[], delta: number) { test("a head that spells Object ID Delta 1 is contiguous", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await deltaHead(fetch.requestId, ["h0", "h1"], 1)); @@ -466,7 +448,6 @@ test("a head that spells Object ID Delta 1 is contiguous", async () => { test("a head that repeats an Object ID is dropped", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await deltaHead(fetch.requestId, ["h0", "h0"], 0)); @@ -477,7 +458,6 @@ test("a head that repeats an Object ID is dropped", async () => { test("a tail that is only an End of Group finishes the head", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -493,7 +473,6 @@ test("a tail that is only an End of Group finishes the head", async () => { test("a joining FETCH spanning another group drops the head", async () => { const { subscriber, consumer, fetching, fetch } = await join(); - if (!fetch) throw new Error("no fetch"); await accept(fetching); const bytes = await Writer.collect(VERSION, async (w) => { @@ -522,12 +501,12 @@ for (const version of VERSIONS) { if (version === VERSION) continue; test(`${versionName(version)}: a join subscribes at Next Object with a StartGroup=1 fill, and sends no FETCH`, async () => { - hostTime(); + using clock = manual(); const { subscribe, answer, client } = await subscribed(version); expect(subscribe.filter).toEqual({ kind: "nextObject" }); expect(subscribe.fill).toEqual({ filter: { kind: "relative", groups: 1n }, rangeFilters: false }); await answer({ groupId: GROUP, objectId: 1n }); - expect(await nextStream(client, 200, version)).toBeUndefined(); + expect(await opens(client, clock)).toBe(false); }); test(`${versionName(version)}: a fill and its tail stitch into one group`, async () => { @@ -667,7 +646,6 @@ test("an evicted joined group is fetched again as standalone history", async () const installed = clock.install(); onTestFinished(() => installed.close()); const { subscriber, consumer, fetching, fetch, client } = await join(); - if (!fetch) throw new Error("no joining FETCH"); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); await subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); @@ -682,7 +660,6 @@ test("an evicted joined group is fetched again as standalone history", async () onTestFinished(() => broadcast.close()); const pending = broadcast.track("video").fetchGroup(GROUP); const stream = await nextStream(client); - if (!stream) throw new Error("no standalone FETCH"); expect(await stream.reader.u53()).toBe(Fetch.id); const standalone = await Fetch.decode(stream.reader, VERSION); expect(standalone.type.kind).toBe("standalone"); diff --git a/js/net/src/ietf/malformed.test.ts b/js/net/src/ietf/malformed.test.ts index ce6d29343f0..ddf7c90449e 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -1,10 +1,9 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli, Nano, sleep } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { type Manual, Milli, Nano } from "@moq/clock"; import { offered } from "../connection/extensions.ts"; import { exchangeSetup } from "../connection/handshake.ts"; import { ProtocolViolation, SessionCode, StreamCode, StreamError } from "../error.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, manual } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Stream, Writer } from "../stream.ts"; @@ -47,11 +46,14 @@ function subscribe(fields: number[][], name: number, requestId = 0): Uint8Array return frame(0x03, [requestId, fields.length, ...fields.flat(), ...field(name), 0]); } -/** Resolves to the session's close code, or undefined if it stays open a moment. */ -async function closeCode(quic: WebTransport): Promise { - const open = Symbol("open"); - const result = await Promise.race([quic.closed, sleep(Nano.fromMilli(Milli(50))).then(() => open)]); - return result === open ? undefined : (result as WebTransportCloseInfo).closeCode; +/** Resolves to the session's close code once `clock` passes a moment, or undefined if it stays open. */ +async function closeCode(quic: WebTransport, clock: Manual): Promise { + let code: number | undefined; + void quic.closed.then((info) => { + code = info.closeCode; + }); + await clock.advance(Nano.fromMilli(Milli(50))); + return code; } /** A server publishing `room/video`, and a fresh client request stream. */ @@ -132,11 +134,12 @@ for (const [version, alpn] of DRAFTS) { ], ] as const) { test(`a request with ${name} closes ${alpn}`, async () => { + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { await stream.writer.write(bytes); - expect(await closeCode(pair.client)).toBe(code); + expect(await closeCode(pair.client, clock)).toBe(code); } finally { logged.mockRestore(); close(); @@ -145,12 +148,13 @@ for (const [version, alpn] of DRAFTS) { } test(`a request truncated at FIN closes ${alpn}`, async () => { + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { await stream.writer.write(subscribe([field(4)], 5).slice(0, 6)); stream.writer.close(); - expect(await closeCode(pair.client)).toBe(SessionCode.ProtocolViolation); + expect(await closeCode(pair.client, clock)).toBe(SessionCode.ProtocolViolation); } finally { logged.mockRestore(); close(); @@ -163,7 +167,7 @@ for (const [version, alpn] of DRAFTS) { ["a second GOAWAY", 2, SessionCode.ProtocolViolation], ] as const) { test(`${name} on a namespace subscription ${code === undefined ? "keeps" : "closes"} ${alpn}`, async () => { - hostTime(); + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { @@ -171,7 +175,7 @@ for (const [version, alpn] of DRAFTS) { await new SubscribeNamespace({ requestId: 0n, namespace: Path.empty() }).encode(stream.writer, version); expect(await stream.reader.u53()).toBe(RequestOk.id); await stream.writer.write(goaways(count, version)); - expect(await closeCode(pair.client)).toBe(code); + expect(await closeCode(pair.client, clock)).toBe(code); } finally { logged.mockRestore(); close(); @@ -179,7 +183,7 @@ for (const [version, alpn] of DRAFTS) { }); test(`${name} on a subscription ${code === undefined ? "keeps" : "closes"} ${alpn}`, async () => { - hostTime(); + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { @@ -196,7 +200,7 @@ for (const [version, alpn] of DRAFTS) { ); expect(await stream.reader.u53()).toBe(SubscribeOk.id); await stream.writer.write(goaways(count, version)); - expect(await closeCode(pair.client)).toBe(code); + expect(await closeCode(pair.client, clock)).toBe(code); } finally { logged.mockRestore(); close(); @@ -205,6 +209,7 @@ for (const [version, alpn] of DRAFTS) { } test(`an unknown message on a subscription closes ${alpn}`, async () => { + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { @@ -213,7 +218,7 @@ for (const [version, alpn] of DRAFTS) { ); expect(await stream.reader.u53()).toBe(SubscribeOk.id); await stream.writer.write(frame(0x7e, [])); - expect(await closeCode(pair.client)).toBe(SessionCode.ProtocolViolation); + expect(await closeCode(pair.client, clock)).toBe(SessionCode.ProtocolViolation); } finally { logged.mockRestore(); close(); @@ -222,14 +227,14 @@ for (const [version, alpn] of DRAFTS) { // A relay cancels an object stream it no longer serves, such as an old route's after a replacement. test(`a peer reset object stream keeps ${alpn} and logs no error`, async () => { - hostTime(); + using clock = manual(); const logged = spyOn(console, "error"); const { pair, close } = await serving(version, alpn); try { const uni = new Writer(await pair.client.createUnidirectionalStream(), version); await uni.write(new Uint8Array([0x10])); uni.reset(new StreamError(StreamCode.Cancel, { message: "cancel" })); - expect(await closeCode(pair.client)).toBeUndefined(); + expect(await closeCode(pair.client, clock)).toBeUndefined(); expect(logged).not.toHaveBeenCalled(); } finally { logged.mockRestore(); @@ -257,12 +262,12 @@ for (const [version, alpn] of DRAFTS) { ], ] as const) { test(`${name} on the setup stream ${code === undefined ? "keeps" : "closes"} ${alpn}`, async () => { - hostTime(); + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, peer, connection } = await client(version, alpn); try { await write(peer.writer); - expect(await closeCode(pair.server)).toBe(code); + expect(await closeCode(pair.server, clock)).toBe(code); } finally { logged.mockRestore(); connection.abort(); @@ -308,12 +313,12 @@ for (const [requestId, code] of [ ] as const) { const name = requestId === undefined ? "without a Request ID" : `Request ID ${requestId}`; test(`a draft-18 GOAWAY ${name} ${code === undefined ? "keeps" : "closes"} a client`, async () => { - hostTime(); + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, peer, connection } = await client(Version.DRAFT_18, ALPN.DRAFT_18); try { await peer.writer.write(goaways(1, Version.DRAFT_18, requestId)); - expect(await closeCode(pair.server)).toBe(code); + expect(await closeCode(pair.server, clock)).toBe(code); } finally { logged.mockRestore(); connection.abort(); @@ -324,6 +329,7 @@ for (const [requestId, code] of [ // Draft-18's GOAWAY Request ID belongs on the control stream only. for (const [version, alpn] of DRAFTS) { test(`a client's request stream GOAWAY naming a new session closes ${alpn}`, async () => { + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(version, alpn); try { @@ -332,7 +338,7 @@ for (const [version, alpn] of DRAFTS) { expect(await stream.reader.u53()).toBe(RequestOk.id); // New Session URI "a", then a zero timeout. await stream.writer.write(frame(GoAway.id, [1, 0x61, 0])); - expect(await closeCode(pair.client)).toBe(SessionCode.ProtocolViolation); + expect(await closeCode(pair.client, clock)).toBe(SessionCode.ProtocolViolation); } finally { logged.mockRestore(); close(); @@ -341,6 +347,7 @@ for (const [version, alpn] of DRAFTS) { } test("a draft-18 request stream GOAWAY with a Request ID closes", async () => { + using clock = manual(); const logged = spyOn(console, "error").mockImplementation(() => undefined); const { pair, stream, close } = await serving(Version.DRAFT_18, ALPN.DRAFT_18); try { @@ -351,7 +358,7 @@ test("a draft-18 request stream GOAWAY with a Request ID closes", async () => { ); expect(await stream.reader.u53()).toBe(RequestOk.id); await stream.writer.write(goaways(1, Version.DRAFT_18, 0)); - expect(await closeCode(pair.client)).toBe(SessionCode.ProtocolViolation); + expect(await closeCode(pair.client, clock)).toBe(SessionCode.ProtocolViolation); } finally { logged.mockRestore(); close(); diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index a6a0935acce..4e00bb0a26d 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -1,6 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, sleep, timeout, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; @@ -18,7 +17,7 @@ import { import { type Hop, HopSchema } from "../hop.ts"; import * as Instance from "../instance.ts"; import { hooks } from "../internal.ts"; -import { createMockTransportPair, SessionBroadcast } from "../mock.ts"; +import { createMockTransportPair, manual, SessionBroadcast, settlesWithin } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Reader, Stream, Writer } from "../stream.ts"; @@ -58,13 +57,6 @@ const CLUSTER = { cluster: true }; /** How long to wait for a stream before calling it absent, which is how a regression reports. */ const STREAM_WAIT = 1000; -/** A manual clock, installed until disposed. */ -function manual(): Manual & Disposable { - const clock = new Manual(); - const installed = clock.install(); - return Object.assign(clock, { [Symbol.dispose]: () => installed.close() }); -} - /** * Whether `read` yields a stream once pending work has armed its timers and {@link STREAM_WAIT} * has passed on `clock`, which fires any retry that would open one. @@ -92,26 +84,13 @@ async function noStream(transport: WebTransport, clock: Manual): Promise { } } -/** Long enough for the publish to reach the announce loop's signal. */ -const SETTLE = 5; - -/** - * Accept the next stream the publisher opens, or give up rather than hang forever. - * - * Reads the queue directly instead of racing {@link Stream.accept}, whose pending read - * would keep the reader locked after the race resolves and could swallow a later stream. - */ -async function nextStream(transport: WebTransport): Promise { +/** Accept the next stream the publisher opens. */ +async function nextStream(transport: WebTransport): Promise { const reader = transport.incomingBidirectionalStreams.getReader() as ReadableStreamDefaultReader; - try { - const next = await timeout(Nano.fromMilli(Milli(STREAM_WAIT)), reader.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - - if (!next || next.done) return undefined; + const next = await reader.read(); + if (next.done) throw new Error("the session ended before the publisher opened a stream"); return new Stream({ readable: next.value.readable, writable: next.value.writable, version: VERSION }); } finally { reader.releaseLock(); @@ -386,12 +365,7 @@ test("a second GOAWAY on an unanswered SUBSCRIBE closes the session", async () = // GOAWAY with no new session and no timeout, twice. held.send(Uint8Array.of(0x10, 0, 2, 0, 0, 0x10, 0, 2, 0, 0)); - const closed = await Promise.race([ - pair.server.closed, - sleep(Nano.fromMilli(Milli(500))).then(() => { - throw new Error("session stayed up"); - }), - ]); + const closed = await pair.server.closed; expect(closed.closeCode).toBe(SessionCode.ProtocolViolation); await task; expect(held.written).toEqual([]); @@ -920,11 +894,7 @@ test("a blocked group header is reset when the group expires", async () => { later.writeFrame({ payload: new TextEncoder().encode("later"), timestamp: Timestamp.fromMillis(20_000) }); later.finish(); - const resetBeforeRelease = await Promise.race([ - streamReset.then(() => true), - sleep(Nano.fromMilli(Milli(500))).then(() => false as const), - ]); - expect(resetBeforeRelease).toBe(true); + await streamReset; } finally { release(); client.close(); @@ -1190,7 +1160,7 @@ test("a group that goes stale while its stream opens writes nothing", async () = * namespace unadvertised until something unrelated changed. */ test("a broadcast published mid-advertisement is still announced", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server); @@ -1200,17 +1170,15 @@ test("a broadcast published mid-advertisement is still announced", async () => { // Take the first advertisement but withhold the reply, parking the loop. const one = await nextStream(pair.client); - if (!one) throw new Error("no PUBLISH_NAMESPACE for the first broadcast"); expect(await readPublishNamespace(one)).toBe(Path.from("first")); // Publish while the loop is parked on that reply. publish(origin, Path.from("second")); - await sleep(Nano.fromMilli(Milli(SETTLE))); + await clock.advance(Nano.zero); await acceptPublishNamespace(one); const two = await nextStream(pair.client); - if (!two) throw new Error("the broadcast published mid-advertisement was never announced"); expect(await readPublishNamespace(two)).toBe(Path.from("second")); await acceptPublishNamespace(two); @@ -1223,7 +1191,7 @@ test("a broadcast published mid-advertisement is still announced", async () => { * be offered again for the life of the session. */ test("a declined advertisement is retried on the next change", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server); @@ -1232,7 +1200,6 @@ test("a declined advertisement is retried on the next change", async () => { void pub.runPublishNamespaces(); const declined = await nextStream(pair.client); - if (!declined) throw new Error("no PUBLISH_NAMESPACE for the first broadcast"); expect(await readPublishNamespace(declined)).toBe(Path.from("first")); await declinePublishNamespace(declined); @@ -1242,8 +1209,8 @@ test("a declined advertisement is retried on the next change", async () => { const seen = new Set(); for (let i = 0; i < 2; i++) { - const stream = await nextStream(pair.client); - if (!stream) break; + // The refusal asked for a 1ms wait before the namespace is offered again. + const stream = await clock.drive(nextStream(pair.client)); seen.add(await readPublishNamespace(stream)); await acceptPublishNamespace(stream); } @@ -1441,7 +1408,6 @@ test("a refusal that forbids retrying is not retried", async () => { void pub.runPublishNamespaces(); const stream = await nextStream(pair.client); - if (!stream) throw new Error("the namespace was never advertised"); expect(await readPublishNamespace(stream)).toBe(Path.from("lonely")); await declinePublishNamespace(stream, 0n); @@ -1458,7 +1424,7 @@ test("a refusal that forbids retrying is not retried", async () => { * the replacement for the life of the session. */ test("republishing a path clears a refusal without unannouncing first", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server); @@ -1467,16 +1433,14 @@ test("republishing a path clears a refusal without unannouncing first", async () void pub.runPublishNamespaces(); const declined = await nextStream(pair.client); - if (!declined) throw new Error("the namespace was never advertised"); expect(await readPublishNamespace(declined)).toBe(Path.from("recycled")); await declinePublishNamespace(declined, 0n); - await sleep(Nano.fromMilli(Milli(SETTLE))); + await clock.advance(Nano.zero); // A new broadcast takes the path over outright: no close, no gap. publish(origin, Path.from("recycled")); const retried = await nextStream(pair.client); - if (!retried) throw new Error("the replacement broadcast was never offered"); expect(await readPublishNamespace(retried)).toBe(Path.from("recycled")); await acceptPublishNamespace(retried); @@ -1489,7 +1453,7 @@ test("republishing a path clears a refusal without unannouncing first", async () * delivers. */ test("a new instance at the same path clears a refusal", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server); @@ -1498,15 +1462,13 @@ test("a new instance at the same path clears a refusal", async () => { void pub.runPublishNamespaces(); const declined = await nextStream(pair.client); - if (!declined) throw new Error("the namespace was never advertised"); expect(await readPublishNamespace(declined)).toBe(Path.from("restarted")); await declinePublishNamespace(declined, 0n); - await sleep(Nano.fromMilli(Milli(SETTLE))); + await clock.advance(Nano.zero); wireOf(broadcast).update({ ...wireOf(broadcast).info, instance: Instance.random() }); const retried = await nextStream(pair.client); - if (!retried) throw new Error("the new instance was never offered"); expect(await readPublishNamespace(retried)).toBe(Path.from("restarted")); await acceptPublishNamespace(retried); @@ -1520,7 +1482,7 @@ test("a new instance at the same path clears a refusal", async () => { * by rebuilding the watched entry on re-announce. */ test("re-announcing a path clears a refusal that forbade retrying", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server); @@ -1529,17 +1491,15 @@ test("re-announcing a path clears a refusal that forbade retrying", async () => void pub.runPublishNamespaces(); const declined = await nextStream(pair.client); - if (!declined) throw new Error("the namespace was never advertised"); expect(await readPublishNamespace(declined)).toBe(Path.from("recycled")); await declinePublishNamespace(declined, 0n); // The broadcast goes away, taking the refusal with it, and a new one takes its place. first.close(); - await sleep(Nano.fromMilli(Milli(SETTLE))); + await clock.advance(Nano.zero); publish(origin, Path.from("recycled")); const retried = await nextStream(pair.client); - if (!retried) throw new Error("a re-announced path was never offered again"); expect(await readPublishNamespace(retried)).toBe(Path.from("recycled")); await acceptPublishNamespace(retried); @@ -1560,7 +1520,6 @@ test("closing the session ends the unsolicited announce loop", async () => { const loop = pub.runPublishNamespaces(); const one = await nextStream(pair.client); - if (!one) throw new Error("no PUBLISH_NAMESPACE for the first broadcast"); expect(await readPublishNamespace(one)).toBe(Path.from("first")); await acceptPublishNamespace(one); @@ -1568,12 +1527,7 @@ test("closing the session ends the unsolicited announce loop", async () => { pair.server.close(); // Ending with the session's error is ending too: the close fails its open streams. - await Promise.race([ - loop.catch(() => undefined), - sleep(Nano.fromMilli(Milli(STREAM_WAIT))).then(() => { - throw new Error("the announce loop outlived its session"); - }), - ]); + await loop.catch(() => undefined); // The origin really did survive the session, so publishing into it is still valid. publish(origin, Path.from("second")); @@ -1595,7 +1549,6 @@ test("an advertisement carries our hop id once the peer declared one", async () void pub.runPublishNamespaces(); const stream = await nextStream(pair.client); - if (!stream) throw new Error("no PUBLISH_NAMESPACE for the broadcast"); expect(await stream.reader.u53()).toBe(PublishNamespace.id); if (peer === undefined) { @@ -2225,7 +2178,6 @@ test.each([ void pub.runPublishNamespaces(); const stream = await nextStream(pair.client); - if (!stream) throw new Error("no PUBLISH_NAMESPACE for the broadcast"); expect(await stream.reader.u53()).toBe(PublishNamespace.id); const msg = await PublishNamespace.decode(stream.reader, VERSION, { cluster: peer !== undefined }); expect(msg.trackNamespace).toBe(Path.from("mine")); @@ -2394,15 +2346,12 @@ async function runSubscribe( return { client, ok: await SubscribeOk.decode(client.reader, fx.version) }; } -/** Take the next uni stream the publisher opened, or undefined if it opened none. */ +/** Take the next uni stream the publisher opens. */ async function nextUni( uni: ReadableStreamDefaultReader>, -): Promise | undefined> { - const next = await timeout(Nano.fromMilli(Milli(STREAM_WAIT)), uni.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - if (!next || next.done) return undefined; +): Promise> { + const next = await uni.read(); + if (next.done) throw new Error("the session ended before the publisher opened a stream"); return next.value; } @@ -2533,7 +2482,6 @@ test("draft-22: an absolute filter trims the range it serves", async () => { }); const first = await nextUni(fx.uni); - if (!first) throw new Error("the filter's start group was never served"); expect(await readGroup(first)).toEqual({ sequence: 1n, // The head was trimmed, so the stream does not start at the group's first object. @@ -2546,7 +2494,6 @@ test("draft-22: an absolute filter trims the range it serves", async () => { }); const second = await nextUni(fx.uni); - if (!second) throw new Error("the filter's end group was never served"); expect(await readGroup(second)).toEqual({ sequence: 2n, firstObject: true, @@ -2622,7 +2569,6 @@ test.each(IETF_VERSIONS)("version %d: only an absolute start replays history", a const served: bigint[] = []; for (const _ of expected) { const stream = await nextUni(fx.uni); - if (!stream) throw new Error(`${version} ${filter.kind}: missing group stream`); served.push((await GroupMessage.decode(new Reader(stream, undefined, version), version)).groupId); } expect(served).toEqual([...expected]); @@ -2667,7 +2613,6 @@ test.each(["nextObject", "unfiltered"] as const)( expect(ok.largest).toEqual({ groupId: 1n, objectId: 1n }); const fill = await nextUni(fx.uni); - if (!fill) throw new Error("no fetch stream for the requested fill"); expect(await readFill(fill)).toEqual({ requestId: 7n, objects: [ @@ -2682,7 +2627,6 @@ test.each(["nextObject", "unfiltered"] as const)( group.finish(); const live = await nextUni(fx.uni); - if (!live) throw new Error("the subscription never served the live tail"); expect(await readGroup(live)).toEqual({ sequence: 1n, firstObject: false, @@ -2713,7 +2657,6 @@ test("draft-22: a fill never rewinds an absolute live join", async () => { ); try { const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing fill before the live join"); expect((await readFill(fill)).objects).toEqual([ { group: 0, id: 0, payload: "0.0" }, { group: 0, id: 1, payload: "0.1" }, @@ -2722,7 +2665,6 @@ test("draft-22: a fill never rewinds an absolute live join", async () => { group.writeFrame({ payload: new TextEncoder().encode("1.0"), timestamp: Timestamp.now() }); group.finish(); const live = await nextUni(fx.uni); - if (!live) throw new Error("missing live group after the fill"); expect(await readGroup(live)).toEqual({ sequence: 1n, firstObject: true, @@ -2763,7 +2705,6 @@ test("draft-22: an open group with a shed front refuses a tail join", async () = expect(ok.largest).toEqual({ groupId: 0n, objectId: 39n }); const live = await nextUni(fx.uni); - if (!live) throw new Error("the subscription never opened a stream for the evicted group"); await expect(readGroup(live)).rejects.toBeDefined(); } finally { fx.close(); @@ -2799,7 +2740,6 @@ test("draft-22: a backwards range within one group serves nothing and ends the s try { const served = await nextUni(fx.uni); - if (!served) throw new Error("the group stream never opened"); expect(await readGroup(served)).toEqual({ sequence: 0n, firstObject: false, endOfGroup: false, objects: [] }); } finally { fx.close(); @@ -2833,7 +2773,6 @@ test.each(["ascending", "descending"] as const)("draft-22: a wider fill is refus try { const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing fill stream"); const served = await readFill(fill, order); expect(served.reset).toBeInstanceOf(StreamError); expect(served.objects).toEqual([]); @@ -2843,7 +2782,6 @@ test.each(["ascending", "descending"] as const)("draft-22: a wider fill is refus const objects = []; while (objects.length === 0) { const stream = await nextUni(fx.uni); - if (!stream) throw new Error("subscription ended with its refused fill"); objects.push(...(await readGroup(stream)).objects); } expect(objects).toEqual([{ id: 0, payload: "live" }]); @@ -2954,7 +2892,6 @@ test.each([ writeGroup(track, 1); const served = await nextUni(fx.uni); - if (!served) throw new Error("the group was never served"); const reader = new Reader(served, undefined, version); const header = await GroupMessage.decode(reader, version); expect(header.flags.hasExtensions).toBe(propertiesWanted); @@ -3018,7 +2955,6 @@ test("a timed track declares TIMESCALE and stamps its objects", async () => { writeGroup(track, 1); const served = await nextUni(fx.uni); - if (!served) throw new Error("the group was never served"); const reader = new Reader(served, undefined, version); const header = await GroupMessage.decode(reader, version); expect(header.flags.hasExtensions).toBe(true); @@ -3187,7 +3123,6 @@ test("draft-22: a clean close past a bounded filter's end still sends PUBLISH_DO try { const served = await nextUni(fx.uni); - if (!served) throw new Error("the requested group was never served"); expect((await readGroup(served)).sequence).toBe(0n); // Beyond the end, so it is never served, and it must not hold the subscription open. @@ -3202,7 +3137,6 @@ test("draft-22: a clean close past a bounded filter's end still sends PUBLISH_DO // Only the in-range group was ever served; the other stream marks the track's end. const end = await nextUni(fx.uni); - if (!end) throw new Error("the track's end was never marked"); expect(await readEndOfTrack(end)).toBe(2n); expect(await opens(fx.uni.read(), clock)).toBe(false); } finally { @@ -3230,7 +3164,6 @@ test.each([0, 1000])("draft-22: FILL_TIMEOUT=%s is ignored for a largest-group f ); try { const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing fill"); expect(await readFill(fill)).toMatchObject({ objects: [{ group: 0, id: 0, payload: "0.0" }] }); } finally { open.finish(); @@ -3278,7 +3211,6 @@ test("draft-22: a fill works on a dynamically requested track", async () => { expect(ok.largest).toEqual({ groupId: 0n, objectId: 1n }); const fill = await nextUni(fx.uni); - if (!fill) throw new Error("no fetch stream for the requested fill"); expect(await readFill(fill)).toEqual({ requestId: 7n, objects: [ @@ -3342,7 +3274,7 @@ for (const synchronous of [true, false]) { // PUBLISH_DONE MUST wait until every stream the subscription will open is closed, so its // Stream Count is final. A group still queued for a stream slot when the track ends is one. test("draft-22: PUBLISH_DONE waits for a queued group and counts every stream", async () => { - hostTime(); + using clock = manual(); const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); @@ -3376,12 +3308,10 @@ test("draft-22: PUBLISH_DONE waits for a queued group and counts every stream", // Nothing ends the subscription while the group waits for its slot. const response = client.reader.u53(); - const idle = sleep(Nano.fromMilli(Milli(20))).then(() => "pending" as const); - expect(await Promise.race([response, idle])).toBe("pending"); + expect(await settlesWithin(response, clock, Milli(20))).toBe(false); slot.resolve(); const served = await nextUni(fx.uni); - if (!served) throw new Error("the queued group was never served"); expect((await readGroup(served)).sequence).toBe(0n); expect(await response).toBe(PublishDone.id); @@ -3391,7 +3321,6 @@ test("draft-22: PUBLISH_DONE waits for a queued group and counts every stream", expect(done.streamCount).toBe(2n); const end = await nextUni(fx.uni); - if (!end) throw new Error("the track's end was never marked"); expect(await readEndOfTrack(end)).toBe(1n); } finally { fx.close(); @@ -3739,7 +3668,6 @@ test("a SUBSCRIBE pauses without demand and resumes as a new subscriber", async write("before"); if (!startPaused) { const before = await nextUni(fx.uni); - if (!before) throw new Error("the subscription served nothing"); expect((await readGroup(before)).objects).toEqual([{ id: 0, payload: "before" }]); await forward(2n, false); } @@ -3751,7 +3679,6 @@ test("a SUBSCRIBE pauses without demand and resumes as a new subscriber", async write("after"); for (;;) { const stream = await nextUni(fx.uni); - if (!stream) throw new Error("the resumed subscription served nothing"); const group = await readGroup(stream); const payloads = group.objects.map((object) => object.payload); expect(payloads).not.toContain("paused"); @@ -4082,7 +4009,7 @@ test("draft-22: narrowing resets a group stream parked on flow control", async ( await client.writer.u53(SubscribeUpdate.id); await new SubscribeUpdate({ requestId: 2n, parameters }).encode(client.writer, V22); expect(await client.reader.u53()).toBe(RequestOk.id); - const reason = await timeout(Nano.fromMilli(Milli(1000)), aborted); + const reason = await aborted; expect(fromTransport(reason, { version: V22 })).toMatchObject({ code: StreamCode.Cancel }); } finally { open.finish(); @@ -4210,19 +4137,13 @@ test.each([0, Number.MAX_SAFE_INTEGER + 2])( publish(origin, Path.from("a")); const stream = await nextStream(pair.client); - if (!stream) throw new Error("no PUBLISH_NAMESPACE was sent"); expect(await readPublishNamespace(stream)).toBe(Path.from("a")); const parameters = new Parameters(); parameters.activeCount = count; await stream.writer.u53(RequestOk.id); await new RequestOk({ parameters }).encode(stream.writer, VERSION); - const closed = await Promise.race([ - pair.server.closed, - sleep(Nano.fromMilli(Milli(500))).then(() => { - throw new Error("session stayed up"); - }), - ]); + const closed = await pair.server.closed; expect(closed.closeCode).toBe(new ProtocolViolation("").code); origin.close(); }, @@ -4259,7 +4180,6 @@ test("draft-22: a range update replaces the live subscription bounds", async () const served: ServedGroup[] = []; for (let i = 0; i < 2; i++) { const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing group from updated range"); served.push(await readGroup(stream)); } expect( @@ -4275,7 +4195,6 @@ test("draft-22: a range update replaces the live subscription bounds", async () expect(done.statusCode).toBe(TRACK_ENDED_STATUS); expect(done.streamCount).toBe(3n); const end = await nextUni(fx.uni); - if (!end) throw new Error("missing exact track end after updated bounds"); expect(await readEndOfTrack(end)).toBe(5n); } finally { client.close(); @@ -4346,7 +4265,6 @@ test("draft-22: an update fills its snapshot under its own request ID", async () let served: ServedFill | undefined; for (let i = 0; i < 2; i++) { const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing update data stream"); const reader = new Reader(stream, undefined, V22); if ((await reader.peekU62()) === BigInt(FetchHeader.type)) served = await readFill(reader, "ascending"); else expect((await readGroup(reader)).objects).toEqual([]); @@ -4385,7 +4303,6 @@ test("draft-22: an empty newer group is not an object in Largest or a relative f expect(ok.largest).toEqual({ groupId: 0n, objectId: 1n }); expect(track.largest()).toEqual({ group: 1n, frame: 0 }); const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing relative fill"); const served = await readFill(stream); expect(served.reset).toBeUndefined(); expect(served.objects).toEqual([0, 1].map((id) => ({ group: 0, id, payload: `0.${id}` }))); @@ -4460,7 +4377,6 @@ test("draft-22: Next Object behind an upstream group report still delivers its f group.writeFrame({ payload: new TextEncoder().encode("first"), timestamp: Timestamp.now() }); group.finish(); const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing first received object"); expect((await readGroup(stream)).objects).toEqual([{ id: 0, payload: "first" }]); } finally { client.close(); @@ -4491,7 +4407,6 @@ test("draft-22: Next Object on an empty group still delivers its first object", group.writeFrame({ payload: new TextEncoder().encode("first"), timestamp: Timestamp.now() }); group.finish(); const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing first published object"); expect((await readGroup(stream)).objects).toEqual([{ id: 0, payload: "first" }]); } finally { client.close(); @@ -4565,7 +4480,6 @@ test("draft-22: a SUBSCRIBE's fill reads the cache at the converted subscriber p try { expect(track.subscription.peek()?.priority).toBe(-64); const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing fill stream"); const served = await readFill(new Reader(stream, undefined, V22), "ascending"); expect(served.reset).toBeUndefined(); expect(served.objects).toEqual([0, 1].map((id) => ({ group: 0, id, payload: `0.${id}` }))); @@ -4637,7 +4551,6 @@ test("draft-22: narrowing gives up an excluded group's open stream", async () => ); try { const stream = await nextUni(fx.uni); - if (!stream) throw new Error("missing initial open group"); const [data, observed] = stream.tee(); const reading = readGroup(data).then(() => undefined, error); const reader = new Reader(observed, undefined, V22); @@ -4657,7 +4570,6 @@ test("draft-22: narrowing gives up an excluded group's open stream", async () => open.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.now() }); writeGroup(track, 1); const next = await nextUni(fx.uni); - if (!next) throw new Error("missing group after narrowed range"); expect((await readGroup(next)).sequence).toBe(1n); } finally { open.finish(); @@ -4669,7 +4581,7 @@ test("draft-22: narrowing gives up an excluded group's open stream", async () => }); test("draft-22: widening with a fill keeps the open live group", async () => { - hostTime(); + using clock = manual(); const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); writeGroup(track, 1); @@ -4681,7 +4593,6 @@ test("draft-22: widening with a fill keeps the open live group", async () => { ); try { const live = await nextUni(fx.uni); - if (!live) throw new Error("missing initial open group"); const reading = readGroup(live); const parameters = new Parameters(); parameters.subscriptionFilter = { kind: "absolute", startGroup: 1n, startObject: 0n }; @@ -4694,7 +4605,6 @@ test("draft-22: widening with a fill keeps the open live group", async () => { expect(await client.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(client.reader, fx.version); const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing update fill"); expect((await readFill(fill, "ascending")).objects).toEqual([{ group: 1, id: 0, payload: "1.0" }]); open.writeFrame({ payload: new TextEncoder().encode("1.1"), timestamp: Timestamp.now() }); open.finish(); @@ -4703,7 +4613,7 @@ test("draft-22: widening with a fill keeps the open live group", async () => { { id: 0, payload: "1.0" }, { id: 1, payload: "1.1" }, ]); - expect(await nextUni(fx.uni)).toBeUndefined(); + expect(await opens(fx.uni.read(), clock)).toBe(false); } finally { open.finish(); client.close(); @@ -4714,7 +4624,7 @@ test("draft-22: widening with a fill keeps the open live group", async () => { }); test("draft-22: a fill-only update short of the edge keeps the live join's floor", async () => { - hostTime(); + using clock = manual(); const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); writeGroup(track, 1); @@ -4726,7 +4636,6 @@ test("draft-22: a fill-only update short of the edge keeps the live join's floor ); try { const live = await nextUni(fx.uni); - if (!live) throw new Error("missing initial open group"); const reading = readGroup(live); const parameters = new Parameters(); parameters.fillParameters = Filter.encodeFill( @@ -4742,7 +4651,6 @@ test("draft-22: a fill-only update short of the edge keeps the live join's floor expect(await client.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(client.reader, fx.version); const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing update fill"); expect((await readFill(fill, "ascending")).reset).toBeDefined(); open.writeFrame({ payload: new TextEncoder().encode("1.1"), timestamp: Timestamp.now() }); open.finish(); @@ -4751,7 +4659,7 @@ test("draft-22: a fill-only update short of the edge keeps the live join's floor { id: 1, payload: "1.1" }, ]); // The refused fill never changes the live cursor. - expect(await nextUni(fx.uni)).toBeUndefined(); + expect(await opens(fx.uni.read(), clock)).toBe(false); } finally { open.finish(); client.close(); @@ -4762,7 +4670,7 @@ test("draft-22: a fill-only update short of the edge keeps the live join's floor }); test("draft-22: a fill-only update keeps the subscription's floor", async () => { - hostTime(); + using clock = manual(); const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); writeGroup(track, 1); @@ -4774,7 +4682,6 @@ test("draft-22: a fill-only update keeps the subscription's floor", async () => ); try { const live = await nextUni(fx.uni); - if (!live) throw new Error("missing initial open group"); const reading = readGroup(live); const parameters = new Parameters(); parameters.fillParameters = Filter.encodeFill( @@ -4786,7 +4693,6 @@ test("draft-22: a fill-only update keeps the subscription's floor", async () => expect(await client.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(client.reader, fx.version); const fill = await nextUni(fx.uni); - if (!fill) throw new Error("missing update fill"); expect((await readFill(fill, "ascending")).objects).toEqual([{ group: 1, id: 0, payload: "1.0" }]); open.writeFrame({ payload: new TextEncoder().encode("1.1"), timestamp: Timestamp.now() }); open.finish(); @@ -4795,7 +4701,7 @@ test("draft-22: a fill-only update keeps the subscription's floor", async () => { id: 1, payload: "1.1" }, ]); // The live join's floor stays at group 1, so group 0 is never offered. - expect(await nextUni(fx.uni)).toBeUndefined(); + expect(await opens(fx.uni.read(), clock)).toBe(false); } finally { open.finish(); client.close(); @@ -4820,7 +4726,6 @@ test.each([ ); try { const live = await nextUni(fx.uni); - if (!live) throw new Error("missing initial open group"); const reading = readGroup(live).then(() => undefined, error); for (const [requestId, startGroup, startObject] of [ [2n, group, object], @@ -4859,7 +4764,6 @@ async function readServed( const served: string[] = []; for (let i = 0; i < count; i++) { const stream = await nextUni(uni); - if (!stream) throw new Error("missing stream after widening"); const reader = new Reader(stream, undefined, V22); if ((await reader.peekU62()) === BigInt(FetchHeader.type)) served.push(...(await readFill(reader, "ascending")).objects.map(({ payload }) => payload)); @@ -4921,7 +4825,6 @@ for (const endObject of [BigInt(Number.MAX_SAFE_INTEGER), (1n << 60n) + 1n]) { try { writeGroup(track, 2); const stream = await nextUni(fx.uni); - if (!stream) throw new Error("no group for the accepted filter"); expect((await readGroup(stream)).objects).toEqual([ { id: 0, payload: "0.0" }, { id: 1, payload: "0.1" }, diff --git a/js/net/src/ietf/request_stream.test.ts b/js/net/src/ietf/request_stream.test.ts index 3eaeb121702..121adbba81e 100644 --- a/js/net/src/ietf/request_stream.test.ts +++ b/js/net/src/ietf/request_stream.test.ts @@ -1,7 +1,7 @@ import { expect, mock, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano } from "@moq/clock"; import { ProtocolViolation, SessionCode, StreamCode, StreamError } from "../error.ts"; +import { manual, settlesWithin } from "../mock.ts"; import { Reader, Stream } from "../stream.ts"; import { Deadline, REQUEST_TIMEOUT_MS } from "../util/deadline.ts"; import * as Varint from "../varint.ts"; @@ -88,7 +88,7 @@ for (const version of [Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22]) { }); test(`${versionName(version)} a request stream's messages are taken whole, around a GOAWAY`, async () => { - hostTime(); + using clock = manual(); // An empty REQUEST_OK, then FIN. const { request, closes } = requested(version, Uint8Array.of(...GOAWAY, 7, 0, 0), "fin"); const framed = await request.next(); @@ -96,11 +96,7 @@ for (const version of [Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22]) { expect(await framed?.reader.u16()).toBe(0); expect(await request.next()).toBeUndefined(); // FIN cancels a draft-18 request; a draft-22 one lasts until reset. - const ended = await Promise.race([ - request.ended.then(() => true), - sleep(Nano.fromMilli(Milli(10))).then(() => false), - ]); - expect(ended).toBe(version === Version.DRAFT_18); + expect(await settlesWithin(request.ended, clock, Milli(10))).toBe(version === Version.DRAFT_18); expect(closes).toEqual([]); }); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index 276cb51ba88..1935502beaa 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -1,12 +1,11 @@ import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, sleep, timeout, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import { Once } from "@moq/signals"; import type * as announce from "../announced.ts"; import { ProtocolViolation, StreamCode, Stream as StreamError } from "../error.ts"; import { type Hop, HopSchema, UNKNOWN_HOP } from "../hop.ts"; import { hooks } from "../internal.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import * as Path from "../path.ts"; import { Reader, Stream } from "../stream.ts"; import { Tail } from "../tail.ts"; @@ -30,26 +29,13 @@ import { ALPN, type IetfVersion, Version } from "./version.ts"; const VERSION = Version.DRAFT_18; -/** How long to wait for a stream before calling it absent. */ -const STREAM_WAIT = 500; - -/** - * Accept the next stream the subscriber opens, or give up rather than hang forever. - * - * Reads the queue directly instead of racing {@link Stream.accept}, whose pending read - * would keep the reader locked after the race resolves and could swallow a later stream. - */ -async function nextStream(transport: WebTransport, version: IetfVersion = VERSION): Promise { +/** Accept the next stream the subscriber opens. */ +async function nextStream(transport: WebTransport, version: IetfVersion = VERSION): Promise { const reader = transport.incomingBidirectionalStreams.getReader() as ReadableStreamDefaultReader; - try { - const next = await timeout(Nano.fromMilli(Milli(STREAM_WAIT)), reader.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - - if (!next || next.done) return undefined; + const next = await reader.read(); + if (next.done) throw new Error("the session ended before the subscriber opened a stream"); return new Stream({ readable: next.value.readable, writable: next.value.writable, version }); } finally { reader.releaseLock(); @@ -100,7 +86,6 @@ test("an unsolicited announcement lands", async () => { // The handler holds the request open until the peer drops it, and withdraws the // namespace on the way out. const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream to close"); peer.writer.close(); await peer.writer.closed; // A second advertisement is a processing barrier: the FIN must not retract the first. @@ -117,7 +102,6 @@ test("an unsolicited announcement lands", async () => { kind: "end", }); const secondPeer = await nextStream(pair.client); - if (!secondPeer) throw new Error("missing sentinel stream"); secondPeer.close(); await other; }); @@ -146,7 +130,6 @@ test("an advertisement with no path is anonymous", async () => { */ async function acceptSubscribeNamespace(transport: WebTransport, version: IetfVersion = VERSION): Promise { const stream = await nextStream(transport, version); - if (!stream) throw new Error("no SUBSCRIBE_NAMESPACE was sent"); // Drain the request, then answer it. await stream.reader.u53(); @@ -190,7 +173,7 @@ async function syncInline(stream: Stream, announced: announce.Routes, cluster?: * watcher drops a broadcast that is still being published. */ test("an announcement survives the first of its two sources ending", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const session = new NativeSession(pair.server, VERSION, true); const subscriber = new Subscriber({ session }); @@ -212,15 +195,10 @@ test("an announcement survives the first of its two sources ending", async () => // The unsolicited request goes away. The subscription still advertises the path, so // nothing has been withdrawn and there is nothing for the consumer to hear. const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream to close"); peer.close(); await handler; - const next = await Promise.race([ - announced.next(), - sleep(Nano.fromMilli(Milli(250))).then(() => "nothing" as const), - ]); - expect(next).toBe("nothing"); + expect(await settlesWithin(announced.next(), clock, Milli(250))).toBe(false); }); test("announced lists literal matches unless covering asks for overlapping routes too", async () => { @@ -272,7 +250,6 @@ test("an announcement ends once its last source does", async () => { await syncInline(subscription, announced); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream to close"); peer.close(); await handler; @@ -317,7 +294,7 @@ test("a subscription that dies releases what it advertised", async () => { * for the session with nobody left to release it. */ test("an entry buffered past a consumer close does not pin the path", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const session = new NativeSession(pair.server, VERSION, true); const subscriber = new Subscriber({ session }); @@ -335,12 +312,11 @@ test("an entry buffered past a consumer close does not pin the path", async () = subscription.writer.close(); // Whatever the loop managed to attach, the stream gave back on its way out. - await sleep(Nano.fromMilli(Milli(50))); + await clock.advance(Nano.zero); const fresh = subscriber.routes(); await acceptSubscribeNamespace(pair.client); - const seeded = await Promise.race([fresh.next(), sleep(Nano.fromMilli(Milli(250))).then(() => "nothing" as const)]); - expect(seeded).toBe("nothing"); + expect(await settlesWithin(fresh.next(), clock, Milli(250))).toBe(false); }); /** The Hop IDs a cluster-negotiated session declared, ours first. */ @@ -433,7 +409,6 @@ test("a PUBLISH_NAMESPACE that looped back through us is refused", async () => { ); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); expect(await peer.reader.u53()).toBe(RequestError.id); const err = await RequestError.decode(peer.reader, VERSION); // UNINTERESTED, draft-22 section 16.11.2: stop offering us this namespace. @@ -460,12 +435,7 @@ test("a NAMESPACE missing its hop path closes the session", async () => { await subscription.writer.u53(SubscribeNamespaceEntry.id); await new SubscribeNamespaceEntry({ suffix: Path.from("nohops") }).encode(subscription.writer, VERSION); - await Promise.race([ - pair.server.closed, - sleep(Nano.fromMilli(Milli(STREAM_WAIT))).then(() => { - throw new Error("session stayed up"); - }), - ]); + await pair.server.closed; }); test("a malformed PUBLISH_NAMESPACE update closes the session", async () => { @@ -498,12 +468,7 @@ test("a malformed PUBLISH_NAMESPACE update closes the session", async () => { await request.writer.u16(1); await request.writer.u8(3); - await Promise.race([ - pair.server.closed, - sleep(Nano.fromMilli(Milli(STREAM_WAIT))).then(() => { - throw new Error("session stayed up"); - }), - ]); + await pair.server.closed; } finally { logged.mockRestore(); connection.abort(); @@ -538,7 +503,6 @@ test("a PUBLISH_NAMESPACE update that starts looping back is detached", async () expect(await announced.next()).toMatchObject({ prefix: Path.from("theirs"), kind: "start" }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); expect(await peer.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(peer.reader, VERSION); @@ -596,7 +560,6 @@ test("a PUBLISH_NAMESPACE repricing is acknowledged in place", async () => { }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); expect(await peer.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(peer.reader, VERSION); @@ -641,7 +604,6 @@ test("a PUBLISH_NAMESPACE update that changes the publisher applies in place", a expect(await announced.next()).toMatchObject({ prefix: Path.from("theirs"), kind: "start" }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); expect(await peer.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(peer.reader, VERSION); const held = subscriber.consume(Path.from("theirs")); @@ -703,7 +665,6 @@ test("a repeated PUBLISH_NAMESPACE is a protocol violation", async () => { expect(await announced.next()).toMatchObject({ prefix: Path.from("theirs"), kind: "start" }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); await peer.writer.u53(PublishNamespace.id); await advert.encode(peer.writer, VERSION); @@ -778,7 +739,6 @@ async function subscribeTrack({ .subscribe(subscription ?? { ...track.Subscription.default(), ranges: [{ start: { relative: 0n } }] }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("the subscriber never opened a subscribe stream"); peer.reader.version = version; peer.writer.version = version; @@ -804,7 +764,6 @@ test("a refused SUBSCRIBE or SUBSCRIBE_NAMESPACE ends its stream cleanly", async const announced = subscriber.routes(); const namespace = await nextStream(pair.client); - if (!namespace) throw new Error("no SUBSCRIBE_NAMESPACE was sent"); expect(await namespace.reader.u53()).toBe(SubscribeNamespace.id); await SubscribeNamespace.decode(namespace.reader, VERSION); await refuse(namespace); @@ -813,7 +772,6 @@ test("a refused SUBSCRIBE or SUBSCRIBE_NAMESPACE ends its stream cleanly", async const track = subscriber.consume(Path.from("room")).track("video").subscribe(); const subscribe = await nextStream(pair.client); - if (!subscribe) throw new Error("no SUBSCRIBE was sent"); expect(await subscribe.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(subscribe.reader, VERSION); await refuse(subscribe); @@ -919,7 +877,6 @@ test("an info-only lookup waits for TRACK_STATUS_OK instead of abandoning", asyn const subscriber = new Subscriber({ session }); const info = subscriber.consume(Path.from("room")).track("video").info(); const peer = await nextStream(pair.client); - if (!peer) throw new Error("missing TRACK_STATUS stream"); expect(await peer.reader.u53()).toBe(TrackStatusRequest.id); await TrackStatusRequest.decode(peer.reader, VERSION); @@ -964,7 +921,6 @@ test("SUBSCRIBE_OK's largest is known before any group arrives", async () => { const subscriber = new Subscriber({ session }); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); const peer = await nextStream(pair.client); - if (!peer) throw new Error("missing SUBSCRIBE stream"); expect(await peer.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(peer.reader, VERSION); @@ -1032,7 +988,6 @@ test.each(["acceptance", "refusal"])("returning demand preserves pending setup u installed.close(); }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("missing pending subscribe"); expect(await peer.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(peer.reader, VERSION); await clock.advance(Nano.fromMilli(Milli(6_000))); @@ -1104,7 +1059,6 @@ test("setup abandonment closes before a queued viewer can attach", async () => { session.close(); }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("missing initial subscribe"); expect(await peer.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(peer.reader, VERSION); first.close(); @@ -1129,7 +1083,6 @@ test("early group waits for SUBSCRIBE_OK priority before track acceptance", asyn const subscriber = new Subscriber({ session }); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); const peer = await nextStream(pair.client); - if (!peer) throw new Error("missing SUBSCRIBE stream"); expect(await peer.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(peer.reader, VERSION); @@ -1179,7 +1132,6 @@ test.each([Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22])( delay: { max: null }, }); const peer = await nextStream(pair.client, version); - if (!peer) throw new Error("missing SUBSCRIBE stream"); try { expect(await peer.reader.u53()).toBe(Subscribe.id); expect((await Subscribe.decode(peer.reader, version)).filter).toEqual({ @@ -1240,9 +1192,8 @@ test.each([Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22])( delay: { max: null }, }); const peer = await nextStream(pair.client, version); - if (!peer) throw new Error("missing SUBSCRIBE stream"); const ordered = consumer.ordered(); - let fetch: Awaited> | undefined; + let fetch: Stream | undefined; try { expect(await peer.reader.u53()).toBe(Subscribe.id); const msg = await Subscribe.decode(peer.reader, version); @@ -1267,7 +1218,6 @@ test.each([Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22])( // The reader waits on group 0, which only a FETCH can bring. void ordered.nextGroup().catch(() => {}); fetch = await nextStream(pair.client, version); - if (!fetch) throw new Error("missing FETCH stream"); expect(await fetch.reader.u53()).toBe(Fetch.id); const { type } = await Fetch.decode(fetch.reader, version); // One range for groups 0 and 1, below the live group 2. @@ -1306,13 +1256,11 @@ test("a bounded subscription asks upstream from its start without an end", async }); // The range reaches past the live edge TRACK_STATUS names, so it subscribes. const status = await nextStream(pair.client, version); - if (!status) throw new Error("missing TRACK_STATUS stream"); expect(await status.reader.u53()).toBe(TrackStatusRequest.id); await TrackStatusRequest.decode(status.reader, version); await status.writer.u53(TrackStatusOk.id); await new TrackStatusOk({ largest: { groupId: 5n, objectId: 0n } }).encode(status.writer, version); const peer = await nextStream(pair.client, version); - if (!peer) throw new Error("missing SUBSCRIBE stream"); try { expect(await peer.reader.u53()).toBe(Subscribe.id); const { filter } = await Subscribe.decode(peer.reader, version); @@ -1675,7 +1623,6 @@ test("a more specific unnamed announcement replaces the consumed source", async ); await announced.next(); const broadPeer = await nextStream(pair.client); - if (!broadPeer) throw new Error("no broad publish stream"); await broadPeer.reader.u53(); await RequestOk.decode(broadPeer.reader, VERSION); const held = subscriber.consume(job); @@ -1686,7 +1633,6 @@ test("a more specific unnamed announcement replaces the consumed source", async ); await announced.next(); const specificPeer = await nextStream(pair.client); - if (!specificPeer) throw new Error("no specific publish stream"); await specificPeer.reader.u53(); await RequestOk.decode(specificPeer.reader, VERSION); const fresh = subscriber.consume(job); @@ -1780,7 +1726,6 @@ test("a request overlapping one on its way out waits for the peer to end it", as /** Answer the next SUBSCRIBE_NAMESPACE with REQUEST_OK, carrying `activeCount` when given. */ async function answerCounted(transport: WebTransport, activeCount: number | undefined): Promise { const stream = await nextStream(transport); - if (!stream) throw new Error("no SUBSCRIBE_NAMESPACE was sent"); await stream.reader.u53(); await SubscribeNamespace.decode(stream.reader, VERSION); const parameters = new Parameters(); @@ -1790,17 +1735,9 @@ async function answerCounted(transport: WebTransport, activeCount: number | unde return stream; } -const sessionClosed = (pair: ReturnType) => - Promise.race([ - pair.server.closed, - sleep(Nano.fromMilli(Milli(STREAM_WAIT))).then(() => { - throw new Error("session stayed up"); - }), - ]); - /** The session closes with PROTOCOL_VIOLATION, not a clean code. */ async function violationClosed(pair: ReturnType) { - expect((await sessionClosed(pair)).closeCode).toBe(new ProtocolViolation("").code); + expect((await pair.server.closed).closeCode).toBe(new ProtocolViolation("").code); } const yieldTask = () => yieldNow(); @@ -1916,7 +1853,6 @@ for (const negotiated of [false, true]) { .track("video") .subscribe({ delay: { max: Milli(250) } }); const peer = await nextStream(pair.client); - if (!peer) throw new Error("no subscribe stream"); expect(await peer.reader.u53()).toBe(Subscribe.id); const request = await Subscribe.decode(peer.reader, VERSION); expect(request.maxAge).toBe(negotiated ? 250 : undefined); diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 2c18c414168..ded72ec1d22 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -1,10 +1,10 @@ import { expect, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now } from "@moq/clock"; +import { Instant, Manual, Milli, Nano } from "@moq/clock"; import { ProtocolViolation, StreamCode, StreamError } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; import { hooks } from "../internal.ts"; import { GRACE } from "../ledger.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, driveUntil, manual } from "../mock.ts"; import * as Path from "../path.ts"; import { Reader, Stream } from "../stream.ts"; import { type GroupFlags, Group as GroupMessage } from "./object.ts"; @@ -96,6 +96,7 @@ async function readAll(group: GroupConsumer | undefined): Promise { } test("a group stream that arrives after PUBLISH_DONE is delivered", async () => { + using clock = manual(); const { subscriber, reader, done } = await subscribed(); const first = groupStream(subscriber, 0n); first.write(object("0.0")); @@ -104,17 +105,21 @@ test("a group stream that arrives after PUBLISH_DONE is delivered", async () => await done(TRACK_ENDED, 2n); // QUIC does not order streams, so the second one lands after PUBLISH_DONE. - const started = now(); + const started = clock.now(); const late = groupStream(subscriber, 1n); late.write(object("1.0")); late.finish(); - expect(await readAll(await reader.recvGroup())).toEqual(["0.0"]); - expect(await readAll(await reader.recvGroup())).toEqual(["1.0"]); - expect(await reader.recvGroup()).toBeUndefined(); - expect(await reader.closed).toBeNull(); + const read = (async () => { + expect(await readAll(await reader.recvGroup())).toEqual(["0.0"]); + expect(await readAll(await reader.recvGroup())).toEqual(["1.0"]); + expect(await reader.recvGroup()).toBeUndefined(); + expect(await reader.closed).toBeNull(); + })(); + await driveUntil(clock, read); + await read; // The Stream Count was met, so nothing waited out the grace. - expect(Nano.toMilli(Instant.durationSince(now(), started))).toBeLessThan(GRACE); + expect(Nano.toMilli(Instant.durationSince(clock.now(), started))).toBeLessThan(GRACE); }); test("a group read across PUBLISH_DONE is delivered whole", async () => { diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 100c65142ca..004b9dd8023 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -1,6 +1,5 @@ import { afterEach, expect, mock, onTestFinished, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, sleep, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; import type { Getter } from "@moq/signals"; import type * as Announce from "./announced.ts"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; @@ -22,7 +21,7 @@ import * as Instance from "./instance.ts"; import { hooks } from "./internal.ts"; import * as Lite from "./lite/index.ts"; import { Publisher as LitePublisher } from "./lite/publisher.ts"; -import { createMockTransportPair, textFrame } from "./mock.ts"; +import { createMockTransportPair, manual, settlesWithin, textFrame } from "./mock.ts"; import type { Consumer as OriginConsumer } from "./origin.ts"; import { Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; @@ -53,8 +52,6 @@ function accept( return acceptSession({ transport, url, ...props }); } -const sleepMs = (ms: number) => sleep(Nano.fromMilli(Milli(ms))); - /** * Have every peer refuse announce requests for the rest of the test, the way a relay without * discovery does. Returns how many it has refused so far. @@ -332,7 +329,7 @@ test("integration: lite carries a fractional delay as a whole millisecond", asyn }); test("integration: lite applies initial and updated group bounds", async () => { - hostTime(); + using clock = manual(); const GROUP_COUNT = 6n; const INITIAL_START_GROUP = 1n; const INITIAL_END_GROUP = 3n; // exclusive: groups 1 and 2 @@ -385,8 +382,7 @@ test("integration: lite applies initial and updated group bounds", async () => { delay: { max: Milli(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: GROUP_COUNT } }], }); - const live = subscriber.nextGroup(); - expect(await Promise.race([live, sleepMs(PENDING_ASSERT_MS).then(() => "pending")])).toBe("pending"); + expect(await settlesWithin(subscriber.nextGroup(), clock, Milli(PENDING_ASSERT_MS))).toBe(false); } finally { subscriber.close(); remote.close(); @@ -651,7 +647,7 @@ test("integration: lite draft-06", async () => { test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( "integration: %s demand holds across a subscription's TRACK and SUBSCRIBE", async (protocol) => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(protocol); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -685,7 +681,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( const remote = wireOf(client).consume(Path.from("test")); const track = remote.track("video").subscribe().ordered(); expect(await track.readString()).toBe("hello"); - await sleepMs(50); + await clock.advance(Nano.fromMilli(Milli(50))); // One request, wanted from its subscription on and never let go in between. if (!producer) throw new Error("the track was never answered"); const served = producer; @@ -1427,12 +1423,13 @@ async function runConsumeDedup(protocol: string, version?: number) { server.abort(); } -async function waitUntil(predicate: () => boolean): Promise { - for (let i = 0; i < 200; i++) { - if (predicate()) return; - await sleepMs(5); +/** Wait for `signal` to hold a value that passes `pred`, and return it. */ +async function waitFor(signal: Getter, pred: (value: T) => boolean): Promise { + for (;;) { + const value = signal.peek(); + if (pred(value)) return value; + await signal.changed(); } - throw new Error("condition not met within timeout"); } // Closing the last subscriber to a track tears the wire subscription down, so the publisher stops @@ -1454,12 +1451,12 @@ async function runSubscriberTeardown(protocol: string, version?: number) { expect(await sub.readString()).toBe("hello"); // The publisher now has a live downstream reader for the track. - await waitUntil(() => video.demand().wanted.peek() !== undefined); + await waitFor(video.demand().wanted, (wanted) => wanted !== undefined); // Closing the only subscriber must tear the wire subscription down, so demand drops on the // publisher rather than the relay serving groups to nobody. sub.close(); - await waitUntil(() => video.demand().wanted.peek() === undefined); + await waitFor(video.demand().wanted, (wanted) => wanted === undefined); broadcast.close(); remote.close(); @@ -1468,19 +1465,16 @@ async function runSubscriberTeardown(protocol: string, version?: number) { } test("integration: lite subscriber teardown on last unsubscribe", async () => { - hostTime(); await runSubscriberTeardown(Lite.ALPN_06); }); test("integration: ietf subscriber teardown on last unsubscribe", async () => { - hostTime(); await runSubscriberTeardown(Ietf.ALPN.DRAFT_18); }); // A fetched group can stay open indefinitely (a catalog track, a JSON stream), so abandoning the // fetch must cancel the FETCH stream rather than wait for a stream end that never comes. test("integration: lite fetch teardown when the reader abandons an open group", async () => { - hostTime(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -1498,12 +1492,12 @@ test("integration: lite fetch teardown when the reader abandons an open group", expect(await fetched.readString()).toBe("hello"); // The publisher is now serving the still-open group. - await waitUntil(() => group.demand().wanted.peek()); + await waitFor(group.demand().wanted, (wanted) => wanted); // Abandoning the fetch cancels the FETCH stream, so the publisher stops serving instead of // pumping an open group to a reader that left. fetched.close(); - await waitUntil(() => !group.demand().wanted.peek()); + await waitFor(group.demand().wanted, (wanted) => !wanted); group.finish(); broadcast.close(); @@ -1515,14 +1509,12 @@ test("integration: lite fetch teardown when the reader abandons an open group", // Older drafts have no TRACK stream or SUBSCRIBE_UPDATE, so the demand loop must still tear the // subscription down through the plain stream-close path. test("integration: lite draft-01 subscriber teardown on last unsubscribe", async () => { - hostTime(); await runSubscriberTeardown("", Lite.Version.DRAFT_01); }); // Two subscribers to one track dedupe onto a single wire subscription: closing one keeps it alive // for the other, and only the last close tears it down. test("integration: lite fan-out keeps the upstream until the last subscriber leaves", async () => { - hostTime(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -1539,7 +1531,7 @@ test("integration: lite fan-out keeps the upstream until the last subscriber lea const b = remote.track("video").subscribe().ordered(); expect(await a.readString()).toBe("hello"); expect(await b.readString()).toBe("hello"); - await waitUntil(() => video.demand().wanted.peek() !== undefined); + await waitFor(video.demand().wanted, (wanted) => wanted !== undefined); // Closing one leaves the shared upstream serving the other. a.close(); @@ -1549,7 +1541,7 @@ test("integration: lite fan-out keeps the upstream until the last subscriber lea // The last close tears it down. b.close(); - await waitUntil(() => video.demand().wanted.peek() === undefined); + await waitFor(video.demand().wanted, (wanted) => wanted === undefined); broadcast.close(); remote.close(); @@ -1560,7 +1552,6 @@ test("integration: lite fan-out keeps the upstream until the last subscriber lea // Repeated subscribe/unsubscribe cycles must each tear down and re-open cleanly (the 40-toggle // scenario in the issue), never wedging the shared cache or leaking a subscription. test("integration: lite re-subscribe re-opens the upstream after each teardown", async () => { - hostTime(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -1577,10 +1568,10 @@ test("integration: lite re-subscribe re-opens the upstream after each teardown", video.writeFrame(textFrame(`hello-${i}`)); const sub = remote.track("video").subscribe().ordered(); expect(await sub.readString()).toBe(`hello-${i}`); - await waitUntil(() => video.demand().wanted.peek() !== undefined); + await waitFor(video.demand().wanted, (wanted) => wanted !== undefined); sub.close(); - await waitUntil(() => video.demand().wanted.peek() === undefined); + await waitFor(video.demand().wanted, (wanted) => wanted === undefined); } broadcast.close(); @@ -1592,7 +1583,6 @@ test("integration: lite re-subscribe re-opens the upstream after each teardown", // Coalesced fetches of one open group share a single FETCH stream: closing one keeps it flowing // for the other, and only the last abandon cancels it. test("integration: lite coalesced fetch stays until every reader abandons the open group", async () => { - hostTime(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -1610,7 +1600,7 @@ test("integration: lite coalesced fetch stays until every reader abandons the op const f2 = await remote.track("video").fetchGroup(group.sequence); expect(await f1.readString()).toBe("hello"); expect(await f2.readString()).toBe("hello"); - await waitUntil(() => group.demand().wanted.peek()); + await waitFor(group.demand().wanted, (wanted) => wanted); // Closing one coalesced reader keeps the shared FETCH flowing for the other. f1.close(); @@ -1620,7 +1610,7 @@ test("integration: lite coalesced fetch stays until every reader abandons the op // The last abandon cancels the FETCH. f2.close(); - await waitUntil(() => !group.demand().wanted.peek()); + await waitFor(group.demand().wanted, (wanted) => !wanted); group.finish(); broadcast.close(); @@ -1633,6 +1623,7 @@ test("integration: lite coalesced fetch stays until every reader abandons the op // the demand watch. The frame read in flight across that re-arm must still reach the group. The // window is a few microtasks wide, so the late reader arrives after every delay across it. test("integration: lite fetch re-armed by a late reader keeps every frame", async () => { + using clock = manual(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -1657,8 +1648,9 @@ test("integration: lite fetch re-armed by a late reader keeps every frame", asyn expect(await f2.readString()).toBe("hello"); group.writeFrame(textFrame("more")); - const more = await Promise.race([f2.readString(), sleepMs(500).then(() => "dropped" as const)]); - expect(`${delay}: ${more}`).toBe(`${delay}: more`); + const more = f2.readString(); + expect(`${delay}: ${await settlesWithin(more, clock, Milli(500))}`).toBe(`${delay}: true`); + expect(await more).toBe("more"); f2.close(); group.finish(); @@ -1734,16 +1726,8 @@ test("integration: subscribe to non-existent broadcast", async () => { }); // Resolves once `signal` satisfies `pred`, returning the matching value. -async function waitFor(signal: Getter, pred: (value: T) => boolean): Promise { - for (;;) { - const value = signal.peek(); - if (pred(value)) return value; - await signal.changed(); - } -} - test("integration: a follower waits for a late publisher", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(Lite.ALPN_06); const origin = new OriginProducer(); const clientOrigin = new OriginProducer(); @@ -1764,7 +1748,7 @@ test("integration: a follower waits for a late publisher", async () => { // Nobody publishes this path yet. A blind consume would be reset (see the // "subscribe to non-existent broadcast" test); the handle just stays offline. const watched = clientOrigin.follow(Path.from("late")); - await sleepMs(50); + await clock.advance(Nano.fromMilli(Milli(50))); expect(watched.active.peek()).toBeUndefined(); // The publisher arrives afterwards. @@ -2174,7 +2158,7 @@ test("origin: remote entries retract when the session dies, local ones survive", }); test("origin: one origin on both directions consumes locally and never echoes", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(Lite.ALPN_05); // The client routes both directions through one origin, the FFI default shape. @@ -2217,7 +2201,7 @@ test("origin: one origin on both directions consumes locally and never echoes", // The critical part: the client must NOT re-announce "from-server" back. If it did, the // server's forwarder would insert it as a remote entry in serverSees. Give the wire a // moment, then check the only remote entry the server has is the client's own broadcast. - await sleepMs(50); + await clock.advance(Nano.fromMilli(Milli(50))); expect(wireOf(serverReader).routes(Path.from("from-server"))).toBe(false); watchingShared.close(); @@ -2460,7 +2444,7 @@ test.each([Ietf.ALPN.DRAFT_18])( ); test("origin: a blind request ends with its session, and the next session answers a fresh one", async () => { - hostTime(); + using clock = manual(); withoutDiscovery(); const original = globalThis.WebTransport; const reconnectUrl = new URL("https://example.com/re-request"); @@ -2489,18 +2473,17 @@ test("origin: a blind request ends with its session, and the next session answer const request = clientOrigin.request(Path.from("standing")); try { - await until(() => request.active.peek() !== undefined); - const first = request.active.peek(); + const first = await waitFor(request.active, (b) => b !== undefined); // The answering session dies, and the request it answered ends with it: the next session // is another publisher instance as far as anything here can tell. servers[0]?.session.close(); - await until(() => request.closed.peek() !== undefined); + await Promise.resolve(request.closed); expect(request.active.peek()).toBeUndefined(); - // The next session answers a fresh request. + // The next session answers a fresh request, once the reconnect delay passes. const fresh = clientOrigin.request(Path.from("standing")); - await until(() => fresh.active.peek() !== undefined); + await clock.drive(waitFor(fresh.active, (b) => b !== undefined)); expect(fresh.active.peek()).not.toBe(first); fresh.close(); } finally { @@ -2512,7 +2495,7 @@ test("origin: a blind request ends with its session, and the next session answer }); test("origin: a reactive handle follows announcements across a republish", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(Lite.ALPN_05); const serverOrigin = new OriginProducer(); const clientOrigin = new OriginProducer(); @@ -2525,7 +2508,7 @@ test("origin: a reactive handle follows announcements across a republish", async const watch = clientOrigin.follow(Path.from("show")); // Nothing published yet: the handle waits instead of subscribing blind. - for (let i = 0; i < 5; i++) await sleepMs(1); + await clock.advance(Nano.fromMilli(Milli(5))); expect(watch.active.peek()).toBeUndefined(); // The publish resolves it through the wire. @@ -2551,7 +2534,7 @@ test("origin: a reactive handle follows announcements across a republish", async }); test("origin: overlapping sessions carrying one path fail over", async () => { - hostTime(); + using clock = manual(); // Two live relays announce the same broadcast into one origin, the redundant-relay // shape (and the GOAWAY drain shape, where old and new sessions briefly overlap). const clientOrigin = new OriginProducer(); @@ -2584,7 +2567,7 @@ test("origin: overlapping sessions carrying one path fail over", async () => { // The newer session dies; the older one still carries the path and must keep serving. second.client.abort(); second.server.abort(); - await sleepMs(50); + await clock.advance(Nano.fromMilli(Milli(50))); const remote = await routed(reader, Path.from("redundant")); if (!remote) throw new Error("route black-holed despite a live session"); @@ -2768,6 +2751,7 @@ async function runSessionDeath( version?: number, kill: "death" | "remote" | "local" = "death", ): Promise<[Error | null, Error | null, Position | undefined]> { + using clock = manual(); const pair = createMockTransportPair(protocol); const origin = new OriginProducer(); @@ -2796,10 +2780,8 @@ async function runSessionDeath( else if (kill === "remote") void server.close().catch(() => {}); else pair.server.close({ closeCode: DEATH, reason: "killed" }); const groupEnd = Promise.resolve(group.closed); - const closed = await withTimeout( - Promise.resolve(track.closed), - Nano.fromMilli(Milli(2000)), - "the track never ended", + const closed = await clock.drive( + withTimeout(Promise.resolve(track.closed), Nano.fromMilli(Milli(2000)), "the track never ended"), ); broadcast.close(); @@ -2810,7 +2792,7 @@ async function runSessionDeath( origin.close(); return [ closed, - await withTimeout(groupEnd, Nano.fromMilli(Milli(2000)), "the group never ended"), + await clock.drive(withTimeout(groupEnd, Nano.fromMilli(Milli(2000)), "the group never ended")), hooks.subscriberEnd(track), ]; } @@ -2832,7 +2814,6 @@ for (const [name, protocol, version] of [ // continues past it. for (const kill of ["remote", "local"] as const) { test(`integration: ${name} cancels the track on a ${kill} session close`, async () => { - hostTime(); const [closed, groupEnd, end] = await runSessionDeath(protocol, version, kill); expect(closed).toBeInstanceOf(SessionError); expect((closed as SessionError).code).toBe(SessionCode.Cancel); diff --git a/js/net/src/lite/connection.test.ts b/js/net/src/lite/connection.test.ts index 8e065222c11..6a9b42928f3 100644 --- a/js/net/src/lite/connection.test.ts +++ b/js/net/src/lite/connection.test.ts @@ -1,12 +1,11 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import Qmux from "@moq/qmux"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; import { inspect } from "../connection/stats.ts"; import { SessionCode, SessionError } from "../error.ts"; -import { createMockTransportPair, type MockTransport, textFrame } from "../mock.ts"; +import { createMockTransportPair, type MockTransport, manual, settlesWithin, textFrame } from "../mock.ts"; import { Producer } from "../origin.ts"; import * as Path from "../path.ts"; import { acceptBudget, Stream, Writer } from "../stream.ts"; @@ -102,7 +101,7 @@ async function sendGoaway(server: WebTransport, uri: string): Promise { } test("a lite GOAWAY keeps the session open, and a second one closes it", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_04); const connection = new Connection({ url: new URL("https://relay.example/"), @@ -110,22 +109,14 @@ test("a lite GOAWAY keeps the session open, and a second one closes it", async ( version: Version.DRAFT_04, }); - let closed = false; - void connection.closed.then(() => { - closed = true; - }); - try { await sendGoaway(pair.server, ""); const drain = await connection.draining; expect(drain.uri).toBe(""); - - await sleep(Nano.fromMilli(Milli(20))); - expect(closed).toBe(false); + expect(await settlesWithin(connection.closed, clock, Milli(20))).toBe(false); await sendGoaway(pair.server, "https://other.example/"); - await sleep(Nano.fromMilli(Milli(50))); - expect(closed).toBe(true); + expect(await settlesWithin(connection.closed, clock, Milli(50))).toBe(true); } finally { connection.abort(); } diff --git a/js/net/src/lite/datagram-tracks.test.ts b/js/net/src/lite/datagram-tracks.test.ts index 22df152a2ea..43b84515220 100644 --- a/js/net/src/lite/datagram-tracks.test.ts +++ b/js/net/src/lite/datagram-tracks.test.ts @@ -1,9 +1,8 @@ import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; import { Signal } from "@moq/signals"; import { accept, connect } from "../connection/index.ts"; -import { createMockTransportPair, type MockTransport } from "../mock.ts"; +import { createMockTransportPair, driveUntil, type MockTransport, manual } from "../mock.ts"; import { Producer as Origin } from "../origin.ts"; import * as Path from "../path.ts"; import { sendOrder } from "../priority.ts"; @@ -18,7 +17,7 @@ const path = Path.from("live"); for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { for (const streams of [false, true]) { test(`${alpn}: ${streams ? "same-name kinds" : "datagram-only track"} delivery`, async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); const datagrams = publication.broadcast.createDatagrams("audio", { @@ -58,7 +57,10 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { while (datagrams.priority.peek() !== -9) await datagrams.priority.changed(); datagrams.finish(); track?.finish(); - expect(await reader.recv()).toBeUndefined(); + // The end waits out the grace a late datagram gets. + const end = reader.recv(); + await driveUntil(clock, end); + expect(await end).toBeUndefined(); } finally { reader.close(); remote.close(); @@ -338,7 +340,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { [100, true], ] as const) { test(`${alpn}: a datagram sent right behind its answer arrives (answer ${lag} microtasks late${finish ? ", then the end" : ""})`, async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); const datagrams = publication.broadcast.createDatagrams("audio"); @@ -360,8 +362,14 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { await reader.info(); if (!finish) datagrams.append(undefined, Uint8Array.of(2)); expect((await reader.recv())?.payload).toEqual(Uint8Array.of(1)); - if (finish) expect(await reader.recv()).toBeUndefined(); - else expect((await reader.recv())?.payload).toEqual(Uint8Array.of(2)); + if (finish) { + // The end waits out the grace a late datagram gets. + const end = reader.recv(); + await driveUntil(clock, end); + expect(await end).toBeUndefined(); + } else { + expect((await reader.recv())?.payload).toEqual(Uint8Array.of(2)); + } expect((await client.stats()).datagramsUnrouted).toBe(0); } finally { reader.close(); @@ -378,7 +386,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { // of its track's end. The subscriber routes the datagram before it ends the track. for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { test(`${alpn}: a datagram sent right before its end arrives`, async () => { - hostTime(); + using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); const datagrams = publication.broadcast.createDatagrams("audio"); @@ -397,7 +405,10 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { datagrams.append(undefined, Uint8Array.of(1)); datagrams.finish(); expect((await reader.recv())?.payload).toEqual(Uint8Array.of(1)); - expect(await reader.recv()).toBeUndefined(); + // The end waits out the grace a late datagram gets. + const end = reader.recv(); + await driveUntil(clock, end); + expect(await end).toBeUndefined(); expect((await client.stats()).datagramsUnrouted).toBe(0); } finally { reader.close(); @@ -413,7 +424,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { // with some of it still queued. The end waits for the loop to read the queue empty. for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { test(`${alpn}: a burst sent right before its end arrives past a budget yield`, async () => { - hostTime(); + using clock = manual(); // As many as a datagram track buffers unread, past two receive budgets. const BURST = 64; const source = new Origin(); @@ -438,9 +449,14 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { while (datagrams.priority.peek() !== 5) await datagrams.priority.changed(); for (let i = 0; i < BURST; i++) datagrams.append(undefined, Uint8Array.of(i)); datagrams.finish(); - let count = 0; - while ((await reader.recv()) !== undefined) count++; - expect(count).toBe(BURST); + const counted = (async () => { + let count = 0; + while ((await reader.recv()) !== undefined) count++; + return count; + })(); + // The end waits out the grace a late datagram gets. + await driveUntil(clock, counted); + expect(await counted).toBe(BURST); expect((await client.stats()).datagramsUnrouted).toBe(0); } finally { budget.mockRestore(); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 27a6d4495a6..06bafca36a5 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -1,6 +1,5 @@ import { expect, mock, spyOn, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, sleep, timeout, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; @@ -8,7 +7,7 @@ import { fromTransport, SessionCode, StreamCode, StreamError, toStreamCode } fro import type { Producer as GroupProducer } from "../group.ts"; import { randomHop } from "../hop.ts"; import { hooks } from "../internal.ts"; -import { createMockTransportPair, textFrame } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin, textFrame } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { sendOrder } from "../priority.ts"; @@ -113,7 +112,7 @@ test.each([ [Version.DRAFT_05, false], [Version.DRAFT_06, true], ])("a re-price goes out only where the wire carries cost (version %s)", async (version, sent) => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -130,7 +129,7 @@ test.each([ }, }), }); - const settle = () => sleep(Nano.fromMilli(Milli(10))); + const settle = () => clock.advance(Nano.zero); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); const initial = written.length; @@ -152,7 +151,7 @@ test.each([ test.each([Version.DRAFT_06, Version.DRAFT_07])( "a republish restarts the advertisement (version %s)", async (version) => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -168,7 +167,7 @@ test.each([Version.DRAFT_06, Version.DRAFT_07])( }, }), }); - const settle = () => sleep(Nano.fromMilli(Milli(10))); + const settle = () => clock.advance(Nano.zero); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); const initial = written.length; @@ -207,6 +206,7 @@ async function subscribeEnd( version: Version = Version.DRAFT_05, error?: Error, ): Promise { + using clock = manual(); const pair = createMockTransportPair(version === Version.DRAFT_07 ? ALPN_07_WIP : ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -231,7 +231,7 @@ async function subscribeEnd( // Let the publisher drain this group before the next, so arrival order is the // order given rather than whatever the cache hands over in one batch. A group that // arrives late opens no stream at all, so there is nothing firmer to wait on. - await sleep(Nano.fromMilli(Milli(5))); + await clock.advance(Nano.zero); } if (error) track.finishAt({ group: BigInt(Math.max(-1, ...sequences) + 1), frame: 0 }, error); else track.finish(); @@ -373,6 +373,7 @@ test("lite draft-05: a subscribe update re-ranks the whole subscription", async // A group can outlive the priority it opened with, so an update has to reach the stream that // is already on the wire. Otherwise (say) an active-speaker change waits for the next group. test("lite draft-05: a subscribe update re-ranks a group already on the wire", async () => { + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); @@ -408,11 +409,9 @@ test("lite draft-05: a subscribe update re-ranks a group already on the wire", a await replayUpdate({ priority: 9 }).encode(client.writer, Version.DRAFT_05); while (track.subscription.peek()?.priority !== 9) await track.subscription.changed(); - // The publisher re-ranks from that same signal, so wait on the send order itself rather - // than on the dispatch order between its subscriber and this one. - for (let i = 0; i < 200 && stream.sendOrder === sendOrder({ priority: 1 }); i++) { - await sleep(Nano.fromMilli(Milli(5))); - } + // The publisher re-ranks from that same signal, so let everything it queued run rather + // than depend on the dispatch order between its subscriber and this one. + await clock.advance(Nano.zero); expect(stream.sendOrder).toBe(sendOrder({ priority: 9 })); } finally { @@ -425,7 +424,7 @@ test("lite draft-05: a subscribe update re-ranks a group already on the wire", a // Opening a stream can block on transport capacity, and a subscription listener only sees // later changes, so an update landing in that window would otherwise be lost until the next one. test("lite draft-05: a subscribe update during the stream open still ranks the group", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); @@ -469,9 +468,7 @@ test("lite draft-05: a subscribe update during the stream open still ranks the g if ((await opened.read()).done) throw new Error("publisher never opened the group stream"); opened.releaseLock(); - for (let i = 0; i < 200 && pair.server.sendStreams.uni[0]?.sendOrder !== sendOrder({ priority: 9 }); i++) { - await sleep(Nano.fromMilli(Milli(5))); - } + await clock.advance(Nano.zero); expect(pair.server.sendStreams.uni[0]?.sendOrder).toBe(sendOrder({ priority: 9 })); } finally { @@ -484,6 +481,7 @@ test("lite draft-05: a subscribe update during the stream open still ranks the g // A stalled track piles up open groups, and the signals leak guard throws at 100 subscribers // on one signal, so the subscription is ranked by a single listener rather than one per group. test("lite draft-05: many concurrent groups share one subscription listener", async () => { + using clock = manual(); const count = 120; const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); @@ -526,10 +524,7 @@ test("lite draft-05: many concurrent groups share one subscription listener", as const expected = groups.map((group) => sendOrder({ priority: 9, position: count - 1 - Number(group.sequence) }), ); - for (let i = 0; i < 200; i++) { - if (pair.server.sendStreams.uni.every((stream, at) => stream.sendOrder === expected[at])) break; - await sleep(Nano.fromMilli(Milli(5))); - } + await clock.advance(Nano.zero); expect(pair.server.sendStreams.uni.map((stream) => stream.sendOrder)).toEqual(expected); } finally { @@ -646,9 +641,9 @@ test("lite draft-06: an unchecked track's fetched frames carry their own timesta } }); -// How long a served-subscription test waits for the next group stream before calling the -// publisher idle. Nothing waits this out: it only bounds the read when a group never comes. -const IDLE_MS = 500; +// How long a served-subscription test waits on its manual clock for the next group stream +// before calling the publisher idle. +const IDLE_MS = Milli(500); // One macrotask turn, which drains every microtask queued behind it. Signal notifications // are coalesced per microtask, so this is what lets a just-written group reach the serving @@ -856,15 +851,15 @@ async function servedSubscription( await reader.u53(); // stream type return (await GroupMessage.decode(reader, version)).sequence; }, - // The next group stream the publisher opened, drained, or undefined once it has gone - // idle. A group the publisher dropped then fails an assertion instead of hanging the - // test on a stream that will never arrive. + // Whether the publisher opens another group stream before `clock` passes IDLE_MS. The + // read stays queued, so it takes the next stream: call this last. + opensGroup(clock: Manual): Promise { + return settlesWithin(opened.read(), clock, IDLE_MS); + }, + // The next group stream the publisher opened, drained, or undefined once the session ends. async servedGroup(): Promise { - const next = await timeout(Nano.fromMilli(Milli(IDLE_MS)), opened.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - if (!next || next.done) return undefined; + const next = await opened.read(); + if (next.done) return undefined; const reader = new Reader(next.value, undefined, version); await reader.u53(); // stream type @@ -1493,7 +1488,7 @@ test.each([ ])( "lite %s (reported %s, routed %s): a subscribe that beats its track resolving joins at its newest group", async (version, reported, routed) => { - hostTime(); + using clock = manual(); const sub = await servedSubscription({ version, pending: true, routed }); try { await sub.accept([0n, 3n, 7n], reported); @@ -1504,7 +1499,7 @@ test.each([ sub.serve(9n); } expect(await sub.servedHeader()).toBe(reported ?? 7n); - expect(await sub.servedSequence()).toBeUndefined(); + expect(await sub.opensGroup(clock)).toBe(false); } finally { await sub.close(); } @@ -1516,7 +1511,7 @@ test.each([ test.each([Version.DRAFT_04, Version.DRAFT_05])( "lite %s: a join on a track already holding groups starts at a reported newer group", async (version) => { - hostTime(); + using clock = manual(); const sub = await servedSubscription({ version, prefill: [0n, 3n], reported: 9n }); try { if (version === Version.DRAFT_04) { @@ -1527,7 +1522,7 @@ test.each([Version.DRAFT_04, Version.DRAFT_05])( sub.serve(7n); sub.serve(9n); expect(await sub.servedHeader()).toBe(9n); - expect(await sub.servedSequence()).toBeUndefined(); + expect(await sub.opensGroup(clock)).toBe(false); } finally { await sub.close(); } @@ -1789,7 +1784,7 @@ test("lite draft-06: a burst of updates coalesces before the next group pop", as // Applying one update can itself race the decoder's next message. The serving loop yields a task // before another pop so the decoder can finish the already-delivered update and tighten the cap. test("lite draft-06: a newer update wins before a buffered group backlog drains", async () => { - hostTime(); + using clock = manual(); const sub = await servedSubscription({ version: Version.DRAFT_06, startGroup: 0n, @@ -1826,7 +1821,7 @@ test("lite draft-06: a newer update wins before a buffered group backlog drains" expect(await sub.servedSequence()).toBe(0n); expect(await sub.servedSequence()).toBe(1n); await second; - expect(await sub.servedSequence()).toBeUndefined(); + expect(await sub.opensGroup(clock)).toBe(false); expect(ranges).toHaveBeenCalledTimes(2); } finally { ranges.mockRestore(); @@ -1871,7 +1866,7 @@ test("lite draft-06: scheduling updates apply while SUBSCRIBE_START is blocked", // there rather than draining what is buffered, since nobody is reading the rest. Matches the Rust // publisher's TrackEnd::PeerFin, which drops the in-flight group machines instead of draining. test("lite draft-05: a peer FIN ends serving while the producer is still live", async () => { - hostTime(); + using clock = manual(); const sub = await servedSubscription({ startGroup: 0n }); try { sub.serve(0n); @@ -1882,7 +1877,7 @@ test("lite draft-05: a peer FIN ends serving while the producer is still live", await flush(); sub.serve(1n); - expect(await sub.servedSequence()).toBeUndefined(); + expect(await sub.opensGroup(clock)).toBe(false); } finally { await sub.close(); } @@ -1898,11 +1893,7 @@ test("lite draft-05: a peer FIN interrupts a blocked SUBSCRIBE_START", async () await sub.parked; sub.client.writer.close(); - const stopped = await Promise.race([ - sub.serving.then(() => true), - sleep(Nano.fromMilli(Milli(IDLE_MS))).then(() => false as const), - ]); - expect(stopped).toBe(true); + await sub.serving; expect(resets).toHaveBeenCalledTimes(1); } finally { resets.mockRestore(); @@ -1937,14 +1928,12 @@ test("lite draft-05: teardown unwinds with an undelivered update queued", async // A Rust subscriber feeds this value straight into `track::Producer::finish_at`, which is // exclusive, so an inclusive bound here silently truncates the final group across languages. test("lite draft-05: subscribe end is the exclusive boundary", async () => { - hostTime(); expect((await subscribeEnd([0, 1, 2])).group).toBe(3n); }); // recvGroup is arrival-ordered, so the boundary has to clear the max sequence delivered, // not the last one seen. Otherwise the boundary lands on a group already on the wire. test("lite draft-05: subscribe end clears the max sequence when groups arrive out of order", async () => { - hostTime(); expect((await subscribeEnd([0, 2, 1])).group).toBe(3n); }); @@ -1956,7 +1945,6 @@ test("lite draft-05: subscribe end is 0 when no groups were produced", async () // Lite-07 forwards an errored end's error with its boundary, so the subscriber keeps the history. test("lite draft-07: subscribe end carries the track's error", async () => { - hostTime(); const end = await subscribeEnd([0, 1], Version.DRAFT_07, new StreamError(StreamCode(71))); expect([end.group, end.error]).toEqual([2n, 71]); expect((await subscribeEnd([0, 1], Version.DRAFT_07)).error).toBeUndefined(); @@ -1964,7 +1952,6 @@ test("lite draft-07: subscribe end carries the track's error", async () => { // The boundary clears every produced group even when a sequence was skipped. test("lite draft-07: subscribe end names the final boundary", async () => { - hostTime(); const end = await subscribeEnd([0, 2], Version.DRAFT_07); expect(end.group).toBe(3n); }); @@ -2020,7 +2007,7 @@ test("lite draft-07: subscribe end precedes groups below a declared finish", asy // Before lite-07 an errored end goes out only as the reset at that end: a clean SUBSCRIBE_FINISH // sent early could let the subscriber settle before the reset arrives. test("lite draft-06: an errored end is not declared early", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume()); @@ -2044,14 +2031,7 @@ test("lite draft-06: an errored end is not declared early", async () => { const start = await decodeSubscribeResponse(client.reader, Version.DRAFT_06); expect("start" in start).toBe(true); const pending = decodeSubscribeResponse(client.reader, Version.DRAFT_06); - const early = await Promise.race([ - pending.then( - () => "response", - () => "reset", - ), - sleep(Nano.fromMilli(Milli(20))).then(() => "none"), - ]); - expect(early).toBe("none"); + expect(await settlesWithin(pending, clock, Milli(20))).toBe(false); const second = track.createGroup(1n); second.writeFrame(textFrame("hello")); @@ -2294,6 +2274,7 @@ async function serve( bounds: { startGroup?: bigint; startFrame?: number; endGroup?: bigint; endFrame?: number }, received: Record = {}, ): Promise<{ start?: bigint; end?: bigint; served: Served[] }> { + using clock = manual(); const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume()); @@ -2328,7 +2309,7 @@ async function serve( // Let the publisher drain each group before the next, so the streams arrive in // the order written rather than whatever the cache hands over in one batch. - await sleep(Nano.fromMilli(Milli(5))); + await clock.advance(Nano.zero); } track.finish(); track.close(); @@ -2337,14 +2318,13 @@ async function serve( try { const served: Served[] = []; for (;;) { - // The publisher may simply have nothing more to send, so race the read - // against an idle timeout. Clear the timer either way, and cancel rather - // than release below: releasing with a read still pending would throw. - const next = await timeout(Nano.fromMilli(Milli(50)), reader.read()).catch((error: unknown) => { - if (error instanceof Elapsed) return undefined; - throw error; - }); - if (!next || next.done) break; + // The publisher may simply have nothing more to send, so give the read an idle + // window. Cancel rather than release below: releasing with a read still pending + // would throw. + const read = reader.read(); + if (!(await settlesWithin(read, clock, Milli(50)))) break; + const next = await read; + if (next.done) break; const stream = new Reader(next.value, undefined, Version.DRAFT_06); await stream.u53(); // stream type @@ -2381,7 +2361,6 @@ async function serve( // The response has no per-frame index, so the receiver numbers what it gets from the // GROUP header. Ignoring the requested start would relabel frame 0 as frame N. test("lite draft-06: a subscription starting mid-group skips the head", async () => { - hostTime(); const { served } = await serve({ 0: ["a", "b", "c", "d"] }, { startGroup: 0n, startFrame: 2 }); expect(served).toEqual([{ sequence: 0n, frameStart: 2, payloads: ["c", "d"] }]); }); @@ -2389,7 +2368,6 @@ test("lite draft-06: a subscription starting mid-group skips the head", async () // A start at the group's final frame count is a valid, empty range: FIN, don't reset. // A relay resuming a parked track asks for exactly this. test("lite draft-06: a subscription starting at the end of a group serves it empty", async () => { - hostTime(); const { start, served } = await serve({ 0: ["a", "b"] }, { startGroup: 0n, startFrame: 2 }); expect(start).toBe(0n); expect(served).toEqual([{ sequence: 0n, frameStart: 2, payloads: [] }]); @@ -2397,14 +2375,12 @@ test("lite draft-06: a subscription starting at the end of a group serves it emp // A received tail that ends where it starts is the same valid, empty range. test("lite draft-06: an empty received tail is served empty at its start", async () => { - hostTime(); const { served } = await serve({ 0: [] }, { startGroup: 0n, startFrame: 5 }, { 0: 5 }); expect(served).toEqual([{ sequence: 0n, frameStart: 5, payloads: [] }]); }); // The end bound is inclusive. test("lite draft-06: a subscription capped mid-group stops at the end frame", async () => { - hostTime(); const { served } = await serve( { 0: ["a", "b", "c", "d"] }, { startGroup: 0n, startFrame: 1, endGroup: 0n, endFrame: 2 }, @@ -2414,7 +2390,6 @@ test("lite draft-06: a subscription capped mid-group stops at the end frame", as // The default is the whole group, byte-identical to a draft with no such field. test("lite draft-06: an unbounded subscription serves the whole group", async () => { - hostTime(); const { served } = await serve({ 0: ["a", "b"] }, {}); expect(served).toEqual([{ sequence: 0n, frameStart: 0, payloads: ["a", "b"] }]); }); @@ -2422,7 +2397,6 @@ test("lite draft-06: an unbounded subscription serves the whole group", async () // The frame bounds qualify their own group and nothing else. Without a span like this, // an implementation that caps every group passes just as well. test("lite draft-06: frame bounds apply only to the groups they name", async () => { - hostTime(); const { served } = await serve( { 0: ["a0", "a1", "a2"], 1: ["b0", "b1", "b2"], 2: ["c0", "c1", "c2"] }, { startGroup: 0n, startFrame: 2, endGroup: 2n, endFrame: 0 }, @@ -2438,7 +2412,6 @@ test("lite draft-06: frame bounds apply only to the groups they name", async () // A group below the requested start was never asked for. Serving it also lets // SUBSCRIBE_START name a group below the start, which the draft forbids. test("lite draft-06: groups below the start group are not served", async () => { - hostTime(); const { start, served } = await serve({ 0: ["x"], 1: ["y"], 2: ["z"] }, { startGroup: 1n }); expect(served.map((s) => s.sequence)).toEqual([1n, 2n]); expect(start).toBe(1n); @@ -2446,7 +2419,6 @@ test("lite draft-06: groups below the start group are not served", async () => { // The end group is inclusive; anything past it is outside the subscription. test("lite draft-06: groups past the end group are not served", async () => { - hostTime(); const { served } = await serve({ 0: ["w"], 1: ["x"], 2: ["y"], 3: ["z"] }, { startGroup: 1n, endGroup: 2n }); expect(served.map((s) => s.sequence)).toEqual([1n, 2n]); }); @@ -2455,7 +2427,6 @@ test("lite draft-06: groups past the end group are not served", async () => { // range: a Rust peer feeds it into finish_at, so a truncated value would silently drop // the held-back groups across languages. test("lite draft-06: a capped subscription still reports the track's final boundary", async () => { - hostTime(); const { end } = await serve({ 0: ["w"], 1: ["x"], 2: ["y"], 3: ["z"] }, { startGroup: 1n, endGroup: 2n }); expect(end).toBe(4n); }); @@ -2603,11 +2574,7 @@ test("lite draft-05: a blocked group header is reset when the group expires", as edge.writeFrame({ payload: new TextEncoder().encode("edge"), timestamp: Timestamp.fromMillis(1000) }); edge.finish(); - const resetBeforeRelease = await Promise.race([ - streamReset.then(() => true), - sleep(Nano.fromMilli(Milli(500))).then(() => false as const), - ]); - expect(resetBeforeRelease).toBe(true); + await streamReset; } finally { release(); publisher.close(); @@ -2617,7 +2584,7 @@ test("lite draft-05: a blocked group header is reset when the group expires", as }); test("lite draft-05: a group waiting for a stream slot is dropped when the subscriber leaves", async () => { - hostTime(); + using clock = manual(); const { client, track, freeSlot, outcome, close } = await saturatedGroup(); client.close(); @@ -2628,8 +2595,7 @@ test("lite draft-05: a group waiting for a stream slot is dropped when the subsc // The slot is kept for the next open, never used to send the dropped group. freeSlot(); - const idle = sleep(Nano.fromMilli(Milli(20))).then(() => "pending" as const); - expect(await Promise.race([outcome, idle])).toBe("pending"); + expect(await settlesWithin(outcome, clock, Milli(20))).toBe(false); close(); }); @@ -2639,7 +2605,7 @@ test("lite draft-05: a group waiting for a stream slot is dropped when the subsc // delivered, so dropping them here would strand the tail of every finite track. The FIN // tells the subscriber every group is accounted for, so it waits for the queued group. test("lite draft-05: a group waiting for a stream slot survives the track finishing", async () => { - hostTime(); + using clock = manual(); const { client, track, freeSlot, outcome, close } = await saturatedGroup(); track.finish(); @@ -2653,8 +2619,7 @@ test("lite draft-05: a group waiting for a stream slot survives the track finish // The FIN holds until the queued group is on the wire. const fin = client.reader.closed.then(() => "fin" as const); - const idle = sleep(Nano.fromMilli(Milli(20))).then(() => "pending" as const); - expect(await Promise.race([fin, idle])).toBe("pending"); + expect(await settlesWithin(fin, clock, Milli(20))).toBe(false); freeSlot(); expect(await outcome).toBe("sent"); @@ -2668,7 +2633,7 @@ test("lite draft-05: a group waiting for a stream slot survives the track finish // and `runProbe`'s catch would then close the probe stream for the rest of the // session. Drive the real loop so removing the rounding fails this test. test("runProbe rounds a fractional smoothedRtt instead of killing the stream", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05, { stats: { estimatedSendRate: 1_000_000, smoothedRtt: 12.34 }, }); @@ -2683,7 +2648,8 @@ test("runProbe rounds a fractional smoothedRtt instead of killing the stream", a // task running past the end of the test. const probing = publisher.runProbe(server); try { - const probe = await ProbeMessage.decodeMaybe(client.reader, Version.DRAFT_05); + // The first report waits out the probe interval. + const probe = await clock.drive(ProbeMessage.decodeMaybe(client.reader, Version.DRAFT_05)); expect(probe).toBeDefined(); expect(probe?.rtt).toBe(12); expect(probe?.bitrate).toBe(1_000_000); @@ -2846,7 +2812,7 @@ function unauthorizedResets(resets: { mock: { calls: unknown[][] } }): string[] // Nothing is announced before the grant it would be checked against: an ANNOUNCE_REQUEST that // lands before the setup token is answered waits, then leaves out what the grant excludes. test("lite draft-06: announces wait for the setup grant", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); const grant = new Signal(undefined); @@ -2868,7 +2834,7 @@ test("lite draft-06: announces wait for the setup grant", async () => { }, }), }); - const settle = () => sleep(Nano.fromMilli(Milli(10))); + const settle = () => clock.advance(Nano.zero); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); expect(written.length).toBe(0); @@ -2892,7 +2858,7 @@ test("lite draft-06: announces wait for the setup grant", async () => { // A local close while an announce waits on the setup grant finishes it at once, rather than // holding the close until its deadline. test("lite draft-06: closing while announces wait for the setup grant does not hang", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); const grant = new Signal(undefined); @@ -2912,13 +2878,10 @@ test("lite draft-06: closing while announces wait for the setup grant does not h }), }); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); - await sleep(Nano.fromMilli(Milli(10))); + await clock.advance(Nano.zero); - const drained = await Promise.race([ - publisher.drain().then(() => "drained" as const), - sleep(Nano.fromMilli(Milli(500))).then(() => "hung" as const), - ]); - expect(drained).toBe("drained"); + // Without any time passing. + expect(await settlesWithin(publisher.drain(), clock)).toBe(true); await running; expect(written.length).toBe(0); diff --git a/js/net/src/lite/tail.test.ts b/js/net/src/lite/tail.test.ts index 5689b3c404d..33d8ce053fa 100644 --- a/js/net/src/lite/tail.test.ts +++ b/js/net/src/lite/tail.test.ts @@ -1,11 +1,10 @@ import { describe, expect, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, sleep, timeout } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano } from "@moq/clock"; import { ProtocolViolation, StreamCode, StreamError } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; import { randomHop } from "../hop.ts"; import { hooks } from "../internal.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import * as Path from "../path.ts"; import { Reader, Stream } from "../stream.ts"; import { Timescale } from "../time.ts"; @@ -102,17 +101,6 @@ async function readAll(group: GroupConsumer | undefined): Promise { /** Let every pending microtask run, so a parked read gets a turn without a timer. */ const settle = () => new Promise((resolve) => setImmediate(resolve)); -/** Whether `promise` settles within `ms`. */ -async function settlesWithin(promise: Promise, ms: number): Promise { - return await timeout(Nano.fromMilli(Milli(ms)), promise).then( - () => true, - (error: unknown) => { - if (error instanceof Elapsed) return false; - throw error; - }, - ); -} - describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (version) => { test("the source start waits for SUBSCRIBE_START where it resolves the start", async () => { const { reader, respond } = await subscribed(version, GRACE, { start: { absolute: 2n } }); @@ -261,6 +249,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a subscription ends without waiting once every group is accounted for", async () => { + using clock = manual(); // A max delay far past the test's patience: only the accounting may end it. const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000)); await respond({ start: new SubscribeStart([0n]) }); @@ -272,7 +261,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await fin(); expect((await reader.recvGroup())?.sequence).toBe(1n); - expect(await settlesWithin(reader.recvGroup(), 1000)).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); @@ -305,18 +294,19 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a subscription that served nothing ends at SUBSCRIBE_FINISH", async () => { + using clock = manual(); const { reader, respond, fin } = await subscribed(version, Milli(60_000)); await respond({ finish: new SubscribeFinish(0n) }); await fin(); - expect(await settlesWithin(reader.recvGroup(), 1000)).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); expect(await reader.closed).toBeNull(); expect(hooks.subscriberEnd(reader)).toEqual({ group: 0n, frame: 0 }); }); // lite-05 specified an inclusive end, so there the group costs only its own stream. test(`a group at or past SUBSCRIBE_FINISH ${version === Version.DRAFT_05 ? "is dropped" : "aborts the track"}`, async () => { - hostTime(); + using clock = manual(); const { subscriber, reader, respond } = await subscribed(version); await respond({ start: new SubscribeStart([0n]) }); await respond({ finish: new SubscribeFinish(2n) }); @@ -325,7 +315,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const handled = groupStream(subscriber, 2n).handled; if (version === Version.DRAFT_05) { await handled; - expect(await settlesWithin(Promise.resolve(reader.closed), 50)).toBe(false); + expect(await settlesWithin(Promise.resolve(reader.closed), clock, Milli(50))).toBe(false); } else { // The violation escapes to the connection, which closes the session on it. expect( @@ -339,6 +329,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a floor below SUBSCRIBE_START owes nothing below it", async () => { + using clock = manual(); const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000), { start: { absolute: 1n }, }); @@ -350,12 +341,12 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await fin(); expect((await reader.recvGroup())?.sequence).toBe(3n); - expect(await settlesWithin(reader.recvGroup(), 1000)).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); test("a lowered floor owes the groups it newly asked for", async () => { - hostTime(); + using clock = manual(); const maxDelay = Milli(60_000); const { subscriber, respond, update, fin } = await subscribed(version, maxDelay, { start: { absolute: 3n }, @@ -380,7 +371,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await respond({ finish: new SubscribeFinish(4n) }); await fin(); // Long enough for a subscription that owed nothing more to have ended. - await sleep(Nano.fromMilli(Milli(50))); + await clock.advance(Nano.fromMilli(Milli(50))); // QUIC does not order streams, so the lowered groups land after the FIN. for (const sequence of [1n, 2n]) { @@ -404,7 +395,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // lite-05 specified an inclusive end, and @moq/net 0.1.3 to 0.1.9 sent one, so there an end // below a received group only costs the early boundary. test(`a SUBSCRIBE_FINISH below a group already received ${version === Version.DRAFT_05 ? "finishes clean" : "aborts the track"}`, async () => { - hostTime(); + using clock = manual(); const { subscriber, reader, respond, fin } = await subscribed(version); await respond({ start: new SubscribeStart([0n]) }); const group = groupStream(subscriber, 3n); @@ -414,7 +405,8 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver if (version === Version.DRAFT_05) { await fin(); - expect(await reader.closed).toBeNull(); + // Groups 0 and 1 never arrive, so the subscription ends once their grace runs out. + expect(await clock.drive(Promise.resolve(reader.closed))).toBeNull(); } else { expect(await reader.closed).toBeInstanceOf(ProtocolViolation); } @@ -422,6 +414,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { + using clock = manual(); const { subscriber, reader, respond, fin } = await subscribed(Version.DRAFT_07, Milli(60_000)); await respond({ start: new SubscribeStart([0n]) }); for (const sequence of [0n, 2n]) { @@ -436,18 +429,19 @@ test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { expect((await reader.recvGroup())?.sequence).toBe(0n); expect((await reader.recvGroup())?.sequence).toBe(2n); - expect(await settlesWithin(reader.recvGroup(), 1000)).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); test("lite-07 settles a dropped range without grace", async () => { + using clock = manual(); const { reader, respond, fin } = await subscribed(Version.DRAFT_07, Milli(60_000)); await respond({ start: new SubscribeStart([0n]) }); await respond({ finish: new SubscribeFinish(3n) }); await respond({ drop: new SubscribeDrop({ start: 0n, end: 2n, error: 0 }) }); await fin(); - expect(await settlesWithin(reader.recvGroup(), 1000)).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); expect(await reader.closed).toBeNull(); expect(hooks.subscriberEnd(reader)).toEqual({ group: 3n, frame: 0 }); }); diff --git a/js/net/src/lite/track_stream.test.ts b/js/net/src/lite/track_stream.test.ts index 889f01a5c17..d29ae60ef5f 100644 --- a/js/net/src/lite/track_stream.test.ts +++ b/js/net/src/lite/track_stream.test.ts @@ -2,11 +2,10 @@ // SUBSCRIBE is answered, and the publisher keeps the track wanted until the subscriber closes it. import { describe, expect, spyOn, test } from "bun:test"; -import { Elapsed, Milli, Nano, timeout } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Milli } from "@moq/clock"; import { SessionCode } from "../error.ts"; import { randomHop } from "../hop.ts"; -import { createMockTransportPair } from "../mock.ts"; +import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Stream } from "../stream.ts"; @@ -21,17 +20,6 @@ import { Subscriber } from "./subscriber.ts"; import { TrackInfo, Track as TrackMessage } from "./track.ts"; import { ALPN_05, Version } from "./version.ts"; -/** Whether `promise` settles within `ms`. */ -async function settlesWithin(promise: Promise, ms: number): Promise { - return await timeout(Nano.fromMilli(Milli(ms)), promise).then( - () => true, - (error: unknown) => { - if (error instanceof Elapsed) return false; - throw error; - }, - ); -} - describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (version) => { /** A subscriber whose publisher the test plays by hand, up to the SUBSCRIBE. */ async function subscribing() { @@ -57,10 +45,10 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver } test("a subscription holds its TRACK stream until the SUBSCRIBE is answered", async () => { - hostTime(); + using clock = manual(); const { subscriber, reader, track, sub } = await subscribing(); const fin = track.reader.done(); - expect(await settlesWithin(fin, 50)).toBe(false); + expect(await settlesWithin(fin, clock, Milli(50))).toBe(false); await encodeSubscribeResponse(sub.writer, { start: new SubscribeStart([0n]) }, version); expect(await fin).toBe(true); @@ -70,10 +58,10 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a subscription that ends unanswered closes its TRACK stream", async () => { - hostTime(); + using clock = manual(); const { subscriber, reader, track } = await subscribing(); const fin = track.reader.done(); - expect(await settlesWithin(fin, 50)).toBe(false); + expect(await settlesWithin(fin, clock, Milli(50))).toBe(false); reader.close(); expect(await fin).toBe(true); @@ -117,7 +105,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test.each(["FIN", "reset"] as const)( "an answered TRACK stream keeps the track wanted until the requester's %s", async (close) => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -140,11 +128,11 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await TrackInfo.decode(client.reader, version); expect(await client.reader.done()).toBe(true); if (!producer) throw new Error("the track was never answered"); - expect(await settlesWithin(Promise.resolve(producer.closed), 50)).toBe(false); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(50))).toBe(false); if (close === "FIN") client.writer.close(); else client.writer.reset(new Error("gone")); - expect(await settlesWithin(Promise.resolve(producer.closed), 1000)).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -178,6 +166,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test.each(["FIN", "reset"] as const)( "a requester's %s while TRACK_INFO is blocked lets the track go", async (close) => { + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -215,7 +204,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver if (close === "FIN") client.writer.close(); else client.writer.reset(new Error("gone")); - expect(await settlesWithin(Promise.resolve(producer.closed), 1000)).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -225,7 +214,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver ); test("one TRACK stream closing leaves the track wanted while another holds it", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -255,10 +244,10 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver expect(producers.length).toBe(1); first.writer.close(); - expect(await settlesWithin(released(0), 50)).toBe(false); + expect(await settlesWithin(released(0), clock, Milli(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(released(0), 1000)).toBe(true); + expect(await settlesWithin(released(0), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -267,7 +256,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a TRACK stream after the cached lookup was let go holds the track again", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -293,15 +282,15 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const first = await open(); await TrackInfo.decode(first.reader, version); first.writer.close(); - expect(await settlesWithin(released(0), 1000)).toBe(true); + expect(await settlesWithin(released(0), clock, Milli(1000))).toBe(true); const second = await open(); await TrackInfo.decode(second.reader, version); expect(producers.length).toBe(2); - expect(await settlesWithin(released(1), 50)).toBe(false); + expect(await settlesWithin(released(1), clock, Milli(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(released(1), 1000)).toBe(true); + expect(await settlesWithin(released(1), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -326,6 +315,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test.each(["TRACK", "FETCH"])( "%s requesters leaving before the answer let the track go once the last one leaves", async (kind) => { + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -344,7 +334,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // The handler still gets an open track, and the answer lets it go. const producer = request.accept({ timescale: Timescale.MILLI }); - expect(await settlesWithin(Promise.resolve(producer.closed), 1000)).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -353,6 +343,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver ); test.each(["TRACK", "FETCH"])("a lost session lets go of a %s still waiting on the answer", async (kind) => { + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -367,7 +358,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver pair.server.close(); // The handler still gets an open track, and the answer lets it go. const producer = request.accept({ timescale: Timescale.MILLI }); - expect(await settlesWithin(Promise.resolve(producer.closed), 1000)).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -375,7 +366,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test("a TRACK stream after every earlier one left an unanswered lookup holds the track again", async () => { - hostTime(); + using clock = manual(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -391,13 +382,13 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // The next TRACK stream joins the request still waiting on the application. const second = await requester(pair, publisher, "TRACK"); - expect(await settlesWithin(wireOf(broadcast).requested(), 50)).toBe(false); + expect(await settlesWithin(wireOf(broadcast).requested(), clock, Milli(50))).toBe(false); const producer = request.accept({ timescale: Timescale.MILLI }); await TrackInfo.decode(second.reader, version); - expect(await settlesWithin(Promise.resolve(producer.closed), 50)).toBe(false); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(Promise.resolve(producer.closed), 1000)).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); publisher.close(); broadcast.close(); diff --git a/js/net/src/mock.ts b/js/net/src/mock.ts index 726a9341e8f..7e9e91f4491 100644 --- a/js/net/src/mock.ts +++ b/js/net/src/mock.ts @@ -4,6 +4,7 @@ * Creates paired client/server transports connected by in-memory streams. */ +import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import { Consumer as BroadcastConsumer } from "./broadcast.ts"; import type { TransportStats } from "./connection/stats.ts"; import type { Frame } from "./group.ts"; @@ -15,6 +16,54 @@ export function textFrame(text: string, timestamp = Timestamp.now()): Frame { return { payload: new TextEncoder().encode(text), timestamp }; } +/** A Manual clock installed in this realm until disposed, for a test that moves time itself. */ +export function manual(): Manual & Disposable { + const clock = new Manual(); + const installed = clock.install(); + return Object.assign(clock, { [Symbol.dispose]: () => installed.close() }); +} + +/** Whether `work` settles once everything pending has run and `clock` has advanced `duration`. */ +export async function settlesWithin( + work: PromiseLike, + clock: Manual, + duration = Milli.zero, +): Promise { + let settled = false; + const done = () => { + settled = true; + }; + Promise.resolve(work).then(done, done); + await clock.advance(Nano.fromMilli(duration)); + return settled; +} + +/** + * Moves `clock` a millisecond at a time, each step after a host turn, until `until` holds or settles. + * + * `Manual.drive` fires the next deadline after one drain, which skips past work waiting on a host + * task the clock can't see, such as a read through the host's streams or the IETF handshake's + * dynamic import. A regression fails within ten mocked seconds. + */ +export async function driveUntil(clock: Manual, until: (() => boolean) | PromiseLike): Promise { + let done: () => boolean; + if (typeof until === "function") { + done = until; + } else { + let settled = false; + const stop = () => { + settled = true; + }; + Promise.resolve(until).then(stop, stop); + done = () => settled; + } + for (let i = 0; i < 10_000 && !done(); i++) { + await yieldNow(); + await clock.advance(Nano.fromMilli(Milli(1))); + } + if (!done()) throw new Error("not done within ten mocked seconds"); +} + /** * A broadcast as a session hands it out: no producer, so it ends once no handle holds it, * which is how a test sees the origin let go of an answer. diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index b354df703ae..a450f8df459 100644 --- a/js/net/src/tail.test.ts +++ b/js/net/src/tail.test.ts @@ -1,11 +1,11 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { type Installed, Instant, Manual, Milli, Nano, now } from "@moq/clock"; +import { type Installed, Instant, Manual, Milli, Nano } from "@moq/clock"; import { Once } from "@moq/signals"; import { accept, connect } from "./connection/index.ts"; import * as Ietf from "./ietf/index.ts"; import { GRACE as TAIL_GRACE_MS } from "./ledger.ts"; import * as Lite from "./lite/index.ts"; -import { createMockTransportPair, textFrame } from "./mock.ts"; +import { createMockTransportPair, driveUntil, manual, textFrame } from "./mock.ts"; import { Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; import { Tail } from "./tail.ts"; @@ -87,6 +87,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06])( // declared an end past the groups it produced, and the Stream Count lets the subscriber stop // waiting for streams at once. test.each([Ietf.ALPN.DRAFT_22])("%s: END_OF_TRACK carries the declared end", async (alpn) => { + using clock = manual(); const { video, reader, close } = await session(alpn); try { video.writeFrame(textFrame("0")); @@ -95,15 +96,17 @@ test.each([Ietf.ALPN.DRAFT_22])("%s: END_OF_TRACK carries the declared end", asy video.finishAt({ group: 4n, frame: 0 }); video.writeFrame(textFrame("1")); video.writeFrame(textFrame("2")); - const ended = now(); + const ended = clock.now(); video.finish(); video.close(); - expect(await readAll(reader)).toEqual(["1", "2"]); + const read = readAll(reader); + await driveUntil(clock, reader.closed); + // Every counted stream arrived, so nothing waited out the grace. + expect(Nano.toMilli(Instant.durationSince(clock.now(), ended))).toBeLessThan(TAIL_GRACE_MS); + expect(await read).toEqual(["1", "2"]); expect(await reader.closed).toBeNull(); expect(await reader.finished()).toEqual({ group: 4n, frame: 0 }); - // Every counted stream arrived, so nothing waited out the grace. - expect(Nano.toMilli(Instant.durationSince(now(), ended))).toBeLessThan(TAIL_GRACE_MS); } finally { close(); } diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 9f118d4974f..67ff21fdbc0 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -1,6 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep, Wall, yieldNow } from "@moq/clock"; -import { hostTime } from "@moq/clock/test"; +import { Manual, Milli, Nano, Wall, yieldNow } from "@moq/clock"; import { race } from "@moq/signals"; import { ProtocolViolation, StreamCode, StreamError, TimestampMismatch, TooFarBehind } from "./error.ts"; import type { Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; @@ -2451,7 +2450,6 @@ test("end is group 0 for an empty track and undefined after an abort", async () }); test("readFrame does not livelock when a sole group finishes before the next arrives", async () => { - hostTime(); const producer = new TrackProducer("test"); const track = producer.subscribe().ordered(); @@ -2461,8 +2459,8 @@ test("readFrame does not livelock when a sole group finishes before the next arr const g0 = producer.appendGroup(); g0.finish(); - // The next group arrives via a macrotask; if the reader livelocks on microtasks it never runs. - void sleep(Nano.fromMilli(Milli(10))).then(() => { + // The next group arrives in a later host task; if the reader livelocks on microtasks it never runs. + void yieldNow().then(() => { const g1 = producer.appendGroup(); g1.writeFrame(textFrame("hello")); g1.finish(); diff --git a/quest/m1/mock-clock-tests/README.md b/quest/m1/mock-clock-tests/README.md index 2fa5130cb94..cb6adc75796 100644 --- a/quest/m1/mock-clock-tests/README.md +++ b/quest/m1/mock-clock-tests/README.md @@ -38,6 +38,5 @@ before starting, since tests land and move. ## Required -- [js/net tests run on a mocked clock](/quest/m1/mock-clock-tests/js-net.md) - about 120 js/net tests stop waiting on real time, through their shared helpers - [Other JS tests run on a mocked clock](/quest/m1/mock-clock-tests/js-rest.md) - hang's `settle(20)`, publish's fanout helpers, and the rest of JS - [moq-relay's mesh tests run on a mocked clock](/quest/m1/mock-clock-tests/rs-relay.md) - the relay's multi-relay quiet windows and settle sleeps diff --git a/quest/m1/mock-clock-tests/js-net.md b/quest/m1/mock-clock-tests/js-net.md deleted file mode 100644 index 4210074bf4e..00000000000 --- a/quest/m1/mock-clock-tests/js-net.md +++ /dev/null @@ -1,35 +0,0 @@ -# [L] js/net tests run on a mocked clock - -## Goal - -About 120 `js/net` tests stop proving nothing happened by waiting, sleeping -to settle, or asserting on elapsed time. See the -[epic](/quest/m1/mock-clock-tests/README.md) for the rules. - -## Plan - -Start with the shared helpers, which cover most of them: - -- `nextUni` (`src/ietf/publisher.test.ts`) and `nextStream` - (`src/ietf/subscriber.test.ts`) resolve `undefined` when their timeout - runs out. -- `closeCode` (`src/ietf/malformed.test.ts`) races `Bun.sleep(50)`. -- `settlesWithin` (`src/lite/track_stream.test.ts`). - -Then the rest, by file, as of 2026-11-06: `ietf/publisher` 31, -`ietf/subscriber` 22, `lite/publisher` 19, `ietf/malformed` 10, -`ietf/join` 9, `lite/tail` 8, `lite/track_stream` 7, `ietf/goaway` 2, and -one each in `auth`, `connection/connect`, `connection/reload`, -`ietf/datagram`, `ietf/request_stream`, `ietf/tail`, `lite/connection`, -`tail`, and `track`. - -The guard's bare `hostTime();` opt-outs are the tests it saw a real timer -fire in, by file: `lite/publisher` 26, `integration` 15, `ietf/publisher` 9, -`connection/reload` 8, `lite/track_stream` 6, `ietf/malformed` 5, -`lite/datagram-tracks` 4, `ietf/join` 4, `ietf/datagram` 4, `lite/tail` 3, -`ietf/goaway` 3, `connection/connect` 2, `ietf/subscriber` 2, and one each in -`track`, `lite/connection`, `ietf/request_stream`, and -`auth`. The scan above also counts waits whose timer rarely fires, so convert -both; `git grep -n "hostTime();$" -- js/net` lists what remains. - -Public API: none. Wire: none. From 46ff1453cc61f16dd7c14fc86d543105f3c8c3c2 Mon Sep 17 00:00:00 2001 From: quest fixer Date: Sat, 7 Nov 2026 14:31:35 -0800 Subject: [PATCH 3/3] docs: remove completed js-net quest prerequisite --- quest/m1/mock-clock-tests/manual-drive-host-io.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/quest/m1/mock-clock-tests/manual-drive-host-io.md b/quest/m1/mock-clock-tests/manual-drive-host-io.md index accf9711756..75a4b92ce81 100644 --- a/quest/m1/mock-clock-tests/manual-drive-host-io.md +++ b/quest/m1/mock-clock-tests/manual-drive-host-io.md @@ -42,7 +42,3 @@ Also settled: before driving. Public API: none beyond `@moq/clock`'s test helpers, if any. Wire: none. - -## Required - -- [js/net tests run on a mocked clock](/quest/m1/mock-clock-tests/js-net.md) - adds the `driveUntil` callers this replaces