Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion doc/lib/js/clock.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ Use it for dates, rather than measuring elapsed time. A Rust wall-time
boundary must convert its units explicitly. A new `Manual` starts at instant
zero and 2025-01-01 UTC. `await advance()` moves both readings through each due
timer deadline, draining tasks between deadlines, including timers those tasks
re-arm before the target. `jump()` moves straight to the target and fires due
re-arm before the target. `yieldNow()` waits for a later host task, giving the
host's other work a turn without ordering it; a `Manual` clock moves time only
once every pending yield has resumed, so a loop that yields mid-work never sees
a later time. `jump()` moves straight to the target and fires due
timers late without draining, modeling a stalled event loop. `stepWall()` changes
only wall time. `fire()` waits for a timer
to be armed, even by a later host task such as I/O, then advances exactly to the
Expand Down
2 changes: 2 additions & 0 deletions js/clock/api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,6 @@ export function sleepUntil(at: Instant, options?: {
export function timeout<T>(duration: Nano, operation: PromiseLike<T>): Promise<T>;

export function wall(): Wall;

export function yieldNow(): Promise<void>;
```
3 changes: 3 additions & 0 deletions js/clock/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ export type Backend = {
origin(): number;
// `ref: false` must not keep the host process alive.
arm(at: number, ready: () => void, ref: boolean): () => void;
// Call `ready` from a later host task, after every already-queued microtask. Tasks from
// other sources, such as I/O, may still run after it.
task(ready: () => void): void;
};
18 changes: 10 additions & 8 deletions js/clock/src/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,20 @@ export const host: Backend = {
if (timer !== undefined) clearTimeout(timer);
};
},
};

// A host task drains every already-queued microtask, including promise chains;
// counting Promise.resolve() turns would impose an arbitrary depth limit.
export function drain(): Promise<void> {
return new Promise((resolve) => {
task(ready) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Message ports schedule a task without the nested timer's minimum delay.
const channel = new MessageChannel();
channel.port1.onmessage = () => {
channel.port1.close();
channel.port2.close();
resolve();
ready();
};
channel.port2.postMessage(null);
});
},
};

// A host task drains every already-queued microtask, including promise chains;
// counting Promise.resolve() turns would impose an arbitrary depth limit.
export function drain(): Promise<void> {
return new Promise((resolve) => host.task(resolve));
}
16 changes: 16 additions & 0 deletions js/clock/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
timeout,
Wall,
wall,
yieldNow,
} from "./index.ts";

const installs: Installed[] = [];
Expand Down Expand Up @@ -112,6 +113,21 @@ test("advance drains arbitrarily deep microtasks and newly due timers", async ()
expect(done).toBe(true);
});

for (const driver of ["advance", "fire"] as const) {
test(`${driver} waits out a chain of host-task yields before moving time`, async () => {
const clock = manual();
void sleep(Nano(10));
const seen: number[] = [];
void (async () => {
for (let i = 0; i < 3; i++) await yieldNow();
seen.push(now());
})();
if (driver === "advance") await clock.advance(Nano(10));
else expect<number>(await clock.fire()).toBe(10);
expect(seen).toEqual([0]);
});
}

test("a sleep stays on its creation clock and abort releases it", async () => {
const first = manual();
let done = false;
Expand Down
2 changes: 1 addition & 1 deletion js/clock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Wall } from "./types.ts";

export type { Installed } from "./ambient.ts";
export { Manual } from "./manual.ts";
export { Elapsed, Interval, interval, MissedTickBehavior, now, sleep, sleepUntil, timeout } from "./timer.ts";
export { Elapsed, Interval, interval, MissedTickBehavior, now, sleep, sleepUntil, timeout, yieldNow } from "./timer.ts";
export { Instant, Micro, Milli, Nano, Second, Wall } from "./types.ts";

/** Read the installed clock's wall time in Unix milliseconds. */
Expand Down
16 changes: 14 additions & 2 deletions js/clock/src/manual.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type Installed, install } from "./ambient.ts";
import type { Backend } from "./backend.ts";
import { drain } from "./host.ts";
import { drain, host } from "./host.ts";
import { Instant, Nano, Wall } from "./types.ts";

type Timer = { at: number; order: number; index: number; ready: () => void };
Expand All @@ -20,6 +20,7 @@ export class Manual {
#order = 0;
#revision = 0;
#fired = 0;
#tasks = 0;
#driving = false;
#advancing = false;
#armed?: () => void;
Expand All @@ -38,6 +39,15 @@ export class Manual {
this.#remove(timer);
};
},
// Yields stay real host tasks, so the host's other work still gets a turn, but the clock counts them.
task: (ready) => {
this.#tasks++;
this.#revision++;
host.task(() => {
this.#tasks--;
ready();
});
},
};

/** Install this clock in the current realm until the returned handle closes. */
Expand Down Expand Up @@ -67,7 +77,7 @@ export class Manual {
}
}

/** Advance through each due deadline, draining tasks before continuing to the target. */
/** Advance through each due deadline, draining tasks and pending yields before continuing to the target. */
async advance(duration: Nano): Promise<void> {
if (this.#driving) throw new Error("time driver already pending");
this.#driving = true;
Expand Down Expand Up @@ -131,6 +141,8 @@ export class Manual {
for (;;) {
const revision = this.#revision;
await drain();
// A yield armed while draining is still queued: time must not pass a yielding loop.
if (this.#tasks > 0) continue;
if (target === undefined) {
if (stop?.()) return;
// Select fire's target in the same turn that readies its first timer.
Expand Down
6 changes: 6 additions & 0 deletions js/clock/src/timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ export function sleep(duration: Nano, options?: { signal?: AbortSignal; ref?: bo
return wait(clock, Instant.add(Instant(clock.now()), duration), options).promise;
}

/** Complete in a later host task, giving the host's other work a turn; a `Manual` clock won't advance past it. */
export function yieldNow(): Promise<void> {
const clock = backend();
return new Promise((resolve) => clock.task(resolve));
}

/** A timeout expired before its operation completed. */
export class Elapsed extends Error {
/** Build a deadline-elapsed error. */
Expand Down
49 changes: 24 additions & 25 deletions js/net/src/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, spyOn, test } from "bun:test";
import { Manual, Milli, Nano } from "@moq/clock";
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";
Expand All @@ -16,7 +16,6 @@ import * as Path from "./path.ts";
import { Stream, Writer } from "./stream.ts";
import { abandoned } from "./util/demand.ts";
import { withTimeout } from "./util/timeout.ts";
import { nextTask } from "./util/yield.ts";
import { wireOf } from "./wire.ts";

const url = new URL("https://localhost:4443/test");
Expand Down Expand Up @@ -54,7 +53,7 @@ function waited(logged: { mock: { calls: unknown[][] } }, path: string): boolean

/** Yield until `done` holds, failing if it never does. */
async function settles(done: () => boolean): Promise<void> {
for (let i = 0; i < 50 && !done(); i++) await nextTask();
for (let i = 0; i < 50 && !done(); i++) await yieldNow();
expect(done()).toBe(true);
}

Expand Down Expand Up @@ -112,7 +111,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
void token.closed.then(() => {
ended = true;
});
await nextTask();
await yieldNow();
expect(ended).toBe(false);

const second = await connect({ publish: new OriginProducer(), protocol, auth: handle });
Expand Down Expand Up @@ -162,7 +161,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
streams[0]?.abort(new StreamError(StreamCode.Internal, { message: "lost" }));
await waitFor(token.grant, (g) => g === undefined);
await clock.advance(Nano.fromMilli(Milli(999)));
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(streams.length).toBe(1);
await clock.advance(Nano.fromMilli(Milli(1)));
await waitFor(token.grant, (g) => g?.publish.equals(patterns("a")) === true);
Expand Down Expand Up @@ -335,9 +334,9 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
if (!unanswered) throw new Error("missing token");
const withdrawn = origin.createBroadcast(Path.from("foo/bar"));
withdrawn.announce();
await nextTask();
await yieldNow();
withdrawn.unannounce();
await nextTask();
await yieldNow();
const issued = unanswered.accept(grant(["other"], []));
await adding;
// Still enforcing: the next uncovered broadcast is the one named.
Expand Down Expand Up @@ -477,7 +476,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video").subscribe();
await nextTask();
await yieldNow();
expect(track.closed.peek()).toBeUndefined();
clock.jump(Nano.fromMilli(Milli(7)));
const firstGrant = unanswered.accept(grant([], ["room"]));
Expand All @@ -499,7 +498,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
const renewedGrant = renewal.accept(grant([], ["room"]));
const renewed = await renewing;
first.close();
await nextTask();
await yieldNow();
expect(track.closed.peek()).toBeUndefined();
published.appendGroup().writeFrame({ payload: new Uint8Array([2]) });
expect(await track.recvGroup()).toBeDefined();
Expand Down Expand Up @@ -537,7 +536,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
void ready.then(() => {
settled = true;
});
await nextTask();
await yieldNow();
expect(settled).toBe(false);
reader.close();
expect(await ready).toBe(false);
Expand Down Expand Up @@ -568,13 +567,13 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video").subscribe();
await nextTask();
await yieldNow();
track.close();
await settles(() => waited(logged, "room/x"));
const opened = transport.sendStreams.bidi.length;
const issued = unanswered.accept(grant([], ["room"]));
await adding;
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(transport.sendStreams.bidi.length).toBe(opened);
issued.close();
} finally {
Expand Down Expand Up @@ -609,7 +608,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video");
const first = track.subscribe();
await nextTask();
await yieldNow();
first.close();
for (let i = 0; i < gap; i++) await Promise.resolve();
const second = track.subscribe();
Expand Down Expand Up @@ -646,7 +645,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
// reaches the subscription; force that order.
wireOf(client).auth.close();
expect(wireOf(client).auth.grant.peek()?.subscribe.size).toBe(0);
await nextTask();
await yieldNow();
expect(track.closed.peek()).toBeUndefined();

client.abort();
Expand Down Expand Up @@ -709,7 +708,7 @@ test("closing a session settles its unanswered setup token", async () => {
.then(() => {
settled = true;
});
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(settled).toBe(false);
client.abort();
await settles(() => settled);
Expand Down Expand Up @@ -747,7 +746,7 @@ test("lite-07 presents a transiently refused token again after a backoff", async
return request;
});
await clock.advance(Nano.fromMilli(Milli(backoff - 1)));
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(presented).toBe(false);
expect(added).toBe(false);
await clock.advance(Nano.fromMilli(Milli(1)));
Expand Down Expand Up @@ -820,7 +819,7 @@ test("lite-07 presents a shared token again when its retry stream is reset", asy
);
await clock.advance(Nano.fromMilli(Milli(1000)));
await settles(() => logged("auth token ended") > 0);
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(rejected).toBeUndefined();

await clock.advance(Nano.fromMilli(Milli(2000)));
Expand Down Expand Up @@ -865,7 +864,7 @@ test("lite-07 presents a token added after a GOAWAY only on the successor", asyn
answer(successor.server.auth.requests(), (token) => (token ? grant(["second"], []) : grant([], [])));
await late;
await waitFor(handle.grant, (g) => g?.publish.equals(patterns("second")) === true);
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(seen).not.toContain("late");

client.abort();
Expand Down Expand Up @@ -929,7 +928,7 @@ test("lite-07 ignores a draining session's late refusal once its successor grant
unanswered?.reject(SessionCode.Unauthorized, "stale");
try {
await settles(() => warned.mock.calls.some(([line]) => line === "auth token refused"));
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(ended).toBe(false);
expect(token.grant.peek()?.publish.equals(patterns("second"))).toBe(true);
} finally {
Expand Down Expand Up @@ -994,7 +993,7 @@ test("lite-07 ignores a draining session's late refusal while its successor retr
const stale = refusals();
unanswered?.reject(SessionCode.Unauthorized, "stale");
await settles(() => refusals() > stale);
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(ended).toBe(false);

const retried = successorRequests.next();
Expand Down Expand Up @@ -1041,14 +1040,14 @@ test("a fetch abandoned while its token waits never reaches the wire", async ()
.consume(Path.from("room/x"))
.track("video")
.fetchGroup(0, { signal: abort.signal });
await nextTask();
await yieldNow();
abort.abort(new Error("left"));
await expect(fetched).rejects.toThrow();
await settles(() => waited(logged, "room/x"));
const opened = transport.sendStreams.bidi.length;
const issued = unanswered.accept(grant([], ["room"]));
await adding;
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(transport.sendStreams.bidi.length).toBe(opened);
issued.close();
} finally {
Expand Down Expand Up @@ -1079,7 +1078,7 @@ test("a listing waits for its token before reaching the wire", async () => {
if (!unanswered) throw new Error("missing token");
const opened = transport.sendStreams.bidi.length;
const tracks = wireOf(client).consume(Path.from("room/x")).tracks();
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(transport.sendStreams.bidi.length).toBe(opened);
const issued = unanswered.accept(grant([], ["room"]));
await adding;
Expand Down Expand Up @@ -1121,7 +1120,7 @@ test.each(Array.from({ length: 17 }, (_, gap) => gap))(
const track = wireOf(client).consume(Path.from("room/x")).track("video");
const abort = new AbortController();
const first = track.fetchGroup(0, { signal: abort.signal });
await nextTask();
await yieldNow();
// The last caller leaves and another coalesces before the wait observes it.
abort.abort(new Error("left"));
for (let i = 0; i < gap; i++) await Promise.resolve();
Expand Down Expand Up @@ -1236,7 +1235,7 @@ test("a GOING_AWAY refusal leaves a shared token for the next session on moq-tra
});
try {
await settles(() => warned.mock.calls.some(([line]) => line === "auth token refused"));
for (let i = 0; i < 10; i++) await nextTask();
for (let i = 0; i < 10; i++) await yieldNow();
expect(rejected).toBeUndefined();
} finally {
read.mockRestore();
Expand Down
Loading
Loading