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
8 changes: 4 additions & 4 deletions doc/lib/js/clock.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ bun add @moq/clock
import { Manual, Milli, Nano, now, sleep } from "@moq/clock";

const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
try {
const start = now();
const pending = sleep(Nano.fromMilli(Milli(10)));
await clock.advance(Nano.fromMilli(Milli(10)));
await pending;
console.log(now() - start); // 10,000,000 nanoseconds
} finally {
restore();
installed.close();
}
```

Expand Down Expand Up @@ -56,8 +56,8 @@ Timer callbacks may arm timers, but must leave driving that clock to their calle
wall time without the jitter of subtracting two live reads. On the host it is
the realm's performance time origin; on a `Manual` it follows `stepWall()`.

Installation is scoped to the current JS realm. Restore it in `finally` and
keep tests sharing that realm serial. Timers remain bound to the clock on
Installation is scoped to the current JS realm. Close the handle `install()`
returns in `finally`, and keep tests sharing that realm serial. Timers remain bound to the clock on
which they were created, even after restoration. Host timers used by a test
runner or RPC framework keep running in real time.

Expand Down
4 changes: 2 additions & 2 deletions js/auth/src/key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async function generateAsymmetricKeyPair(
test("verify refuses unsafe signed payloads without dropping their restrictions", async () => {
const clock = new Manual();
clock.stepWall(Wall(1_000_000));
const restore = clock.install();
const installed = clock.install();
try {
const key = Key.parse(encodeJwk(testKey));
const secret = new TextEncoder().encode("test-secret-that-is-long-enough-for-hmac-sha256");
Expand All @@ -84,7 +84,7 @@ test("verify refuses unsafe signed payloads without dropping their restrictions"
Key.verify(key, await signed({ publish: ["**"] }, { alg: "HS384", kid: testKey.kid })),
).rejects.toThrow();
} finally {
restore();
installed.close();
}
});

Expand Down
15 changes: 15 additions & 0 deletions js/clock/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ How to update your code for each breaking change, newest first.

## Unreleased

### `Manual.install()` returns an `Installed` handle (#6510)

`install()` returns an `Installed` handle instead of a restore function, matching Rust's `Manual::install`.
Call `installed.close()` where you called `restore()`:

```ts
// Before
const restore = clock.install();
restore();

// After
const installed = clock.install();
installed.close();
```

### Manual time steps through timer deadlines

Rename `await clock.advanceAsync(duration)` to `await clock.advance(duration)`.
Expand Down
4 changes: 2 additions & 2 deletions js/clock/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ Use `Manual` to test time without replacing the host's timers.
import { Manual, Milli, Nano, now, sleep } from "@moq/clock";

const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
try {
const pending = sleep(Nano.fromMilli(Milli(10)));
await clock.advance(Nano.fromMilli(Milli(10)));
await pending;
console.log(now()); // 10,000,000 nanoseconds
} finally {
restore();
installed.close();
}
```

Expand Down
4 changes: 2 additions & 2 deletions js/clock/bench/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ for (const mode of ["jump", "advance"]) {
const samples: number[][] = [[], [], []];
for (let round = 0; round < 6; round++) {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const aborts = Array.from({ length: scope === "shared" ? 1 : armed }, () => new AbortController());
try {
const start = performance.now();
Expand All @@ -31,7 +31,7 @@ for (const mode of ["jump", "advance"]) {
samples[2].push((cancelledAt - advancedAt) * 1000);
}
} finally {
restore();
installed.close();
}
}
console.log(
Expand Down
18 changes: 13 additions & 5 deletions js/clock/src/ambient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,24 @@ import { host } from "./host.ts";

let current: { backend: Backend; previous?: typeof current; active: boolean } = { backend: host, active: true };

/** A clock installed in the current realm; close it to restore the clock it replaced. */
export interface Installed {
/** Restore the clock this one replaced. Idempotent, and safe out of order. */
close(): void;
}

export function backend(): Backend {
return current.backend;
}

export function install(backend: Backend): () => void {
export function install(backend: Backend): Installed {
const entry = { backend, previous: current, active: true };
current = entry;
return () => {
entry.active = false;
// Out-of-order cleanup must not revive an already-restored outer clock.
while (!current.active && current.previous) current = current.previous;
return {
close: () => {
entry.active = false;
// Out-of-order cleanup must not revive an already-restored outer clock.
while (!current.active && current.previous) current = current.previous;
},
};
}
13 changes: 7 additions & 6 deletions js/clock/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { afterEach, expect, test } from "bun:test";
import { setTimeout as hostTimeout } from "node:timers/promises";
import {
Elapsed,
type Installed,
Instant,
interval,
Manual,
Expand All @@ -19,13 +20,13 @@ import {
wall,
} from "./index.ts";

const restores: (() => void)[] = [];
const installs: Installed[] = [];
afterEach(() => {
for (const restore of restores.splice(0).reverse()) restore();
for (const installed of installs.splice(0).reverse()) installed.close();
});
function manual(): Manual {
const clock = new Manual();
restores.push(clock.install());
installs.push(clock.install());
return clock;
}
const ns = Nano.fromMilli;
Expand Down Expand Up @@ -77,11 +78,11 @@ test("installation restores nested and out-of-order scopes without reviving them
const inner = manual();
inner.jump(Nano(8));
expect<number>(now()).toBe(8);
restores[0]();
installs[0].close();
expect<number>(now()).toBe(8);
restores[1]();
installs[1].close();
const restored = now();
restores[1]();
installs[1].close();
expect<number>(now()).toBeGreaterThanOrEqual(restored);
expect<number>(now()).not.toBe(4);
});
Expand Down
6 changes: 5 additions & 1 deletion js/clock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { backend } from "./ambient.ts";
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 { Instant, Micro, Milli, Nano, Second, Wall } from "./types.ts";
Expand All @@ -17,7 +18,10 @@ export function wall(): Wall {
return Wall(backend().wall());
}

/** Read the installed clock's wall time at instant zero, in Unix milliseconds. */
/**
* Read the installed clock's wall time at instant zero, in Unix milliseconds.
* Rust's `moq_clock::origin()` pairs a nanosecond `Wall` with an instant instead.
*/
export function origin(): Wall {
return Wall(backend().origin());
}
6 changes: 3 additions & 3 deletions js/clock/src/manual.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { install } from "./ambient.ts";
import { type Installed, install } from "./ambient.ts";
import type { Backend } from "./backend.ts";
import { drain } from "./host.ts";
import { Instant, Nano, Wall } from "./types.ts";
Expand Down Expand Up @@ -40,8 +40,8 @@ export class Manual {
},
};

/** Install this clock in the current realm and return an idempotent restore function. */
install(): () => void {
/** Install this clock in the current realm until the returned handle closes. */
install(): Installed {
return install(this.#backend);
}

Expand Down
16 changes: 8 additions & 8 deletions js/hang/src/container/consumer.holes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const flush = () => new Promise<void>((resolve) => setImmediate(resolve));

test.each([0, 100])("a sequence hole before a paused data marker expires at %sms", async (budget) => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const track = new Track.Producer("data");
const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), {
format: new Format("data"),
Expand Down Expand Up @@ -48,13 +48,13 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms
consumer.close();
track.close();
await reading;
restore();
installed.close();
}
});

test("a filled hole cancels its timer and the next hole gets a fresh budget", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const track = new Track.Producer("data");
const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), {
format: new Format("data"),
Expand Down Expand Up @@ -99,13 +99,13 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as
consumer.close();
track.close();
await reading;
restore();
installed.close();
}
});

test("the holes a stalled source left behind share one budget", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const track = new Track.Producer("data");
const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), {
format: new Format("data"),
Expand Down Expand Up @@ -140,13 +140,13 @@ test("the holes a stalled source left behind share one budget", async () => {
consumer.close();
track.close();
await reading;
restore();
installed.close();
}
});

test("a hole is late from the earliest arrival past it", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const track = new Track.Producer("data");
const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), {
format: new Format("data"),
Expand Down Expand Up @@ -184,6 +184,6 @@ test("a hole is late from the earliest arrival past it", async () => {
consumer.close();
track.close();
await reading;
restore();
installed.close();
}
});
4 changes: 2 additions & 2 deletions js/hang/src/container/consumer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ test("Consumer skips groups via PTS-span when over the max delay", async () => {

test("Consumer measures arrivals as they land", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const track = new Track.Producer("test");
const consumer = new Consumer(track.subscribe(), {
format: new LegacyFormat("audio"),
Expand Down Expand Up @@ -840,7 +840,7 @@ test("Consumer measures arrivals as they land", async () => {
track.close();
consumer.close();
next.close();
restore();
installed.close();
}
});

Expand Down
4 changes: 2 additions & 2 deletions js/net/bench/drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { type Group, Track } from "@moq/net";
/** Read live frames after a retained window, checking every delivered payload. */
export async function run(): Promise<void> {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const payload = new Uint8Array([7]);
try {
console.log("retained,publishers,readers,ns_per_frame");
Expand Down Expand Up @@ -58,7 +58,7 @@ export async function run(): Promise<void> {
}
}
} finally {
restore();
installed.close();
}
}
if (import.meta.main) await run();
4 changes: 2 additions & 2 deletions js/net/bench/refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ for (const retained of [1, 64, 1024])
for (const tracks of [1, 8, 32])
for (const joined of [1, 8, 32]) {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const source = new Producer();
const destination = new Producer();
const broadcast = source.createBroadcast(Path.from("room"));
Expand Down Expand Up @@ -84,6 +84,6 @@ for (const retained of [1, 64, 1024])
source.close();
for (const peer of peers) peer.abort();
await clock.advance(Nano(0));
restore();
installed.close();
}
}
4 changes: 2 additions & 2 deletions js/net/src/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s",

test("a request waits for its token and survives union renewal", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const logged = spyOn(console, "debug");
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
Expand Down Expand Up @@ -344,7 +344,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s",
server.abort();
await adding.catch(() => void 0);
logged.mockRestore();
restore();
installed.close();
}
});

Expand Down
8 changes: 4 additions & 4 deletions js/net/src/broadcast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -965,7 +965,7 @@ function finishedTrack(broadcast: BroadcastProducer, name: string, maxAge?: numb
// max-age add nothing to the wait.
test("finish serves finished tracks until stale", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
const origin = new OriginProducer();
try {
const broadcast = origin.createBroadcast(Path.from("finish"));
Expand Down Expand Up @@ -1005,7 +1005,7 @@ test("finish serves finished tracks until stale", async () => {
live.close();
} finally {
origin.close();
restore();
installed.close();
}
});

Expand Down Expand Up @@ -1048,7 +1048,7 @@ test("a finished broadcast refuses changes", () => {
// A close elsewhere ends the linger early.
test("closing the broadcast elsewhere ends the linger", async () => {
const clock = new Manual();
const restore = clock.install();
const installed = clock.install();
try {
const broadcast = new BroadcastProducer();
finishedTrack(broadcast, "video", 30).close();
Expand All @@ -1059,6 +1059,6 @@ test("closing the broadcast elsewhere ends the linger", async () => {
await wait;
expect(Number(clock.now())).toBe(Nano.fromMilli(Milli(1_000)));
} finally {
restore();
installed.close();
}
});
Loading
Loading