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
10 changes: 6 additions & 4 deletions doc/lib/js/clock.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ and `JSON.stringify` throw a `TypeError`, so a unit mistake can't hide behind a
cast. A template string prints one with its unit.

`Instant` counts from its clock's origin: the realm's performance time origin
on the host, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`,
on the host, so a DOM timestamp `t` is `Instant.ZERO.saturatingAdd(Duration.millis(t))`,
or zero for a `Manual` clock. Its nanoseconds are exact for roughly 104
days, then gradually lose sub-microsecond precision. Compare instants only
from the same clock. Rust and JS each own their origin: no instant may cross
that boundary until the backend explicitly shares one.
days, then gradually lose sub-microsecond precision. Like kio, moving an instant
by a duration has no throwing form: `checkedAdd`/`checkedSub` return `undefined`
past the clock's range, and `saturatingAdd`/`saturatingSub` stop at its ends.
Compare instants only from the same clock. Rust and JS each own their origin:
no instant may cross that boundary until the backend explicitly shares one.

`Wall` is wall-clock time, separate from monotonic time: `Wall.unixMillis(ms)`
builds one from Unix milliseconds and `asUnixMillis()` reads them back exactly. Use it for dates, rather than
Expand Down
8 changes: 6 additions & 2 deletions js/clock/api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export class Duration {
asMillis(): number;
asNanos(): number;
asSecs(): number;
checkedAdd(other: Duration): Duration | undefined;
clamp(lo: Duration, hi: Duration): Duration;
cmp(other: Duration): -1 | 0 | 1;
div(divisor: number): Duration;
Expand All @@ -26,6 +27,7 @@ export class Duration {
min(other: Duration): Duration;
mul(factor: number): Duration;
static nanos(value: number): Duration;
saturatingAdd(other: Duration): Duration;
saturatingSub(other: Duration): Duration;
static secs(value: number): Duration;
sub(other: Duration): Duration;
Expand All @@ -45,7 +47,8 @@ export interface Installed {
export class Instant {
static readonly ZERO: Instant;
[Symbol.toPrimitive](hint: string): string;
add(duration: Duration): Instant;
checkedAdd(duration: Duration): Instant | undefined;
checkedSub(duration: Duration): Instant | undefined;
cmp(other: Instant): -1 | 0 | 1;
eq(other: Instant): boolean;
ge(other: Instant): boolean;
Expand All @@ -54,8 +57,9 @@ export class Instant {
lt(other: Instant): boolean;
max(other: Instant): Instant;
min(other: Instant): Instant;
saturatingAdd(duration: Duration): Instant;
saturatingSub(duration: Duration): Instant;
since(earlier: Instant): Duration;
sub(duration: Duration): Instant;
toJSON(): never;
toString(): string;
valueOf(): never;
Expand Down
23 changes: 21 additions & 2 deletions js/clock/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function manual(): Manual {
// Read an instant or wall time as a plain number for assertions.
const ns = (at: Instant): number => at.since(Instant.ZERO).asNanos();
const ms = (at: Wall): number => at.asUnixMillis();
const instant = (nanos: number): Instant => Instant.ZERO.add(Duration.nanos(nanos));
const instant = (nanos: number): Instant => Instant.ZERO.saturatingAdd(Duration.nanos(nanos));
const unix = (millis: number): Wall => Wall.unixMillis(millis);
const START = ms(Manual.WALL_START);

Expand All @@ -46,7 +46,6 @@ test("durations convert units and refuse to become numbers", () => {
expect(() => Duration.millis(Number.POSITIVE_INFINITY)).toThrow(RangeError);
expect(() => instant(Number.NaN)).toThrow(RangeError);
expect(() => Duration.millis(1).sub(Duration.millis(2))).toThrow(RangeError);
expect(() => Instant.ZERO.sub(Duration.nanos(1))).toThrow(RangeError);
expect(Duration.millis(1).saturatingSub(Duration.millis(2)).isZero()).toBe(true);
expect(instant(5).since(instant(9)).isZero()).toBe(true);
expect(`${Duration.micros(1500)}`).toBe("1.5ms");
Expand All @@ -68,6 +67,26 @@ test("durations convert units and refuse to become numbers", () => {
}
});

test("moving past either end of a range is checked or saturates", () => {
// Past the longest duration, a nanosecond count is no longer finite.
const longest = Duration.secs(Number.MAX_VALUE);
expect(Instant.ZERO.checkedSub(Duration.nanos(1))).toBeUndefined();
expect(instant(5).saturatingSub(Duration.nanos(9))).toEqual(Instant.ZERO);
expect(instant(5).checkedSub(Duration.nanos(5))).toEqual(Instant.ZERO);
expect(instant(5).checkedAdd(Duration.nanos(4))).toEqual(instant(9));
expect(Instant.ZERO.checkedAdd(longest)).toBeUndefined();
const last = Instant.ZERO.saturatingAdd(longest);
expect(last.gt(instant(Number.MAX_SAFE_INTEGER))).toBe(true);
expect(last.saturatingAdd(Duration.nanos(1))).toEqual(last);
expect(longest.checkedAdd(longest)).toBeUndefined();
expect(longest.saturatingAdd(longest).gt(longest)).toBe(true);
const max = longest.saturatingAdd(longest);
expect(max.checkedAdd(Duration.nanos(1))).toBeUndefined();
expect(max.saturatingAdd(Duration.nanos(1))).toEqual(max);
expect(Duration.secs(1).checkedAdd(Duration.millis(1))).toEqual(Duration.millis(1001));
expect(Duration.secs(1).saturatingAdd(Duration.millis(1))).toEqual(Duration.millis(1001));
});

test("durations keep a whole count of any unit exact past 2^53 ns", () => {
// Microseconds since the Unix epoch, as a legacy container timestamp carries them.
for (const micros of [1_735_689_600_000_016, 4_102_444_800_123_457, Number.MAX_SAFE_INTEGER]) {
Expand Down
61 changes: 50 additions & 11 deletions js/clock/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ const NANOS_PER_SEC = 1_000_000_000;
export class Duration {
/** No time at all. */
static readonly ZERO: Duration = new Duration(0, 0);
// The longest representable duration, which a saturating sum stops at.
static readonly #MAX: Duration = new Duration(Number.MAX_VALUE, NANOS_PER_SEC - 1);

/** @internal Whole seconds. */
readonly [VALUE]: number;
Expand Down Expand Up @@ -75,6 +77,13 @@ export class Duration {
// Whole seconds plus any nanoseconds, possibly out of range or fractional seconds, rounded to
// whole nanoseconds as Rust's are, so a value's conversions agree with its ordering.
static #carry(secs: number, nanos: number): Duration {
const out = Duration.#tryCarry(secs, nanos);
if (out === undefined) throw new RangeError(`invalid duration: ${secs}s + ${nanos}ns`);
return out;
}

// `#carry`, or `undefined` when the result is negative or past the longest duration.
static #tryCarry(secs: number, nanos: number): Duration | undefined {
let whole = Math.floor(secs);
let rest = Math.round((secs - whole) * NANOS_PER_SEC + nanos);
const carry = Math.floor(rest / NANOS_PER_SEC);
Expand All @@ -87,9 +96,7 @@ export class Duration {
whole -= 1;
rest += NANOS_PER_SEC;
}
if (!Number.isFinite(whole) || !Number.isFinite(rest) || whole < 0) {
throw new RangeError(`invalid duration: ${secs}s + ${nanos}ns`);
}
if (!Number.isFinite(whole) || !Number.isFinite(rest) || whole < 0) return undefined;
return new Duration(whole, rest);
}

Expand Down Expand Up @@ -140,7 +147,22 @@ export class Duration {

/** The sum of both durations. */
add(other: Duration): Duration {
return Duration.#carry(this[VALUE] + other[VALUE], this[NANOS] + other[NANOS]);
const sum = this.checkedAdd(other);
if (sum === undefined) throw new RangeError("duration overflow");
return sum;
}

/** The sum of both durations, or `undefined` past the longest representable duration. */
checkedAdd(other: Duration): Duration | undefined {
const sum = Duration.#tryCarry(this[VALUE] + other[VALUE], this[NANOS] + other[NANOS]);
// Near the ceiling a carried second rounds away, which would shrink the sum below an operand.
if (sum === undefined || sum.lt(this) || sum.lt(other)) return undefined;
return sum;
}

/** The sum of both durations, stopping at the longest representable duration. */
saturatingAdd(other: Duration): Duration {
return this.checkedAdd(other) ?? Duration.#MAX;
}

/** This duration minus `other`; throws a `RangeError` if `other` is longer. */
Expand Down Expand Up @@ -248,11 +270,16 @@ export class Duration {
* A point on the installed clock's monotonic timeline, mirroring `kio::clock::Instant`.
*
* Instants are only comparable within one clock. The host clock's origin is the realm's
* performance time origin, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`.
* performance time origin, so a DOM timestamp `t` is `Instant.ZERO.saturatingAdd(Duration.millis(t))`.
*
* Moving one by a `Duration` has no throwing form: each caller picks `checked` or `saturating`,
* so a duration past the clock's range is handled rather than thrown.
*/
export class Instant {
/** The clock's origin. */
static readonly ZERO: Instant = new Instant(0);
// The last instant the clock can represent, which a deadline past its range saturates to.
static readonly #MAX: Instant = new Instant(Number.MAX_VALUE);

/** @internal Nanoseconds since the origin. */
readonly [VALUE]: number;
Expand All @@ -267,14 +294,26 @@ export class Instant {
instantNanos = (at) => at[VALUE];
}

/** This instant moved forward by `duration`. */
add(duration: Duration): Instant {
return new Instant(checked(this[VALUE] + duration.asNanos(), "instant"));
/** This instant moved forward by `duration`, or `undefined` past the clock's range. */
checkedAdd(duration: Duration): Instant | undefined {
const nanos = this[VALUE] + duration.asNanos();
return Number.isFinite(nanos) ? new Instant(nanos) : undefined;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/** This instant moved back by `duration`, or `undefined` before the clock's origin. */
checkedSub(duration: Duration): Instant | undefined {
const nanos = this[VALUE] - duration.asNanos();
return nanos >= 0 ? new Instant(nanos) : undefined;
}

/** This instant moved forward by `duration`, stopping at the clock's last instant. */
saturatingAdd(duration: Duration): Instant {
return this.checkedAdd(duration) ?? Instant.#MAX;
}

/** This instant moved back by `duration`; throws a `RangeError` before the clock's origin. */
sub(duration: Duration): Instant {
return new Instant(checked(this[VALUE] - duration.asNanos(), "instant"));
/** This instant moved back by `duration`, stopping at the clock's origin. */
saturatingSub(duration: Duration): Instant {
return this.checkedSub(duration) ?? Instant.ZERO;
}

/** The time from `earlier` to this instant, zero if `earlier` is later. */
Expand Down
2 changes: 1 addition & 1 deletion js/hang/src/container/consumer.backpressure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ test("Consumer stamps frames the max buffer held back with when they landed, not
});
expect(await consumer.next()).toMatchObject({
kind: "frame",
frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) },
frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.saturatingAdd(Duration.millis(250)) },
});
} finally {
consumer.close();
Expand Down
4 changes: 2 additions & 2 deletions js/net/bench/ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ export function run(): void {
const start = performance.now();
for (let i = 0; i < count * (order === "rolling" ? 2 : 1); i++) {
const sequence = keys[i];
const at = order === "rolling" ? Instant.ZERO.add(Duration.millis(i)) : Instant.ZERO;
const at = order === "rolling" ? Instant.ZERO.saturatingAdd(Duration.millis(i)) : Instant.ZERO;
ledger.account(sequence, sequence + 1n, at);
ledger.expire(at, grace);
if (!ledger.covers(sequence, sequence + 1n)) throw new Error("arrival missing");
}
const arrivals = count * (order === "rolling" ? 2 : 1);
console.log(`${count},${order},${(((performance.now() - start) * 1e6) / arrivals).toFixed(0)}`);
ledger.expire(Instant.ZERO.add(Duration.millis(count * 3)), grace);
ledger.expire(Instant.ZERO.saturatingAdd(Duration.millis(count * 3)), grace);
if (!ledger.covers(0n, BigInt(arrivals * 2 - 1)) || ledger.hasGaps())
throw new Error("expiration incomplete");
}
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export class Pool {
if (this.#sweep !== undefined || this.#expiry === undefined || this.#tracks.size === 0) return;
const sweep = new AbortController();
this.#sweep = sweep;
const at = now().add(TICK.mul(this.#expiry / 2));
const at = now().saturatingAdd(TICK.mul(this.#expiry / 2));
void sleepUntil(at, { signal: sweep.signal, ref: false }).then(
() => {
if (this.#sweep !== sweep) return;
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/connection/bandwidth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async function settle() {
}

async function waitUntil(pred: () => boolean, ms = 1000): Promise<void> {
const deadline = now().add(Duration.millis(ms));
const deadline = now().saturatingAdd(Duration.millis(ms));
for (;;) {
if (pred()) return;
if (now().gt(deadline)) throw new Error("timed out waiting for condition");
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/connection/migrate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function settle() {

// Polls until `pred` holds, so a regression fails the test instead of hanging it.
async function waitUntil(pred: () => boolean, ms = 2000): Promise<void> {
const deadline = now().add(Duration.millis(ms));
const deadline = now().saturatingAdd(Duration.millis(ms));
for (;;) {
if (pred()) return;
if (now().gt(deadline)) throw new Error("timed out waiting for condition");
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/connection/reload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ function present(routes: Announce.Routes): Getter<ReadonlySet<Path.Valid>> {

// Polls until `pred` holds, so a regression fails the test instead of hanging it.
async function waitUntil(pred: () => boolean): Promise<void> {
const deadline = now().add(Duration.millis(1000));
const deadline = now().saturatingAdd(Duration.millis(1000));
while (now().le(deadline)) {
if (pred()) return;
await settle();
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/connection/reload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,7 @@ export class Reload {
// When a retry window starting `at` expires.
#window(at: Instant): Instant | null {
const { timeout } = this.#pacing();
return timeout === null ? null : at.add(timeout);
return timeout === null ? null : at.saturatingAdd(timeout);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions js/net/src/connection/ticker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Ticker {
const abort = new AbortController();
this.#abort = abort;
void (async () => {
let next = now().add(this.#period);
let next = now().saturatingAdd(this.#period);
for (;;) {
await sleepUntil(next, { signal: abort.signal }).catch(() => {});
if (abort.signal.aborted) return;
Expand All @@ -45,7 +45,7 @@ class Ticker {
console.error("ticker callback error", err);
}
}
next = now().add(this.#period);
next = now().saturatingAdd(this.#period);
}
})();
}
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/goaway-requests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async function settle() {
}

async function waitUntil(pred: () => boolean): Promise<void> {
const deadline = now().add(Duration.millis(2000));
const deadline = now().saturatingAdd(Duration.millis(2000));
for (;;) {
if (pred()) return;
if (now().gt(deadline)) throw new Error("timed out waiting for condition");
Expand Down
7 changes: 4 additions & 3 deletions js/net/src/ietf/publisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1868,7 +1868,7 @@ export class Publisher {
ns.active.delete(key);
const wait = lapses.get(key)?.wait ?? RETRY_BASE;
lapses.set(key, { snap, wait: Math.min(wait * 2, RETRY_MAX) });
ns.refused.set(key, now().add(Duration.millis(wait)));
ns.refused.set(key, now().saturatingAdd(Duration.millis(wait)));
ns.offered.set(key, snap);
}

Expand Down Expand Up @@ -2040,10 +2040,11 @@ export class Publisher {

/**
* What a REQUEST_ERROR's retry interval, in milliseconds, says about re-offering the
* namespace: 0 means the peer does not want this again.
* namespace: 0, or an interval past the clock's range, means the peer does not want this again.
*/
#refusal(err: RequestError): Answer {
return err.retryInterval === 0n ? "never" : now().add(Duration.millis(toNumber(err.retryInterval)));
if (err.retryInterval === 0n) return "never";
return now().checkedAdd(Duration.millis(toNumber(err.retryInterval))) ?? "never";
}

/**
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2049,7 +2049,7 @@ test("integration: ietf blind handle picks up a publisher that arrives late", as
/** Poll until `pred` holds, so a regression fails the test instead of hanging it. */
// Yields rather than sleeps, so it also polls under a Manual clock, where only the suite timeout bounds it.
async function until(pred: () => boolean): Promise<void> {
const deadline = now().add(Duration.millis(1000));
const deadline = now().saturatingAdd(Duration.millis(1000));
while (!pred()) {
if (now().gt(deadline)) throw new Error("timed out waiting for condition");
await yieldNow();
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/ledger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { expect, test } from "bun:test";
import { Duration, Instant } from "@moq/clock";
import { Ledger } from "./ledger.ts";

const at = (ms: number) => Instant.ZERO.add(Duration.millis(ms));
const at = (ms: number) => Instant.ZERO.saturatingAdd(Duration.millis(ms));

test("overlapping and adjacent ranges merge without changing surviving gap ages", () => {
const ledger = new Ledger();
Expand Down
6 changes: 3 additions & 3 deletions js/net/src/mock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ test("drive delivers a queued round trip before its deadline and stops at the de
await sleep(ms(10));
return { value, at: now() };
})();
expect(await clock.drive(work)).toEqual({ value: Uint8Array.of(7), at: Instant.ZERO.add(ms(10)) });
expect(await clock.drive(work)).toEqual({ value: Uint8Array.of(7), at: Instant.ZERO.saturatingAdd(ms(10)) });
expect(late).toBe(false);
});

Expand All @@ -84,7 +84,7 @@ test("drive times out a read with nothing in flight at its deadline", async () =
const { local } = await pair();
const read = timeout(ms(1000), local.readable.getReader().read());
expect(await clock.drive(read.catch((e: unknown) => e))).toBeInstanceOf(Elapsed);
expect(clock.now()).toEqual(Instant.ZERO.add(ms(1000)));
expect(clock.now()).toEqual(Instant.ZERO.saturatingAdd(ms(1000)));
});

test("drive reaches a deadline while deliveries keep arriving", async () => {
Expand All @@ -106,7 +106,7 @@ test("drive reaches a deadline while deliveries keep arriving", async () => {
send();
try {
await clock.drive(sleep(ms(1000)));
expect(clock.now()).toEqual(Instant.ZERO.add(ms(1000)));
expect(clock.now()).toEqual(Instant.ZERO.saturatingAdd(ms(1000)));
expect(delivered).toBeGreaterThan(0);
} finally {
sending = false;
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1214,7 +1214,7 @@ class Reader implements ResumeSource {
const timer = new AbortController();
this.#wall = { at, timer };
// A wakeup is never a reason to hold a Node/Bun process open.
void sleepUntil(Instant.ZERO.add(Duration.nanos(at)), { signal: timer.signal, ref: false }).then(
void sleepUntil(Instant.ZERO.saturatingAdd(Duration.nanos(at)), { signal: timer.signal, ref: false }).then(
() => {
if (timer.signal.aborted) return;
this.#wall = undefined;
Expand Down
2 changes: 1 addition & 1 deletion js/net/src/tail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe("Tail", () => {
function tail(grace = GRACE) {
const clock = new Manual();
installed = clock.install();
const at = (to: Duration) => clock.jump(Instant.ZERO.add(to).since(clock.now()));
const at = (to: Duration) => clock.jump(Instant.ZERO.saturatingAdd(to).since(clock.now()));
return { at, clock, tail: new Tail({ grace: () => grace }) };
}

Expand Down
Loading