diff --git a/js/hang/src/container/consumer.startup.test.ts b/js/hang/src/container/consumer.startup.test.ts index b8ac21339ea..d0100600206 100644 --- a/js/hang/src/container/consumer.startup.test.ts +++ b/js/hang/src/container/consumer.startup.test.ts @@ -1,14 +1,14 @@ -import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; -import { Micro, Milli } from "@moq/clock"; +import { expect, onTestFinished, spyOn, test } from "bun:test"; +import { Manual, Micro, Milli, Nano } from "@moq/clock"; import { type Group, Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; -// Drain the in-memory readers and their continuations without advancing mocked time. -const flush = () => new Promise((resolve) => setImmediate(resolve)); - function setup(maxDelay = 100) { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); + // Drain the in-memory readers and their continuations without moving time. + const flush = () => clock.advance(Nano.zero); const track = new Track.Producer("video"); const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), { format: new Format("video"), @@ -31,10 +31,10 @@ function setup(maxDelay = 100) { await reading; } finally { warn.mockRestore(); - jest.useRealTimers(); + installed.close(); } }); - return { track, consumer, results, warn }; + return { track, consumer, results, warn, flush }; } // Each item as "gap <µs>+<µs>", "@<µs>" for a frame, or "end @<µs>". @@ -61,7 +61,7 @@ for (const emptySuccessor of [false, true]) { test.each([0, 100])( `Consumer starts across a hole after an empty reset (empty successor: ${emptySuccessor}, maxDelay: %s)`, async (maxDelay) => { - const { track, results, warn } = setup(maxDelay); + const { track, results, warn, flush } = setup(maxDelay); const stale = track.createGroup(16); await flush(); if (emptySuccessor) { @@ -91,7 +91,7 @@ for (const emptySuccessor of [false, true]) { } test("Consumer preserves a declared marker before its first media across a hole", async () => { - const { track, results, warn } = setup(); + const { track, results, warn, flush } = setup(); const marker = track.createGroup(16); write(marker, 0, true); marker.finish(); @@ -109,7 +109,7 @@ test("Consumer preserves a declared marker before its first media across a hole" }); test.each([false, true])("Consumer still waits for a gap after media (playhead reset: %s)", async (reset) => { - const { track, consumer, results, warn } = setup(1000); + const { track, consumer, results, warn, flush } = setup(1000); const first = track.createGroup(16); write(first, 0); first.finish(); diff --git a/js/net/src/connection/connect.test.ts b/js/net/src/connection/connect.test.ts index aeef7bb808a..5ccd92cb3bd 100644 --- a/js/net/src/connection/connect.test.ts +++ b/js/net/src/connection/connect.test.ts @@ -1,4 +1,4 @@ -import { expect, jest, spyOn, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { Manual, Milli, Nano, sleep } from "@moq/clock"; import { ConnectTimeout, SessionCode, SessionError } from "../error.ts"; import * as Ietf from "../ietf/index.ts"; @@ -300,7 +300,8 @@ test("connect without a signal still works", async () => { // A session-level stream failure promises an authoritative session close, even when the // browser publishes that close after the reset-only fallback would otherwise fire. test("SETUP preserves a delayed session close code", async () => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const closed = Promise.withResolvers(); let localCloses = 0; const transport = { @@ -319,10 +320,7 @@ test("SETUP preserves a delayed session close code", async () => { (cause: unknown) => cause, ); try { - // Drain the finite async setup chain before advancing the mocked clock. - for (let i = 0; i < 64; i++) await Promise.resolve(); - jest.advanceTimersByTime(1_000); - for (let i = 0; i < 64; i++) await Promise.resolve(); + await clock.advance(Nano.fromMilli(Milli(1_000))); expect(localCloses).toBe(0); closed.resolve({ closeCode: SessionCode.Unauthorized, reason: "unauthorized" }); const cause = await result; @@ -331,7 +329,7 @@ test("SETUP preserves a delayed session close code", async () => { } finally { closed.resolve({ closeCode: 0, reason: "test cleanup" }); await result; - jest.useRealTimers(); + installed.close(); } }); diff --git a/js/net/src/connection/forward.test.ts b/js/net/src/connection/forward.test.ts index 58e39cdc479..518e3436086 100644 --- a/js/net/src/connection/forward.test.ts +++ b/js/net/src/connection/forward.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, jest, spyOn, test } from "bun:test"; +import { type Installed, Manual, Milli, Nano } from "@moq/clock"; import { Once } from "@moq/signals"; import * as Announce from "../announced.ts"; import { AuthSession } from "../auth_session.ts"; @@ -14,19 +15,28 @@ import { forwardAnnounced } from "./forward.ts"; const LINGER = 2000; +let clock: Manual; +let installed: Installed; + beforeEach(() => { - jest.useFakeTimers(); + clock = new Manual(); + installed = clock.install(); spyOn(console, "warn").mockImplementation(() => {}); }); afterEach(() => { - jest.useRealTimers(); + installed.close(); jest.restoreAllMocks(); }); -/** Drain the reactive microtasks; timers only move through `jest.advanceTimersByTime`. */ -async function settle() { - for (let i = 0; i < 64; i++) await Promise.resolve(); +/** Drain the reactive work without moving time. */ +function settle(): Promise { + return clock.advance(Nano.zero); +} + +/** Move time forward, draining the reactive work at each deadline on the way. */ +function advance(ms: number): Promise { + return clock.advance(Nano.fromMilli(Milli(ms))); } /** @@ -47,6 +57,9 @@ class FakeSession { /** Whether each request is synced as it opens, as one with no initial set to wait for is. */ syncedAtOnce = false; + /** Called as the forwarder closes a request, before its stream can wind down. */ + onClose?: () => void; + closed: Promise; #die!: (reason: Error | null) => void; @@ -68,6 +81,11 @@ class FakeSession { this.requests.push({ scope: scope.text, hidden: options?.hidden, stream }); if (this.syncedAtOnce) stream.synced(); const consumer = stream.consume(); + const close = consumer.close.bind(consumer); + consumer.close = () => { + this.onClose?.(); + close(); + }; // The last reader leaving cancels the request, as a session's does. closeUnwanted(stream); return consumer; @@ -157,22 +175,16 @@ test("a watch opens its request, and the request closes once the linger expires" // Unwatching keeps the request open for the linger, so a watcher rebuilt in that window reuses it. watch.close(); - await settle(); - jest.advanceTimersByTime(LINGER - 1); - await settle(); + await advance(LINGER - 1); expect(session.open()).toEqual(["room/**"]); const again = origin.announced(Path.Pattern.subtree(Path.from("room"))); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual(["room/**"]); expect(session.requests.length).toBe(1); again.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual([]); // Closing it on purpose is not a discovery failure. expect(origin.discovery.peek()).toBe(true); @@ -192,13 +204,16 @@ test("a watch arriving as the linger expires opens a fresh request", async () => await settle(); // The expiry closes the old request, and the next watch lands before its stream winds down. - jest.advanceTimersByTime(LINGER); - const again = origin.announced(Path.Pattern.subtree(Path.from("room"))); - await settle(); + let again: Announce.Consumer | undefined; + session.onClose = () => { + again ??= origin.announced(Path.Pattern.subtree(Path.from("room"))); + }; + await advance(LINGER); + expect(again).toBeDefined(); expect(session.requests.length).toBe(2); expect(session.open()).toEqual(["room/**"]); - again.close(); + again?.close(); session.die(); origin.close(); }); @@ -253,9 +268,7 @@ test("a follower is a watch on its path", async () => { expect(request.active.peek()).toBeDefined(); request.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual([]); session.die(); @@ -295,18 +308,14 @@ test("a narrower watch rides an open broader request and keeps it open", async ( // The broader watch leaves, but its request stays open for the narrower one, so no request // takes its routes over and nothing restarts. broad.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual(["a/**"]); expect(wireOf(origin).routes(Path.from("a/b/x"))).toBe(true); expect(events).toEqual(["start a/b/x"]); // Once nothing beneath it is watched, it lingers out. narrow.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual([]); expect(wireOf(origin).routes(Path.from("a/b/x"))).toBe(false); @@ -330,20 +339,15 @@ test("a narrower request stays open until the broader one covering it goes", asy const events = record(broad); await settle(); narrow.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual(["a/b/**", "a/**"]); expect(wireOf(origin).routes(Path.from("a/b/x"))).toBe(true); expect(events).toEqual(["start a/b/x"]); // Once the broader request lingers out, the narrower one it held follows. broad.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); + await advance(LINGER); expect(session.open()).toEqual([]); expect(wireOf(origin).routes(Path.from("a/b/x"))).toBe(false); @@ -378,14 +382,10 @@ test("an exclusive session closes every request beneath a broader one before it // The narrower watch rides the broader request from here on. broad.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual(["a/**"]); narrow.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual([]); expect(session.requests.map(({ scope }) => scope)).toEqual(["a/b/**", "a/c/**", "a/**"]); @@ -604,16 +604,12 @@ test("a scoped origin narrows a root watch to its disjoint literal heads", async // nothing. let inside = origin.announced(Path.Pattern.subtree(Path.from("room/alice/chat"))); const outside = origin.announced(Path.Pattern.subtree(Path.from("elsewhere"))); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual(["room/**"]); // With nothing open above it, a watch inside a head asks for itself. inside.close(); - await settle(); - jest.advanceTimersByTime(LINGER); - await settle(); + await advance(LINGER); expect(session.open()).toEqual([]); inside = origin.announced(Path.Pattern.subtree(Path.from("room/alice/chat"))); await settle(); diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 690ed2a3c03..f627896e771 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -1,4 +1,4 @@ -import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; +import { expect, onTestFinished, spyOn, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; @@ -1470,6 +1470,7 @@ test("an advertisement carries its epoch only once negotiated", async () => { test.each([true, false])( "an epoch change advertises the new epoch before withdrawing the old (negotiated: %p)", async (negotiated) => { + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { epoch: negotiated }); const streams = accepted(pair.client); @@ -1479,7 +1480,7 @@ test.each([true, false])( broadcast.announce({ epoch: first }); void pub.runPublishNamespaces(); - const old = await take(streams); + const old = await take(clock, streams); expect(await old.reader.u53()).toBe(PublishNamespace.id); expect((await PublishNamespace.decode(old.reader, VERSION, EPOCH)).params.epoch).toBe( negotiated ? first : undefined, @@ -1490,12 +1491,12 @@ test.each([true, false])( broadcast.announce({ ...broadcast.route, epoch: second }); const withdrawn = watch(old.reader.done()); - const next = await take(streams); + const next = await take(clock, streams); expect(await next.reader.u53()).toBe(PublishNamespace.id); expect((await PublishNamespace.decode(next.reader, VERSION, EPOCH)).params.epoch).toBe( negotiated ? second : undefined, ); - await flush(); + await clock.advance(Nano.zero); expect(withdrawn.state).toBe(negotiated ? "pending" : "rejected"); await acceptPublishNamespace(next); @@ -1508,6 +1509,7 @@ test.each([true, false])( /** On a SUBSCRIBE_NAMESPACE stream, another epoch is one NAMESPACE and no NAMESPACE_DONE. */ test("a solicited namespace takes another epoch as one NAMESPACE and no NAMESPACE_DONE", async () => { + using clock = manual(); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { requiresSolicitation: true, epoch: true }); try { @@ -1533,7 +1535,7 @@ test("a solicited namespace takes another epoch as one NAMESPACE and no NAMESPAC expect(await entry()).toMatchObject({ suffix: Path.from("mine"), params: { epoch: second } }); const more = watch(subscription.reader.u53()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); subscription.close(); } finally { @@ -1641,25 +1643,11 @@ test("EPOCH on a request without MoQ Epoch is a protocol violation", async () => origin.close(); }); -/** Let every pending promise chain run without letting a faked timer fire. */ -async function flush() { - for (let i = 0; i < 20; i++) await new Promise((resolve) => setImmediate(resolve)); -} - -/** Advance faked time in steps, letting the loop react between them as it would in real time. */ -async function advance(ms: number, step = 50) { - for (let elapsed = 0; elapsed < ms; elapsed += step) { - jest.advanceTimersByTime(step); - await flush(); - } -} - -/** Advance faked time until `done` holds, failing once `limit` has passed without it. */ -async function advanceUntil(done: () => boolean, limit: number, step = 50) { +/** Advance time in steps until `done` holds, failing once `limit` has passed without it. */ +async function advanceUntil(clock: Manual, done: () => boolean, limit: number, step = 50) { for (let elapsed = 0; !done(); elapsed += step) { if (elapsed >= limit) throw new Error(`still waiting after ${limit}ms`); - jest.advanceTimersByTime(step); - await flush(); + await clock.advance(Nano.fromMilli(Milli(step))); } } @@ -1696,8 +1684,8 @@ function accepted(transport: WebTransport): Stream[] { } /** Take the next stream the publisher opened, failing if it has not opened one. */ -async function take(queue: Stream[]): Promise { - await flush(); +async function take(clock: Manual, queue: Stream[]): Promise { + await clock.advance(Nano.zero); const stream = queue.shift(); if (!stream) throw new Error("expected the publisher to open a stream"); return stream; @@ -1717,9 +1705,10 @@ async function readUpdate(stream: Stream): Promise { return (await PublishNamespaceUpdate.decode(stream.reader, VERSION)).update; } -/** A clustered publisher on fake time, with every stream it opens collected. */ +/** A clustered publisher on a manual clock, with every stream it opens collected. */ function clustered(requiresSolicitation = false, auth?: Tokens) { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const self: Hop = HopSchema.parse(7n); const peer: Hop = HopSchema.parse(9n); const pair = createMockTransportPair(ALPN.DRAFT_18); @@ -1727,9 +1716,9 @@ function clustered(requiresSolicitation = false, auth?: Tokens) { const streams = accepted(pair.client); const close = () => { origin.close(); - jest.useRealTimers(); + installed.close(); }; - return { self, pair, pub, origin, streams, close }; + return { clock, self, pair, pub, origin, streams, close }; } const VIA: Hop = HopSchema.parse(3n); @@ -1742,13 +1731,13 @@ const OTHER: Hop = HopSchema.parse(5n); * parameter, so leaving it out would leave the peer holding the old price. */ test("a price change on a held namespace is one REQUEST_UPDATE, not a withdrawal", async () => { - const { self, pub, origin, streams, close } = clustered(); + const { clock, self, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); expect(await acceptClustered(stream)).toEqual({ hops: [VIA, self], cost: 4n }); broadcast.announce({ hops: [VIA], cost: 8n }); @@ -1761,7 +1750,7 @@ test("a price change on a held namespace is one REQUEST_UPDATE, not a withdrawal // Still the one request, still open: nothing was withdrawn or advertised again. const more = watch(stream.reader.done()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1770,13 +1759,13 @@ test("a price change on a held namespace is one REQUEST_UPDATE, not a withdrawal }); test("a hop path change behind the same publisher is one REQUEST_UPDATE carrying HOP_PATH", async () => { - const { self, pub, origin, streams, close } = clustered(); + const { clock, self, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA, MID], cost: 4n }); @@ -1784,7 +1773,7 @@ test("a hop path change behind the same publisher is one REQUEST_UPDATE carrying await acceptPublishNamespace(stream); const more = watch(stream.reader.done()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1800,7 +1789,7 @@ test.each([ ["a hop path and cost change", [VIA, MID], 8n], ["a first-hop change", [OTHER], 4n], ] as const)("a solicited namespace takes %s as one NAMESPACE and no NAMESPACE_DONE", async (_, hops, cost) => { - const { self, pair, pub, origin, close } = clustered(true); + const { clock, self, pair, pub, origin, close } = clustered(true); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); @@ -1829,7 +1818,7 @@ test.each([ }); const more = watch(subscription.reader.u53()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); subscription.close(); } finally { @@ -1842,13 +1831,13 @@ test.each([ * change does: withdrawing it would make the namespace briefly vanish downstream. */ test("a first-hop change is one REQUEST_UPDATE carrying HOP_PATH, not a withdrawal", async () => { - const { self, pub, origin, streams, close } = clustered(); + const { clock, self, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [OTHER], cost: 4n }); @@ -1856,7 +1845,7 @@ test("a first-hop change is one REQUEST_UPDATE carrying HOP_PATH, not a withdraw await acceptPublishNamespace(stream); const more = watch(stream.reader.done()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1928,14 +1917,14 @@ function carriedTokens() { */ test("swapping a route's token is one REQUEST_UPDATE carrying it", async () => { const tokens = new Tokens(); - const { pub, origin, streams, close } = clustered(false, tokens); + const { clock, pub, origin, streams, close } = clustered(false, tokens); const { sent, restore } = carriedTokens(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n, auth: tokens.issue("first") }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); expect(sent).toEqual(["first"]); @@ -1953,18 +1942,18 @@ test("swapping a route's token is one REQUEST_UPDATE carrying it", async () => { /** A token another session issued is never carried, so swapping between two sends nothing. */ test("a foreign route token is not carried", async () => { const foreign = new Tokens(); - const { pub, origin, streams, close } = clustered(false, new Tokens()); + const { clock, pub, origin, streams, close } = clustered(false, new Tokens()); const { sent, restore } = carriedTokens(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n, auth: foreign.issue("first") }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA], cost: 4n, auth: foreign.issue("second") }); const more = watch(stream.reader.u53()); - await flush(); + await clock.advance(Nano.zero); expect(more.state).toBe("pending"); expect(sent).toEqual([undefined]); } finally { @@ -1976,19 +1965,19 @@ test("a foreign route token is not carried", async () => { /** REQUEST_UPDATE cannot name a token on a request that had none, so the request restarts. */ test("naming a token on an unnamed request makes it again", async () => { const tokens = new Tokens(); - const { pub, origin, streams, close } = clustered(false, tokens); + const { clock, pub, origin, streams, close } = clustered(false, tokens); const { sent, restore } = carriedTokens(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const old = await take(streams); + const old = await take(clock, streams); await acceptClustered(old); broadcast.announce({ hops: [VIA], cost: 4n, auth: tokens.issue("first") }); expect(await old.reader.done().catch(error)).toMatchObject({ code: StreamCode.Cancel }); - await acceptClustered(await take(streams)); + await acceptClustered(await take(clock, streams)); expect(sent).toEqual([undefined, "first"]); } finally { restore(); @@ -1999,7 +1988,7 @@ test("naming a token on an unnamed request makes it again", async () => { /** Closing a route's token drops it from the request, which REQUEST_UPDATE cannot do. */ test("closing a route's token makes its request again without it", async () => { const tokens = new Tokens(); - const { pub, origin, streams, close } = clustered(false, tokens); + const { clock, pub, origin, streams, close } = clustered(false, tokens); const { sent, restore } = carriedTokens(); try { const broadcast = origin.createBroadcast(Path.from("mine")); @@ -2007,12 +1996,12 @@ test("closing a route's token makes its request again without it", async () => { broadcast.announce({ hops: [VIA], cost: 4n, auth: token }); void pub.runPublishNamespaces(); - const old = await take(streams); + const old = await take(clock, streams); await acceptClustered(old); token.close(); expect(await old.reader.done().catch(error)).toMatchObject({ code: StreamCode.Cancel }); - await acceptClustered(await take(streams)); + await acceptClustered(await take(clock, streams)); expect(sent).toEqual(["first", undefined]); } finally { restore(); @@ -2021,21 +2010,21 @@ test("closing a route's token makes its request again without it", async () => { }); test("a republish withdraws the PUBLISH_NAMESPACE and advertises again", async () => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { const broadcastPublication = origin.createBroadcast(Path.from("mine")); const broadcast = broadcastPublication.broadcast; broadcastPublication.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const old = await take(streams); + const old = await take(clock, streams); await acceptClustered(old); republish(origin, broadcast); // Draft-18+ withdraws by cancelling the request, never a FIN. expect(await old.reader.done().catch(error)).toMatchObject({ code: StreamCode.Cancel }); - const next = await take(streams); + const next = await take(clock, streams); expect(await acceptClustered(next)).toMatchObject({ cost: 4n }); } finally { close(); @@ -2082,13 +2071,13 @@ test.each([ ["waits out its retry interval", 10_000n], ["that forbids retrying is never re-offered", 0n], ])("a refused update %s", async (_, retryInterval) => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA], cost: 8n }); @@ -2099,18 +2088,18 @@ test.each([ expect(await stream.reader.done().catch(error)).toMatchObject({ code: StreamCode.Cancel }); // Well past our own backoff, but inside the interval the peer asked for. - await advance(9_000); + await clock.advance(Nano.fromMilli(Milli(9_000))); expect(streams).toHaveLength(0); if (retryInterval === 0n) { - await advance(20_000); + await clock.advance(Nano.fromMilli(Milli(20_000))); expect(streams).toHaveLength(0); return; } // Past the interval, the next backoff (at most its ceiling) brings it back. - await advanceUntil(() => streams.length > 0, 6_500); - const fresh = await take(streams); + await advanceUntil(clock, () => streams.length > 0, 6_500); + const fresh = await take(clock, streams); expect(await acceptClustered(fresh)).toMatchObject({ cost: 8n }); } finally { close(); @@ -2123,7 +2112,7 @@ test.each([ * instead of ending. */ test("a refused update whose peer closes the request keeps the loop running", async () => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); @@ -2132,7 +2121,7 @@ test("a refused update whose peer closes the request keeps the loop running", as failed = err; }); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA], cost: 8n }); @@ -2140,9 +2129,9 @@ test("a refused update whose peer closes the request keeps the loop running", as await declinePublishNamespace(stream, 1n); stream.close(); - await advanceUntil(() => streams.length > 0 || failed !== undefined, 10_000); + await advanceUntil(clock, () => streams.length > 0 || failed !== undefined, 10_000); expect(failed).toBeUndefined(); - const fresh = await take(streams); + const fresh = await take(clock, streams); expect(await acceptClustered(fresh)).toMatchObject({ cost: 8n }); } finally { close(); @@ -2154,13 +2143,13 @@ test("a refused update whose peer closes the request keeps the loop running", as * without reading it: a change landing while one waits for its answer goes out after. */ test("a change while an update is unanswered waits for its answer", async () => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA], cost: 8n }); @@ -2168,12 +2157,12 @@ test("a change while an update is unanswered waits for its answer", async () => broadcast.announce({ hops: [VIA], cost: 12n }); const second = watch(stream.reader.u53()); - await advance(1_000); + await clock.advance(Nano.fromMilli(Milli(1_000))); expect(second.state).toBe("pending"); expect(streams).toHaveLength(0); await acceptPublishNamespace(stream); - await flush(); + await clock.advance(Nano.zero); expect(second.state).toBe("resolved"); expect(second.value).toBe(PublishNamespaceUpdate.id); expect((await PublishNamespaceUpdate.decode(stream.reader, VERSION)).update).toEqual({ @@ -2192,23 +2181,23 @@ test("a change while an update is unanswered waits for its answer", async () => * on a backoff instead of a stream per turn of the loop. */ test("an advertisement the peer keeps ending comes back on a growing backoff", async () => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { origin.createBroadcast(Path.from("mine")).announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - let stream = await take(streams); + let stream = await take(clock, streams); for (const wait of [100, 200, 400, 800]) { await acceptClustered(stream); stream.writer.close(); - await flush(); + await clock.advance(Nano.zero); // Just short of the wait, nothing has been offered yet. - await advance(wait - 50); + await clock.advance(Nano.fromMilli(Milli(wait - 50))); expect(streams).toHaveLength(0); - await advanceUntil(() => streams.length > 0, 10_000); - stream = await take(streams); + await advanceUntil(clock, () => streams.length > 0, 10_000); + stream = await take(clock, streams); } } finally { close(); @@ -2220,28 +2209,28 @@ test("an advertisement the peer keeps ending comes back on a growing backoff", a * request is dropped and the namespace comes back on a fresh one. */ test("an unanswered update drops the request and re-offers the namespace fresh", async () => { - const { pub, origin, streams, close } = clustered(); + const { clock, pub, origin, streams, close } = clustered(); try { const broadcast = origin.createBroadcast(Path.from("mine")); broadcast.announce({ hops: [VIA], cost: 4n }); void pub.runPublishNamespaces(); - const stream = await take(streams); + const stream = await take(clock, streams); await acceptClustered(stream); broadcast.announce({ hops: [VIA], cost: 8n }); await readUpdate(stream); const reset = watch(stream.reader.u53()); - await advance(9_900); + await clock.advance(Nano.fromMilli(Milli(9_900))); expect(reset.state).toBe("pending"); expect(streams).toHaveLength(0); // The timeout resets the request, then the retry offers it on a new one. - await advance(100); + await clock.advance(Nano.fromMilli(Milli(100))); expect(reset.state).toBe("rejected"); - await advanceUntil(() => streams.length > 0, 200); - const fresh = await take(streams); + await advanceUntil(clock, () => streams.length > 0, 200); + const fresh = await take(clock, streams); expect(await acceptClustered(fresh)).toMatchObject({ cost: 8n }); } finally { close(); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index e03d3879706..2b328e42979 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -1,5 +1,5 @@ import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Manual, Milli, Nano } from "@moq/clock"; import { Once } from "@moq/signals"; import type * as announce from "../announced.ts"; import * as Epoch from "../epoch.ts"; @@ -892,7 +892,8 @@ test("SUBSCRIBE_OK's largest is known before any group arrives", async () => { }); test.each(["acceptance", "timeout"])("returning demand preserves pending setup until %s", async (outcome) => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const pair = createMockTransportPair(ALPN.DRAFT_18); const session = new NativeSession(pair.server, VERSION, true); const subscriber = new Subscriber({ session }); @@ -932,7 +933,7 @@ test.each(["acceptance", "timeout"])("returning demand preserves pending setup u return request; }); const first = broadcast.track("video").subscribe(); - // Restore real timers even if an injection promise outlives the test. + // Restore the ambient clock even if an injection promise outlives the test. onTestFinished(() => { captured.mockRestore(); unwantedSpy.mockRestore(); @@ -941,13 +942,13 @@ test.each(["acceptance", "timeout"])("returning demand preserves pending setup u returned?.close(); broadcast.close(); session.close(); - jest.useRealTimers(); + 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); - jest.advanceTimersByTime(6_000); + await clock.advance(Nano.fromMilli(Milli(6_000))); first.close(); await resumed.promise; if (!returned) throw new Error("demand did not return"); @@ -964,7 +965,7 @@ test.each(["acceptance", "timeout"])("returning demand preserves pending setup u expect(await info).toMatchObject({ priority: 127 - 128 }); expect(returned.closed.peek()).toBeUndefined(); } else { - jest.advanceTimersByTime(4_000); + await clock.advance(Nano.fromMilli(Milli(4_000))); expect(await info).toBeInstanceOf(Error); expect(((await info) as Error).message).toContain("request timed out after 10000ms"); } diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 4dbdb494cd3..41f92bc88c1 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -1,5 +1,5 @@ -import { afterEach, expect, jest, mock, spyOn, test } from "bun:test"; -import { Milli, Nano } from "@moq/clock"; +import { afterEach, expect, mock, onTestFinished, spyOn, test } from "bun:test"; +import { Manual, Milli, Nano } from "@moq/clock"; import type { Getter } from "@moq/signals"; import type * as Announce from "./announce.ts"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; @@ -2280,6 +2280,9 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { for (const method of ["request", "follow"] as const) { test(`${alpn}: a ${method} outlives the listing it resolved through`, async () => { + const clock = new Manual(); + const installed = clock.install(); + onTestFinished(() => installed.close()); const run = LitePublisher.prototype.runAnnounce; let started = 0; let ended = 0; @@ -2318,12 +2321,8 @@ for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { // The listing leaves. Its announce request stays open for the request beneath it rather // than handing the route to a narrower one, so the instance never changes. - jest.useFakeTimers(); listing.close(); - for (let i = 0; i < 64; i++) await new Promise((resolve) => setImmediate(resolve)); - jest.advanceTimersByTime(2000); - jest.useRealTimers(); - await sleep(20); + await clock.advance(Nano.fromMilli(Milli(2000))); expect([started, ended]).toEqual([1, 0]); expect(request.closed.peek()).toBeUndefined(); expect(request.active.peek()).toBe(front); @@ -2332,12 +2331,9 @@ for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { track?.close(); // Once the request goes too, the announce request lingers out. - jest.useFakeTimers(); request.close(); - for (let i = 0; i < 64; i++) await new Promise((resolve) => setImmediate(resolve)); - jest.advanceTimersByTime(2000); - jest.useRealTimers(); - await until(() => ended === 1); + await clock.advance(Nano.fromMilli(Milli(2000))); + expect(ended).toBe(1); broadcast.close(); await serving; diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 2527f300ca9..e634a42e56c 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -1,4 +1,4 @@ -import { expect, jest, mock, spyOn, test } from "bun:test"; +import { expect, mock, spyOn, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; @@ -2905,21 +2905,10 @@ test("lite draft-07 reports the source's largest position past what a relay hold } }); -async function settleControls(): Promise { - await new Promise((resolve) => { - const channel = new MessageChannel(); - channel.port1.onmessage = () => { - channel.port1.close(); - channel.port2.close(); - resolve(); - }; - channel.port2.postMessage(null); - }); -} - for (const version of [Version.DRAFT_03, Version.DRAFT_04, Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { test(`Report consumes PROBE targets and observes their FIN (${version})`, async () => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const pair = createMockTransportPair(ALPN_05, { stats: { estimatedSendRate: 1_000_000, smoothedRtt: 12 } }); const publisher = new Publisher(pair.server, version, randomHop()); const client = await Stream.open(pair.client, { version }); @@ -2930,13 +2919,11 @@ for (const version of [Version.DRAFT_03, Version.DRAFT_04, Version.DRAFT_05, Ver const serving = publisher.runProbe(server); try { await new ProbeMessage({ bitrate: 4_000_000, rtt: 20 }).encode(client.writer, version); - await settleControls(); - jest.advanceTimersByTime(100); - await settleControls(); + await clock.advance(Nano.fromMilli(Milli(100))); expect((await ProbeMessage.decode(client.reader, version)).bitrate).toBe(1_000_000); expect(reset).not.toHaveBeenCalled(); client.writer.close(); - await settleControls(); + await clock.advance(Nano.zero); expect(close).toHaveBeenCalled(); } finally { client.close(); @@ -2946,13 +2933,15 @@ for (const version of [Version.DRAFT_03, Version.DRAFT_04, Version.DRAFT_05, Ver await serving; reset.mockRestore(); close.mockRestore(); - jest.useRealTimers(); + installed.close(); } }); } for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { test(`malformed SUBSCRIBE_UPDATE closes the session after request setup (${version})`, async () => { + const clock = new Manual(); + const installed = clock.install(); const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const broadcast = publish(origin, Path.from("test")); @@ -2967,10 +2956,10 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { server, ); try { - await settleControls(); + await clock.advance(Nano.zero); // The complete zero-length update cannot hold its required fields. await client.writer.write(new Uint8Array([0])); - await settleControls(); + await clock.advance(Nano.zero); expect(close.mock.calls.some(([info]) => info?.closeCode === SessionCode.ProtocolViolation)).toBe(true); } finally { client.close(); @@ -2983,6 +2972,7 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { pair.client.close(); await serving; close.mockRestore(); + installed.close(); } }); } diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 638ccaa7bce..91bc02e6ead 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -1,4 +1,4 @@ -import { expect, jest, spyOn, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { type Getter, Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; @@ -1092,7 +1092,8 @@ test.each([ ["lite-07 subscribe waiting on the TRACK_INFO", Version.DRAFT_07, false], ["lite-05 subscribe waiting on a stream slot for the TRACK", Version.DRAFT_05, true], ] as const)("a %s that times out leaves nothing behind", async (_, version, parked) => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession(parked ? [0] : []); const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); @@ -1101,7 +1102,7 @@ test.each([ await opened(0); if (!parked) await streams[0].reading; - jest.advanceTimersByTime(SUBSCRIBE_SETUP_TIMEOUT_MS); + await clock.advance(Nano.fromMilli(Milli(SUBSCRIBE_SETUP_TIMEOUT_MS))); await track.closed; if (parked) streams[0].release(); @@ -1121,13 +1122,14 @@ test.each([ } finally { subscriber.close(); warn.mockRestore(); - jest.useRealTimers(); + installed.close(); } }); // The SUBSCRIBE stream can open after the deadline too; it is reset without carrying a SUBSCRIBE. test("a lite subscribe that times out waiting on a stream slot for the SUBSCRIBE sends nothing on it", async () => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession([1]); const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); @@ -1137,11 +1139,11 @@ test("a lite subscribe that times out waiting on a stream slot for the SUBSCRIBE await streams[0].reading; // TRACK_INFO lands halfway, so the SUBSCRIBE open's own deadline is still ahead when the // setup deadline fires. - jest.advanceTimersByTime(SUBSCRIBE_SETUP_TIMEOUT_MS / 2); + await clock.advance(Nano.fromMilli(Milli(SUBSCRIBE_SETUP_TIMEOUT_MS / 2))); await answerTrackInfo(streams[0]); await opened(1); - jest.advanceTimersByTime(SUBSCRIBE_SETUP_TIMEOUT_MS / 2); + await clock.advance(Nano.fromMilli(Milli(SUBSCRIBE_SETUP_TIMEOUT_MS / 2))); await track.closed; streams[1].release(); @@ -1150,14 +1152,15 @@ test("a lite subscribe that times out waiting on a stream slot for the SUBSCRIBE } finally { subscriber.close(); warn.mockRestore(); - jest.useRealTimers(); + installed.close(); } }); // A SUBSCRIBE write blocked on flow control may never let the setup settle, so the deadline // lets go of the held TRACK stream without waiting for it. test("a lite subscribe whose SUBSCRIBE write stalls past the deadline closes its TRACK stream", async () => { - jest.useFakeTimers(); + const clock = new Manual(); + const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession([], [1]); const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); @@ -1168,13 +1171,13 @@ test("a lite subscribe whose SUBSCRIBE write stalls past the deadline closes its await answerTrackInfo(streams[0]); await (await opened(1)).writing; - jest.advanceTimersByTime(SUBSCRIBE_SETUP_TIMEOUT_MS); + await clock.advance(Nano.fromMilli(Milli(SUBSCRIBE_SETUP_TIMEOUT_MS))); await track.closed; await streams[0].aborted; } finally { subscriber.close(); warn.mockRestore(); - jest.useRealTimers(); + installed.close(); } }); diff --git a/quest/m0/test-flakes-2/README.md b/quest/m0/test-flakes-2/README.md index 095b1197167..c76d5928ec6 100644 --- a/quest/m0/test-flakes-2/README.md +++ b/quest/m0/test-flakes-2/README.md @@ -52,4 +52,3 @@ Public API: none. Wire: none. - [IETF22 fallback](/quest/m0/test-flakes-2/ietf22-fallback.md) - an IETF22 browser viewer follows a fallback within the media lane's bound, keeping its session and its audio - [Swapped Rust to JS Opus](/quest/m0/test-flakes-2/swapped-js-opus.md) - the `rust-swapped -> js` interop cell stops timing out under load - [JS host-task yields follow the clock](/quest/m0/test-flakes-2/js-host-yields.md) - `Budget` and `nextTask` yield through the injected clock, so `Manual` tests stop racing them -- [Fake timers to Manual](/quest/m0/test-flakes-2/fake-timers.md) - the remaining bun fake-timer tests run on the `Manual` clock diff --git a/quest/m0/test-flakes-2/fake-timers.md b/quest/m0/test-flakes-2/fake-timers.md deleted file mode 100644 index 7e146bad187..00000000000 --- a/quest/m0/test-flakes-2/fake-timers.md +++ /dev/null @@ -1,20 +0,0 @@ -# [M] JS tests drive time through Manual - -## Goal - -The remaining `@moq/net` and `@moq/hang` tests that use bun's fake timers run -on the `Manual` clock instead, so host-task yields cannot race them: forward, -the ietf and lite publisher and subscriber tests, integration, connect, and -hang's consumer startup. - -## Plan - -Follows [moq-dev/moq#6988](https://github.com/moq-dev/moq/pull/6988), which -made `Budget` yield through the clock and moved three tests. Bun's fake -timers cannot see a yield, so these pass today only because nothing yields -at the wrong moment. Each converted test installs its `Manual` clock and -restores the ambient clock when it finishes, as the existing `Manual` tests -do, so no fake clock leaks into the next test. Prove each converted test -still fails when its behavior breaks, and that it passes with `Budget` forced to yield on every call. - -Public API: none. diff --git a/test/audio-quality/clients/js/src/probe.test.ts b/test/audio-quality/clients/js/src/probe.test.ts index 9df2a49b35f..2ba93d3f3ab 100644 --- a/test/audio-quality/clients/js/src/probe.test.ts +++ b/test/audio-quality/clients/js/src/probe.test.ts @@ -1,8 +1,7 @@ -import { expect, jest, mock, test } from "bun:test"; +import { expect, mock, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { Effect, Signal } from "@moq/signals"; import type MoqWatch from "@moq/watch/element"; -import { drain } from "../../../../../js/clock/src/host.ts"; import { Observed } from "../../../../../js/net/src/util/observed.ts"; // This test has no audio graph. Vite supplies this loader in the real page. @@ -10,7 +9,6 @@ mock.module("./tap-worklet.ts?worklet", () => ({ default: async () => "" })); const { probe } = await import("./probe.ts"); test("audio-only sampling holds probe demand until its final RTT sample", async () => { - jest.useFakeTimers(); const clock = new Manual(); const installed = clock.install(); const network = new Observed<{ rtt: Milli } | undefined>(undefined); @@ -31,7 +29,6 @@ test("audio-only sampling holds probe demand until its final RTT sample", async } as unknown as MoqWatch; const measurement = probe(watch); try { - await drain(); await clock.advance(Nano.fromMilli(Milli(250))); expect(measurement.drain().map((sample) => sample.rtt)).toEqual([12]); await measurement.finish(); @@ -42,6 +39,5 @@ test("audio-only sampling holds probe demand until its final RTT sample", async } finally { producer.close(); installed.close(); - jest.useRealTimers(); } });