diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index ced67f42582..c0634b010a2 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -42,7 +42,7 @@ route.announce(); - **Answer claimed paths with a route.** `origin.claim(prefix)` returns a `Claim` over a prefix, and `claim.requested()` yields each requested path. Answer with `request.route()`, a new exact route under the claim's instance (a fresh one if the claim names its own), so on `moq-lite-07-wip` readers resolved through the claim continue (older wires mint another instance for it, restarting their subscription), or `request.route({ hidden: true })` to fill its broadcast before `announce()` answers the requesters; closing it or its broadcast before then refuses them as unroutable, so `using job = request.route({ hidden: true })` refuses on a throw. Serve a broadcast you already hold with `request.serve(broadcast)`, or refuse with `request.reject(err)`. - **End content by finishing tracks.** A broadcast has no finished state. When the input ends, `finish()` each track, then `close()` it; closing a track without finishing aborts it. `fail(error)` ends a track in error instead: unlike `abort`, readers still get every group written, then the error. The broadcast stays announced and keeps serving them until you `close()` it. How long to keep it up for late readers is yours to decide. - **Requests can pin an instance.** `consumer.request(path, { instance })` resolves only through a route announcing that [publisher instance](/concept/moq-lite#publisher-instances). The resolved broadcast's `instance` names the stream it came through, pinned or not. `origin.route(path)` mints a random instance when it is created and keeps it across `withdraw()` and `announce()`. Unless one is named, a claim moves to a fresh instance each time a job holding its current one ends, and a job takes the claim's. Pass `origin.route(path, { instance: { id, epoch } })` only for a publisher that continues its group sequences across restarts and raises the epoch each time. -- **Follow restarts.** `origin.follow(path)` follows whichever publisher instance serves the path: its `active` changes to a fresh broadcast on a restart, clears on an end, and resolves again on the next start, so read it reactively and close it when done. Instances are never stitched, so subscribe again to each new broadcast. Another route of the same instance taking over (instances travel only on `moq-lite-07-wip`; older wires mint one per announcement) keeps `active` as is, and each track subscription resumes there from the first group it lacks. A refusal ends it. Pass `{ instance }` to pin one stream, which it waits for again after an end. `request(path)` instead keeps its accepted instance and ends once that instance stops serving; while pending, it fails `Unroutable` once discovery of its path has synced without a route for it. To list what is live, iterate `announced(scope)`. See [identity and recovery](/concept/identity) to choose between following and holding one instance. +- **Follow restarts.** `origin.follow(path)` follows whichever publisher instance serves the path: its `active` changes to a fresh broadcast on a restart, clears on an end, and resolves again on the next start, so read it reactively and close it when done. Instances are never stitched, so subscribe again to each new broadcast. Another route of the same instance taking over (instances travel only on `moq-lite-07-wip`; older wires mint one per announcement) keeps `active` as is, and each track subscription resumes there from the first group it lacks. A refusal ends it. Pass `{ instance }` to pin one stream, which it waits for again after an end. `request(path)` instead keeps its accepted instance and ends once that instance stops serving; while pending, it fails `Unroutable` once discovery of its path has synced without a route for it. `await request.broadcast()` on the handle `origin.request(path)` returns gives that broadcast or throws why none came, as Rust's `request(path).await` does; the handle itself is not awaitable, and it still owns the broadcast, so close the request when done. To list what is live, iterate `announced(scope)`. See [identity and recovery](/concept/identity) to choose between following and holding one instance. - **Discovery follows what you watch.** A `consume` origin asks the relay for announcements only under the prefixes its readers watch with `announced(scope)`, `request(path)`, or `follow(path)`, stops asking about a prefix 2s after nothing at or beneath it is watched, and asks again on reconnect. Every request and follower watches its path from creation until closed, so it outlives the listing that found it. A relay that refuses an announce request downgrades that session: requests subscribe blind through it, and followers keep waiting for a session that can discover. - **Connections share by URL and versions.** `new Connection({ url })` pools and reconnects with backoff, which the elements use. An ordered `versions` list, spelled like `moq-lite-06` as in Rust, applies to both WebTransport and WebSocket; equivalent lists share, while a different order or an omitted list gets its own pool entry. Supplying your own transport options or origin selects a private loop. Receive estimates are on demand: observe `connection.probe` reactively or subscribe while you need them; `peek()` alone opens no PROBE stream. - **GOAWAY moves the session.** The connection dials the replacement at once while the old session keeps serving its groups, up to `goaway.handover` (default 10s, or the relay's deadline when that is sooner). New requests keep opening on the old session until the replacement's route outranks it, which is a restart when the instance did not cross: an unpinned announced request follows the replacement, while a blind or instance-pinned request stays on its accepted stream. When `moq-lite-07-wip` is offered the instance crosses, the replacement serves the same stream, and open subscriptions move across without missing a group. An empty GOAWAY redials the same URL. A redirect stays on the same host unless `goaway.redirect` is `"follow"`, which also presents the tokens on the connection's `auth` handle to the new host. A one-shot session from `Connection.connect` never moves on its own; its `draining` settles with the GOAWAY, so you can connect again and close it. Its URI is the peer's to choose and `goaway.redirect` does not apply, so validate it before dialing it or presenting tokens to it. diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index b78bb3cbc1d..c01f6fe6d51 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -27,7 +27,7 @@ export namespace Auth { export interface Credential { readonly answered: PromiseLike; close(): void; - readonly closed: PromiseLike; + readonly closed: Signals.GetPromise; readonly grant: Signals.Getter; } export class Duplicate extends Error { @@ -178,8 +178,8 @@ export namespace Connection { rtt?: Clock.Duration; } export interface Props { + backoff?: Connection.Backoff; consume?: Origin.Producer; - delay?: Connection.Backoff; enabled?: boolean | Signals.Signal; goaway?: Connection.Handover; publish?: Origin.Consumer; @@ -199,7 +199,7 @@ export namespace Connection { announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; readonly auth: Auth.Handle; close(): Promise; - closed: Promise; + readonly closed: Signals.GetPromise; readonly draining: Signals.GetPromise; readonly peerImplementation: Promise; readonly probe: Signals.Getter; @@ -503,6 +503,7 @@ export namespace Origin { } export class Requesting { readonly active: Signals.Getter; + broadcast(): Promise; close(): void; readonly closed: Signals.GetPromise; readonly path: Path.Valid; diff --git a/js/net/bench/refresh.ts b/js/net/bench/refresh.ts index 9d40485d114..11482708198 100644 --- a/js/net/bench/refresh.ts +++ b/js/net/bench/refresh.ts @@ -33,9 +33,7 @@ for (const retained of [1, 64, 1024]) const announcements = destination.announced(); while ((await announcements.next())?.kind !== "present") {} const request = destination.request(Path.from("room")); - while (!request.active.peek()) await request.active.changed(); - const remote = request.active.peek(); - if (!remote) throw new Error("broadcast missing"); + const remote = await request.broadcast(); const consumers = producers.map((_, i) => remote.track(`data${i}`)); const baseline = consumers.map((track) => track.subscribe()); for (let i = 0; i < tracks; i++) { diff --git a/js/net/examples/subscribe.ts b/js/net/examples/subscribe.ts index f366b210f8b..caa7dfd0260 100644 --- a/js/net/examples/subscribe.ts +++ b/js/net/examples/subscribe.ts @@ -5,16 +5,13 @@ async function main() { const origin = new Moq.Origin.Producer(); const connection = await Moq.Connection.connect({ url, consume: origin }); - // Keep one publisher instance; wait.ts shows following publisher restarts. - const broadcast = origin.request(Moq.Path.from("my-broadcast")); + // Keep one publisher instance, or throw if none serves the path; wait.ts shows following + // publisher restarts. The request owns the broadcast, so close it when done. + const request = origin.request(Moq.Path.from("my-broadcast")); + const broadcast = await request.broadcast(); // Subscribe to a specific track (with the default subscription) - let active = broadcast.active.peek(); - while (!active) { - await broadcast.active.changed(); - active = broadcast.active.peek(); - } - const track = active.track("chat").subscribe(); + const track = broadcast.track("chat").subscribe(); // Read data as it arrives for (;;) { @@ -40,7 +37,7 @@ async function main() { } track.close(); - broadcast.close(); + request.close(); await connection.close(); origin.close(); } diff --git a/js/net/src/auth.ts b/js/net/src/auth.ts index bd3555bcb48..1ba445cd366 100644 --- a/js/net/src/auth.ts +++ b/js/net/src/auth.ts @@ -18,7 +18,7 @@ */ import type { Wall } from "@moq/clock"; -import type { Getter } from "@moq/signals"; +import type { GetPromise, Getter } from "@moq/signals"; import type { SessionCode } from "./error.ts"; import type * as Path from "./path.ts"; @@ -53,7 +53,7 @@ export interface Credential { * peer closed it without one or it was withdrawn, or the handle's end. A session ending is * not one: the next session presents it again. */ - readonly closed: PromiseLike; + readonly closed: GetPromise; /** * Resolves once a peer first accepts the token. Rejects with {@link Unsupported} when a * session neither carries AUTH nor lets a request carry a token (moq-lite without AUTH), @@ -75,7 +75,7 @@ export interface Request { /** The token the peer presented. Empty means the credential its connection carried. */ readonly token: Uint8Array; /** Settles when the peer withdraws this unanswered token or closes the session. */ - readonly closed: PromiseLike; + readonly closed: GetPromise; /** * Grant the token until the returned {@link Issued} is revoked or closed. * @@ -106,7 +106,7 @@ export interface Issued { /** End the grant without a reason. */ close(): void; /** Settles once the peer withdraws the token or its stream ends. */ - readonly closed: PromiseLike; + readonly closed: GetPromise; } /** diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index 41add2ca507..d4efcb17ada 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -1,5 +1,5 @@ import { Duration, type Instant, now, sleep, type Wall, wall, yieldNow } from "@moq/clock"; -import { type Dispose, type Getter, Once, race, Signal } from "@moq/signals"; +import { type Dispose, type GetPromise, type Getter, Once, race, Signal } from "@moq/signals"; import type { Credential, Grant, Issued, Request, Requests } from "./auth.ts"; import { closeReason, error, ProtocolViolation, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; import * as Path from "./path.ts"; @@ -171,7 +171,6 @@ export interface Pending extends Credential { /** A token the application added to a {@link Handle}, presented on every session of it. */ class Token implements Pending { readonly grant = new Signal(undefined); - readonly closed: Promise; readonly answered: Promise; readonly bytes: Uint8Array; @@ -180,16 +179,13 @@ class Token implements Pending { inband = false; #state: HandleState; - #close!: (err: Error | null) => void; + #closed = new Once(); #answer!: () => void; #refuse!: (err: Error) => void; constructor(bytes: Uint8Array, state: HandleState) { this.bytes = bytes; this.#state = state; - this.closed = new Promise((resolve) => { - this.#close = resolve; - }); this.answered = new Promise((resolve, reject) => { this.#answer = resolve; this.#refuse = reject; @@ -212,7 +208,11 @@ class Token implements Pending { this.isAnswered = true; this.#refuse(err ?? new Error("withdrawn")); } - this.#close(err); + this.#closed.set(err); + } + + get closed(): GetPromise { + return this.#closed; } get held(): boolean { @@ -451,7 +451,7 @@ class PeerRequest implements Request { this.#issued = issued; } - get closed(): Promise { + get closed(): GetPromise { return this.#issued.closed; } @@ -475,8 +475,7 @@ class PeerRequest implements Request { /** Our side of one of the peer's tokens: the grant we issued and its stream. */ class IssuedGrant implements Issued { - ended = false; - readonly closed: Promise; + readonly #closed = new Once(); #stream: Stream; #wire: AuthWire; #writes = Promise.resolve(); @@ -490,15 +489,19 @@ class IssuedGrant implements Issued { this.#stream = stream; this.#wire = wire; // The presenter withdraws by closing or cancelling its side. - this.closed = wire - .withdrawn(stream) - .then( - () => null, - (err: unknown) => (err instanceof StreamError && err.code === StreamCode.Cancel ? null : error(err)), - ) - .finally(() => { - this.ended = true; - }); + void wire.withdrawn(stream).then( + () => this.#closed.set(null), + (err: unknown) => + this.#closed.set(err instanceof StreamError && err.code === StreamCode.Cancel ? null : error(err)), + ); + } + + get closed(): GetPromise { + return this.#closed; + } + + get ended(): boolean { + return this.#closed.peek() !== undefined; } #write(write: () => Promise) { diff --git a/js/net/src/connection/answered.test.ts b/js/net/src/connection/answered.test.ts index b2c42ecb461..61b36d9d3a1 100644 --- a/js/net/src/connection/answered.test.ts +++ b/js/net/src/connection/answered.test.ts @@ -61,7 +61,7 @@ function closing(refused: string, release: Promise) { } function loop(versions: string[], tokens: Signal) { - return new Reload({ url: URL_, versions, websocket: { enabled: false }, tokens, delay: DELAY }); + return new Reload({ url: URL_, versions, websocket: { enabled: false }, tokens, backoff: DELAY }); } /** Whether `promise` rejected with a session close of `code`, once everything pending has run. */ @@ -229,7 +229,7 @@ test("a connection answers once its loop ends with the abort's error", async () versions: ["moq-lite-07-wip"], websocket: { enabled: false }, tokens, - delay: DELAY, + backoff: DELAY, }); try { await clock.advance(Duration.millis(10)); diff --git a/js/net/src/connection/migrate.test.ts b/js/net/src/connection/migrate.test.ts index cd3149786c2..f9908f52d5b 100644 --- a/js/net/src/connection/migrate.test.ts +++ b/js/net/src/connection/migrate.test.ts @@ -90,7 +90,7 @@ test("an empty GOAWAY migrates the follower to the replacement session", async ( consume, goaway: { handover }, // A session younger than this counts as redirected immediately and backs off first. - delay: { initial: Duration.millis(1) }, + backoff: { initial: Duration.millis(1) }, }); const watched = consume.follow(Path.from("cam")); @@ -136,7 +136,7 @@ test("a replacement that closes mid-handover hands back to the draining session" url, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Duration.millis(1) }, + backoff: { initial: Duration.millis(1) }, }); try { @@ -176,7 +176,7 @@ test("a GOAWAY without a timeout hands over at the configured cap", async () => url, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Duration.millis(1) }, + backoff: { initial: Duration.millis(1) }, }); try { @@ -203,7 +203,7 @@ test("a refused redirect ends the connection instead of reconnecting", async () const clock = new Manual(); const installed = clock.install(); const { dials } = fleet(); - const reload = new Reload({ url, websocket: { enabled: false }, delay: { initial: Duration.millis(1) } }); + const reload = new Reload({ url, websocket: { enabled: false }, backoff: { initial: Duration.millis(1) } }); try { await waitUntil(() => reload.status.peek() === "connected"); @@ -233,7 +233,7 @@ test("a certificate pin refuses a redirect to another host even under follow", a websocket: { enabled: false }, webtransport: { serverCertificateHashes: [{ value: "00".repeat(32) }] }, goaway: { redirect: "follow" }, - delay: { initial: Duration.millis(1) }, + backoff: { initial: Duration.millis(1) }, }); try { @@ -434,7 +434,7 @@ test("the connection's tokens ride every session across a GOAWAY", async () => { websocket: { enabled: false }, versions: [Lite.ALPN_07_WIP], goaway: { handover }, - delay: { initial: Duration.millis(1) }, + backoff: { initial: Duration.millis(1) }, }); try { const token = reload.auth.add("token"); @@ -525,7 +525,7 @@ test.each([ websocket: { enabled: false }, goaway: { handover }, // Every session outlives the healthy bar, so the immediate-redirect damping never applies. - delay: { + backoff: { initial: Duration.millis(10), multiplier: 4, max: Duration.millis(1000), @@ -563,7 +563,7 @@ test("redirect endpoint keys omit userinfo without changing the dial URL", async url: from, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Duration.millis(10) }, + backoff: { initial: Duration.millis(10) }, }); try { @@ -590,7 +590,7 @@ test("a redirect loop stops at the retry window", async () => { url, websocket: { enabled: false }, goaway: { handover }, - delay: { + backoff: { initial: Duration.millis(10), multiplier: 4, max: Duration.millis(1000), @@ -622,7 +622,7 @@ test("a loop no faster than the capped delay migrates without backing off", asyn websocket: { enabled: false }, goaway: { handover }, // Each session lives exactly the cap, so it already redials no faster than the backoff would. - delay: { initial: Duration.millis(10), max: life, healthy: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), max: life, healthy: Duration.millis(10) }, }); try { @@ -645,7 +645,7 @@ test("a one-way rolling restart migrates without backing off", async () => { websocket: { enabled: false }, goaway: { handover }, // Long enough that any backoff would be visible. - delay: { initial: Duration.millis(1000) }, + backoff: { initial: Duration.millis(1000) }, }); try { @@ -669,7 +669,7 @@ test("repeated GOAWAYs back to the same place are restarts, not a loop", async ( websocket: { enabled: false }, goaway: { handover }, // Long enough that any backoff would be visible. - delay: { initial: Duration.millis(300), healthy: Duration.millis(300) }, + backoff: { initial: Duration.millis(300), healthy: Duration.millis(300) }, }); try { @@ -697,7 +697,7 @@ test("a peer restarting through immediate GOAWAYs escalates the backoff but neve websocket: { enabled: false }, goaway: { handover }, // The waits add up to far more than the window, which a restart restarts after each one. - delay: { + backoff: { initial: Duration.millis(10), multiplier: 2, max: Duration.millis(1000), @@ -729,7 +729,7 @@ test("a first session drained before it is healthy keeps retrying once its relay url, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Duration.millis(10), max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), max: Duration.millis(10) }, }); try { diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index 1eb629904ab..be7aa64e90a 100644 --- a/js/net/src/connection/pool.test.ts +++ b/js/net/src/connection/pool.test.ts @@ -338,7 +338,7 @@ test("connection-specific options infer a private loop and origin", async () => const options = [ { webtransport: { congestionControl: "throughput" as const } }, { websocket: { enabled: false } }, - { delay: { timeout: null } }, + { backoff: { timeout: null } }, { timeout: Duration.millis(10_000) }, { publish: origin.consume() }, { consume: origin }, @@ -373,7 +373,7 @@ test("explicit share: true refuses connection-specific options", () => { /share: false/, ); expect(() => new Connection({ share: true, websocket: { enabled: false } })).toThrow(/share: false/); - expect(() => new Connection({ share: true, delay: { timeout: null } })).toThrow(/share: false/); + expect(() => new Connection({ share: true, backoff: { timeout: null } })).toThrow(/share: false/); expect(() => new Connection({ share: true, timeout: Duration.millis(10_000) })).toThrow(/share: false/); } finally { origin.close(); @@ -475,7 +475,7 @@ test("exhausted retries then a new URL recovers a private handle", async () => { url, share: false, websocket: { enabled: false }, - delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(1) }, + backoff: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(1) }, }); try { await advance(2); @@ -492,14 +492,14 @@ test("exhausted retries then a new URL recovers a private handle", async () => { } }); -test("a private partial delay keeps the unlimited retry timeout", async () => { +test("a private partial backoff keeps the unlimited retry timeout", async () => { const relay = stubOutage("throw"); const handle = new Connection({ url, share: false, websocket: { enabled: false }, - delay: { initial: Duration.millis(1000), multiplier: 1, max: Duration.millis(1000) }, + backoff: { initial: Duration.millis(1000), multiplier: 1, max: Duration.millis(1000) }, }); try { await relay.outage(handle); @@ -517,7 +517,12 @@ test("a private handle with an explicitly undefined timeout outlasts the outage" // What a caller building options from optional values produces: the undefined means "the // default", which for a Connection is to retry for as long as the handle is held. - const handle = new Connection({ url, share: false, websocket: { enabled: false }, delay: { timeout: undefined } }); + const handle = new Connection({ + url, + share: false, + websocket: { enabled: false }, + backoff: { timeout: undefined }, + }); try { await relay.outage(handle); const before = relay.attempts(); @@ -868,7 +873,7 @@ test("a private handle's timeout bounds each attempt", async () => { share: false, websocket: { enabled: false }, timeout: Duration.millis(50), - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, }); try { await relay.outage(handle); diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index f28f418ea28..6f7db81b75e 100644 --- a/js/net/src/connection/pool.ts +++ b/js/net/src/connection/pool.ts @@ -29,7 +29,7 @@ import { } from "./connect.ts"; import { DISCOVERY_REMOVED } from "./forward.ts"; import type { Goaway as GoawayType, Handover as HandoverType, Redirect as RedirectType } from "./goaway.ts"; -import { pumpAnnounced, Reload, type ReloadDelay, type ReloadStatus } from "./reload.ts"; +import { type Backoff as BackoffType, pumpAnnounced, Reload, type ReloadStatus } from "./reload.ts"; import type { Session as SessionType } from "./session.ts"; import type { Probe as ProbeType, Stats as StatsType } from "./stats.ts"; import type { Transport as TransportType } from "./transport.ts"; @@ -71,7 +71,7 @@ export interface ConnectionProps { consume?: Origin.Producer; /** Backoff settings for the reconnect loop; an unset field uses its default. */ - delay?: ReloadDelay; + backoff?: BackoffType; /** * Credentials to present, kept apart from the URL; see {@link ConnectProps.tokens}. Pass a @@ -120,7 +120,7 @@ export interface ConnectionProps { * session finishes its groups, and the handle and its origin carry across. A redirect the * `goaway` policy refuses stops the loop like an auth rejection does. * - * Options the pool cannot honor (transport options, delay, timeout, goaway, tokens, a pinned + * Options the pool cannot honor (transport options, backoff, timeout, goaway, tokens, a pinned * certificate, caller-owned origins) use a private loop. An explicit `share: true` * refuses them. A supplied transport cannot reconnect at all; pass it to {@link Connection.connect} * instead. @@ -330,7 +330,7 @@ export class Connection { versions, webtransport: props.webtransport, websocket: props.websocket, - delay: props.delay, + backoff: props.backoff, timeout: props.timeout, goaway: props.goaway, tokens: props.tokens, @@ -456,7 +456,7 @@ export namespace Connection { /** Options for {@link Connection.accept}. @reexport */ export type AcceptProps = AcceptPropsType; /** Backoff settings for a private reconnect loop. @reexport */ - export type Backoff = ReloadDelay; + export type Backoff = BackoffType; /** How a connection hands over to a new session after the relay's GOAWAY. @reexport */ export type Handover = HandoverType; /** What to do with the URI a relay names in its GOAWAY. @reexport */ @@ -518,8 +518,8 @@ function refuse(props?: ConnectionProps): void { if (props.websocket !== undefined) { throw new Error("websocket options cannot be shared; pass share: false"); } - if (props.delay !== undefined) { - throw new Error("delay cannot be shared; pass share: false"); + if (props.backoff !== undefined) { + throw new Error("backoff cannot be shared; pass share: false"); } if (props.tokens !== undefined) { throw new Error("tokens cannot be shared; pass share: false"); @@ -537,7 +537,7 @@ function requiresPrivate(props: ConnectionProps): boolean { return ( props.webtransport !== undefined || props.websocket !== undefined || - props.delay !== undefined || + props.backoff !== undefined || props.tokens !== undefined || props.timeout !== undefined || props.goaway !== undefined || diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index e1e7b364018..15f9dec3782 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -21,7 +21,7 @@ import { closeUnwanted } from "../util/announce.ts"; import { wireOf } from "../wire.ts"; import { type AcceptProps, accept as acceptSession } from "./index.ts"; import { Connection, resetShared } from "./pool.ts"; -import { pumpAnnounced, Redirects, Reload, type ReloadDelay, type ReloadProps } from "./reload.ts"; +import { type Backoff, pumpAnnounced, Redirects, Reload, type ReloadProps } from "./reload.ts"; import type { Session } from "./session.ts"; function accept(transport: WebTransport, url: URL, props: Omit = {}) { @@ -155,7 +155,7 @@ test("a peer that severs immediately keeps escalating the backoff", async () => enabled: true, url, websocket: { enabled: false }, - delay: { + backoff: { initial: Duration.millis(1000), multiplier: 2, max: Duration.millis(1000), @@ -182,7 +182,7 @@ test("a peer that severs immediately keeps escalating the backoff", async () => } }); -test("an explicitly undefined delay field falls back to its default", async () => { +test("an explicitly undefined backoff field falls back to its default", async () => { using clock = manual(); const original = globalThis.WebTransport; const url = new URL("https://example.com/"); @@ -202,7 +202,7 @@ test("an explicitly undefined delay field falls back to its default", async () = enabled: true, url, websocket: { enabled: false }, - delay: { initial: undefined, multiplier: undefined, max: undefined, timeout: null }, + backoff: { initial: undefined, multiplier: undefined, max: undefined, timeout: null }, }); try { await clock.advance(Duration.millis(100)); @@ -265,7 +265,7 @@ test("a follower follows the reconnect on the same handle", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, consume: clientOrigin, }); const watched = clientOrigin.follow(Path.from("late")); @@ -315,7 +315,7 @@ test("an ended auth handle gives up instead of retrying", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, }); const warned = spyOn(console, "warn").mockImplementation(() => {}); try { @@ -359,7 +359,7 @@ test("a page hide after give-up does not retry the failed URL", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, }); try { @@ -407,7 +407,7 @@ for (const code of [SessionCode.Unauthorized, SessionCode.MalformedAuthToken, Se enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, }); const watch = new Effect(); watch.run((effect) => { @@ -473,7 +473,7 @@ test("a first session refused before it is healthy stops the URL, even for repla versions: ["moq-lite-06"], websocket: { enabled: false }, tokens, - delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, }); try { await clock.drive(waitFor(reload.established, (established) => established !== undefined)); @@ -506,7 +506,7 @@ test("a refused credential keeps redialing until the tokens change", async () => versions: ["moq-lite-06"], websocket: { enabled: false }, tokens, - delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }, }); try { // Refused only once a session was healthy: until then, a refusal stops the URL. @@ -555,7 +555,7 @@ test("an unauthorized session close during the first setup stops retrying", asyn websocket: { enabled: false }, tokens: ["old"], // Unlimited retries prove that `error` settles only because the first attempt failed. - delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, }); try { @@ -618,7 +618,7 @@ test("a setup stream reset is not mistaken for an unauthorized session", async ( websocket: { enabled: false }, // Unlimited retries, so a second attempt can only happen because the first failure // was treated as retryable rather than terminal. - delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, + backoff: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: null }, }); try { @@ -666,7 +666,7 @@ test("origins span reconnects: local re-announces, remote re-populates", async ( enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, publish: publishOrigin.consume(), consume: subscribeOrigin, }); @@ -806,7 +806,7 @@ for (const [name, teardown] of Object.entries(teardowns)) { // GOAWAY tuning takes a private loop; the rest share the pool, closing when the linger ends. const handle = new Connection( teardown.goaway - ? { url, delay: { initial: Duration.millis(0) }, goaway: { handover: Duration.millis(60_000) } } + ? { url, backoff: { initial: Duration.millis(0) }, goaway: { handover: Duration.millis(60_000) } } : { url }, ); await waitUntil(() => handle.origin.peek() !== undefined); @@ -966,7 +966,7 @@ test("a retired GOAWAY predecessor still closes by its handover cap", async () = url: new URL("https://example.com/"), websocket: { enabled: false }, publish: origin.consume(), - delay: { initial: Duration.millis(0) }, + backoff: { initial: Duration.millis(0) }, goaway: { handover: Duration.millis(100) }, }); @@ -1157,7 +1157,7 @@ test("a watcher syncs with the server's initial set, and again after a reconnect enabled: true, url, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, }; const reload = viaOrigin ? new Reload({ ...props, consume: clientOrigin }) : undefined; const connection = viaOrigin ? undefined : new Connection({ ...props, share: false }); @@ -1315,7 +1315,7 @@ test("a URL's first attempt failing stops it until the URL changes", async () => websocket: { enabled: false }, timeout: Duration.millis(30), // An unbounded window and a short backoff, so only the first-attempt rule can stop it. - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10), timeout: null }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10), timeout: null }, }); try { await waitUntil(() => plan.dials() === 1); @@ -1351,7 +1351,7 @@ test("an attempt that outlives the connect timeout is retried after the backoff" url, websocket: { enabled: false }, timeout: Duration.millis(50), - delay: { initial: Duration.millis(20), multiplier: 1 }, + backoff: { initial: Duration.millis(20), multiplier: 1 }, }); const unsubscribe = reload.status.subscribe((status) => statuses.push(status)); try { @@ -1378,7 +1378,7 @@ test("an attempt that outlives the connect timeout is retried after the backoff" // A healthy session ends at 0, then every attempt hangs until its 30 ms connect timeout. The // window counts from the end of that session, as moq-tokio's does, and no attempt starts once // it has passed. -const windows: [string, ReloadDelay, number, number][] = [ +const windows: [string, Backoff, number, number][] = [ // Dials at 10, 50, and 90; the last runs past the window and gives up when it fails. [ "an attempt under way finishes past the window", @@ -1396,7 +1396,7 @@ const windows: [string, ReloadDelay, number, number][] = [ // Zero is a real bound, not "unlimited": the session's end gives up without a redial. ["a zero window gives up when the session ends", { initial: Duration.millis(10), timeout: Duration.ZERO }, 0, 0], ]; -for (const [name, delay, gaveUp, hung] of windows) { +for (const [name, backoff, gaveUp, hung] of windows) { test(`retry window: ${name}`, async () => { const clock = new Manual(); const installed = clock.install(); @@ -1409,7 +1409,7 @@ for (const [name, delay, gaveUp, hung] of windows) { url, websocket: { enabled: false }, timeout: Duration.millis(30), - delay: { multiplier: 1, max: Duration.millis(1000), ...delay }, + backoff: { multiplier: 1, max: Duration.millis(1000), ...backoff }, }); try { await outlive(clock, reload, plan); @@ -1441,7 +1441,7 @@ test("retry window: a backoff that fires past the window gives up", async () => url, websocket: { enabled: false }, timeout: Duration.millis(30), - delay: { + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(1000), @@ -1472,7 +1472,7 @@ test("retry window: a backoff that fires past the window gives up", async () => // The first session lives past the default healthy bar so the URL retries at all; each later one // lives 100 ms, so the backoff between them shows how `healthy` scores its end and how `max` caps // the delay, matching moq-tokio's `connect.backoff`. -const backoffs: [string, ReloadDelay, number[]][] = [ +const backoffs: [string, Backoff, number[]][] = [ // Past `initial` but short of the default bar, so each end is a failed attempt. ["a session short of the default healthy bar escalates", {}, [10, 20, 40]], ["a session past the healthy bar resets", { healthy: Duration.millis(50) }, [10, 10, 10]], @@ -1487,7 +1487,7 @@ const backoffs: [string, ReloadDelay, number[]][] = [ ["a zero multiplier keeps the delay constant", { multiplier: 0 }, [10, 10, 10]], ["a fractional multiplier below 1 keeps the delay constant", { multiplier: 0.5 }, [10, 10, 10]], ]; -for (const [name, delay, gaps] of backoffs) { +for (const [name, backoff, gaps] of backoffs) { test(`backoff: ${name}`, async () => { const clock = new Manual(); const installed = clock.install(); @@ -1505,7 +1505,7 @@ for (const [name, delay, gaps] of backoffs) { const reload = new Reload({ url, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 2, max: Duration.millis(1000), ...delay }, + backoff: { initial: Duration.millis(10), multiplier: 2, max: Duration.millis(1000), ...backoff }, }); try { const waited: number[] = []; @@ -1545,7 +1545,7 @@ test("backoff: an uncapped delay saturates instead of overflowing", async () => const reload = new Reload({ url, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 1e300, max: null }, + backoff: { initial: Duration.millis(10), multiplier: 1e300, max: null }, }); try { for (let session = 0; session < 2; session++) { @@ -1567,17 +1567,18 @@ test("backoff: an uncapped delay saturates instead of overflowing", async () => } }); -test("a delay field with no meaning is refused when the loop is built", () => { - const invalid: ReloadDelay[] = [ +test("a backoff field with no meaning is refused when the loop is built", () => { + const invalid: Backoff[] = [ // Zero would count every session as healthy. { healthy: Duration.ZERO }, { multiplier: Number.NaN }, { multiplier: Number.POSITIVE_INFINITY }, ]; - for (const delay of invalid) { - expect(() => new Reload({ url: new URL("https://example.com/"), delay }), String(Object.keys(delay))).toThrow( - RangeError, - ); + for (const backoff of invalid) { + expect( + () => new Reload({ url: new URL("https://example.com/"), backoff }), + String(Object.keys(backoff)), + ).toThrow(RangeError); } }); @@ -1648,7 +1649,7 @@ test("a WebSocket fallback returns to WebTransport once it is reachable", async }); const statuses: string[] = []; - const reload = new Reload({ url, versions: [Lite.ALPN_06], delay: { initial: Duration.ZERO } }); + const reload = new Reload({ url, versions: [Lite.ALPN_06], backoff: { initial: Duration.ZERO } }); const watch = new Effect(); watch.subscribe(reload.status, (status) => statuses.push(status)); try { @@ -1720,7 +1721,7 @@ test("a redirect from the draining WebSocket fallback is followed", async () => }); const warned = spyOn(console, "warn").mockImplementation(() => {}); - const reload = new Reload({ url, versions: [Lite.ALPN_06], delay: { initial: Duration.millis(5_000) } }); + const reload = new Reload({ url, versions: [Lite.ALPN_06], backoff: { initial: Duration.millis(5_000) } }); try { for (let i = 0; i < 10 && reload.established.peek()?.transport !== "websocket"; i++) { await clock.advance(Duration.millis(100)); @@ -1792,7 +1793,7 @@ test("a redirect from the draining WebSocket fallback outlives a replacement tha const reload = new Reload({ url, versions: [Lite.ALPN_06], - delay: { initial: Duration.millis(1_000) }, + backoff: { initial: Duration.millis(1_000) }, goaway: { handover: Duration.millis(60_000) }, }); try { @@ -1846,7 +1847,7 @@ test("a WebSocket session ending restores WebTransport's head start", async () = servers.push(transport.ready.then(() => accept(transport, url))); }); - const reload = new Reload({ url, versions: [Lite.ALPN_06], delay: { initial: Duration.ZERO } }); + const reload = new Reload({ url, versions: [Lite.ALPN_06], backoff: { initial: Duration.ZERO } }); try { for (let i = 0; i < 10 && reload.established.peek()?.transport !== "websocket"; i++) { await clock.advance(Duration.millis(100)); diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index 739d1add081..324af557372 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -41,20 +41,20 @@ const PROBE_MAX = Duration.secs(300); * * The delays carry jitter, so a fleet of tabs knocked offline together doesn't reconnect in * lockstep. Nothing retries until a session to the current URL has been established, which - * takes staying up past {@link ReloadDelay.healthy} or being drained by a GOAWAY, which no + * takes staying up past {@link Backoff.healthy} or being drained by a GOAWAY, which no * refusal sends: an attempt failing, or a session closing sooner, stops that URL with its error. That covers a relay refusing a session right after * accepting it, as it does a rejected token on moq-lite 03 or later. After that, every failure is retried, * including an attempt that outlives {@link ConnectProps.timeout}, until - * {@link ReloadDelay.timeout} runs out, whatever the error, an auth rejection included; only a + * {@link Backoff.timeout} runs out, whatever the error, an auth rejection included; only a * refused GOAWAY redirect stops the current URL sooner. A new URL or a disable/re-enable starts another sequence. * - * A GOAWAY off a session that outlived {@link ReloadDelay.healthy} migrates at once, unless it + * A GOAWAY off a session that outlived {@link Backoff.healthy} migrates at once, unless it * sends the connection back to an endpoint that already redirected it elsewhere and the - * session lived less than {@link ReloadDelay.max} (or {@link ReloadDelay.healthy} when + * session lived less than {@link Backoff.max} (or {@link Backoff.healthy} when * uncapped). Two peers redirecting to each other thus * wait out this backoff and count against the timeout. */ -export type ReloadDelay = { +export type Backoff = { /** The delay before reconnecting (default: 1000ms; zero retries at once). */ initial?: Duration; @@ -120,14 +120,14 @@ export type ReloadProps = Omit< url?: URL | Signal; /** Backoff settings for the reconnect loop; every field falls back to its default. */ - delay?: ReloadDelay; + backoff?: Backoff; /** How to react to the peer's GOAWAY; every field falls back to its default. */ goaway?: Handover; }; /** - * The backoff applied to whichever {@link ReloadDelay} fields a caller leaves out. + * The backoff applied to whichever {@link Backoff} fields a caller leaves out. * * Retries are unlimited by default: a loop that gives up stays offline until something * redials it, and a page usually has nothing that will, so an outage of any length has to @@ -135,7 +135,7 @@ export type ReloadProps = Omit< * sets a timeout to surface a persistent failure on {@link Reload.error}; giving up does not * dispose the loop, and a new URL or a disable/re-enable starts another sequence. */ -const DEFAULT_DELAY: Required = { +const DEFAULT_BACKOFF: Required = { initial: Duration.millis(1000), multiplier: 2, max: Duration.millis(5000), @@ -144,23 +144,23 @@ const DEFAULT_DELAY: Required = { }; /** - * {@link ReloadDelay} resolved against its defaults, with the same meaning as moq-tokio's + * {@link Backoff} resolved against its defaults, with the same meaning as moq-tokio's * backoff. Throws a RangeError for a value that has none. * * Field by field rather than by spread: a caller building `{ initial: maybeInitial }` from an * optional value passes an explicit undefined, which a spread would take as the answer. */ -function pacing(delay: ReloadDelay) { - const initial = delay.initial ?? DEFAULT_DELAY.initial; +function pacing(backoff: Backoff) { + const initial = backoff.initial ?? DEFAULT_BACKOFF.initial; // `null` means no bound, so only `undefined` takes the default. - const cap = delay.max === undefined ? DEFAULT_DELAY.max : delay.max; - const multiplier = delay.multiplier ?? DEFAULT_DELAY.multiplier; - if (!Number.isFinite(multiplier)) throw new RangeError(`invalid delay.multiplier: ${multiplier}`); + const cap = backoff.max === undefined ? DEFAULT_BACKOFF.max : backoff.max; + const multiplier = backoff.multiplier ?? DEFAULT_BACKOFF.multiplier; + if (!Number.isFinite(multiplier)) throw new RangeError(`invalid backoff.multiplier: ${multiplier}`); // Zero would count every session as healthy, resetting the retry window forever under a // peer that drops each one on sight. - const healthy = delay.healthy ?? DEFAULT_DELAY.healthy; - if (healthy.isZero()) throw new RangeError("delay.healthy must be positive"); - const timeout = delay.timeout === undefined ? DEFAULT_DELAY.timeout : delay.timeout; + const healthy = backoff.healthy ?? DEFAULT_BACKOFF.healthy; + if (healthy.isZero()) throw new RangeError("backoff.healthy must be positive"); + const timeout = backoff.timeout === undefined ? DEFAULT_BACKOFF.timeout : backoff.timeout; // A multiplier below 1 means no growth, not a delay that shrinks to nothing. const growth = Math.max(multiplier, 1); @@ -192,7 +192,7 @@ export type ReloadStatus = "connecting" | "connected" | "disconnected"; * redials with exponential backoff. * * The first attempt for a URL fails fast instead: until a session to it has stayed up past - * {@link ReloadDelay.healthy} or been drained by a GOAWAY, a failed attempt or a closed session sets {@link Reload.error} + * {@link Backoff.healthy} or been drained by a GOAWAY, a failed attempt or a closed session sets {@link Reload.error} * rather than retrying, so a setup mistake such as an * untrusted certificate or no version in common surfaces at once. A page opened before its * relay is reachable therefore stays disconnected until a new URL or a disable/re-enable. @@ -307,7 +307,7 @@ export class Reload { consume?: OriginProducer; /** Backoff settings for the reconnect loop; an unset field uses its default. */ - delay: ReloadDelay; + backoff: Backoff; /** How to react to the peer's GOAWAY (not reactive). */ goaway: Handover; @@ -359,7 +359,7 @@ export class Reload { #dialing = false; // The current wait between attempts, doubling per failure, and when the retry window expires. - // Both are undefined between sequences, so a later edit to `delay` applies to the next one. + // Both are undefined between sequences, so a later edit to `backoff` applies to the next one. #delay: Duration | undefined; // When the retry window expires, or null when it never does. #deadline: Instant | null | undefined; @@ -396,9 +396,9 @@ export class Reload { this.enabled = Signal.from(props?.enabled ?? true); this.tokens = Signal.from(props?.tokens ?? []); this.#verdict = new Verdict(this.tokens, this.auth); - this.delay = props?.delay ?? {}; + this.backoff = props?.backoff ?? {}; // Validated here, like the timeout, rather than by every retry. - pacing(this.delay); + pacing(this.backoff); this.goaway = props?.goaway ?? {}; this.redirect = this.#redirect; this.versions = normalizeVersions(props); @@ -928,10 +928,10 @@ export class Reload { if (now().since(connected).ge(this.#pacing().healthy)) this.#establishedHref = href; } - // Resolved per use rather than at construction, so an edit to `delay` (including one that + // Resolved per use rather than at construction, so an edit to `backoff` (including one that // drops a field back to its default) applies to the next retry. #pacing() { - return pacing(this.delay ?? {}); + return pacing(this.backoff ?? {}); } // When a retry window starting `at` expires. diff --git a/js/net/src/connection/session.ts b/js/net/src/connection/session.ts index ed24ed999b3..de180aeb068 100644 --- a/js/net/src/connection/session.ts +++ b/js/net/src/connection/session.ts @@ -92,9 +92,9 @@ export interface Session { readonly draining: GetPromise; /** - * Resolves when the session closes: `null` for a clean close, an `Error.Session` when the + * Settles when the session closes: `null` for a clean close, an `Error.Session` when the * peer closed with a code (e.g. `SessionCode.Unauthorized` for an auth rejection), or the * transport's own failure. Never rejects. */ - closed: Promise; + readonly closed: GetPromise; } diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index cdea17c6291..90096a6800f 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -98,6 +98,9 @@ export class Connection implements Session { // The peer's GOAWAY, read off its SETUP stream. #goaway = new Once(); + // How the session ended: `fromClose` of the transport's close, settled after auth lets go of it. + #closed = new Once(); + /** The implementation the peer advertised; see {@link Session.peerImplementation}. */ readonly peerImplementation: Promise; @@ -190,6 +193,10 @@ export class Connection implements Session { // finds this session still active. const leave = () => this.#auth.close(); void quic.closed.then(leave, leave); + void quic.closed.then( + (info) => this.#closed.set(fromClose(info)), + (err: unknown) => this.#closed.set(error(err)), + ); this.#client = client; this.#auth.violated.subscribe((err) => { @@ -614,8 +621,8 @@ export class Connection implements Session { return this.#goaway; } - /** Resolves when the session closes, decoding the peer's close code; see {@link Session.closed}. */ - get closed(): Promise { - return this.#quic.closed.then(fromClose, (err: unknown) => error(err)); + /** Settles when the session closes, decoding the peer's close code; see {@link Session.closed}. */ + get closed(): GetPromise { + return this.#closed; } } diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index b55d7b1adf9..6976c51e175 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -1,7 +1,7 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; import { Duration, yieldNow } from "@moq/clock"; import { Manual } from "@moq/clock/test"; -import { Signal } from "@moq/signals"; +import { Once, Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; import { accept, connect } from "../connection/index.ts"; @@ -1790,7 +1790,7 @@ class Tokens { issue(value: string): Credential { const token: Credential = { grant: new Signal(undefined), - closed: new Promise(() => {}), + closed: new Once(), answered: Promise.resolve(), close: () => { this.#issued.delete(token); diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index d6ac7f8b6a0..eaa3f3228e0 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -2469,7 +2469,7 @@ test("origin: a blind request ends with its session, and the next session answer enabled: true, url: reconnectUrl, websocket: { enabled: false }, - delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, + backoff: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, consume: clientOrigin, share: false, }); diff --git a/js/net/src/lite/compression.test.ts b/js/net/src/lite/compression.test.ts index 32fe831e108..7263234fbb3 100644 --- a/js/net/src/lite/compression.test.ts +++ b/js/net/src/lite/compression.test.ts @@ -40,9 +40,7 @@ for (const downstream of [ALPN_06, ALPN_07_WIP]) { try { await link(source, destination, downstream); const request = destination.request(Path.from("compressed")); - while (request.active.peek() === undefined) await request.active.changed(); - const active = request.active.peek(); - if (!active) throw new Error("broadcast did not resolve"); + const active = await request.broadcast(); const remote = active.track("data"); expect((await remote.info()).compression).toBe(downstream === ALPN_07_WIP ? "deflate" : "none"); const reader = remote.subscribe({ delay: { max: Duration.millis(1000) } }); diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index c24f2118df2..57fe79fb142 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -168,6 +168,9 @@ export class Connection implements Session { // The peer's GOAWAY. Lite carries no deadline, so only the URI is set. #goaway = new Once(); + // How the session ended: `fromClose` of the transport's close, settled after auth lets go of it. + #closed = new Once(); + /** * The {@link Role} the peer advertised in its SETUP, for a server deciding whether the * peer's authorization grants the direction it intends to use. @@ -239,6 +242,10 @@ export class Connection implements Session { this.#auth.close(); }; void quic.closed.then(leave, leave); + void quic.closed.then( + (info) => this.#closed.set(fromClose(info)), + (err: unknown) => this.#closed.set(error(err)), + ); // Lite-07: a send on this endpoint's Announce Stream failed while the session lives, so // what it said is lost and the session cannot go on, as rs/moq-net closes it. An ending // session's own end says why. @@ -655,9 +662,9 @@ export class Connection implements Session { return this.#goaway; } - /** Resolves when the session closes, decoding the peer's close code; see {@link Session.closed}. */ - get closed(): Promise { - return this.#quic.closed.then(fromClose, (err: unknown) => error(err)); + /** Settles when the session closes, decoding the peer's close code; see {@link Session.closed}. */ + get closed(): GetPromise { + return this.#closed; } } diff --git a/js/net/src/lite/refresh.test.ts b/js/net/src/lite/refresh.test.ts index 393d240e0c1..d85cfe14119 100644 --- a/js/net/src/lite/refresh.test.ts +++ b/js/net/src/lite/refresh.test.ts @@ -41,10 +41,7 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s const announcements = b.routes(); while ((await announcements.next())?.kind !== "start") {} const request = b.request(Path.from("room")); - while (request.active.peek() === undefined) await request.active.changed(); - const active = request.active.peek(); - if (!active) throw new Error("broadcast missing"); - const remote = active.track("data"); + const remote = (await request.broadcast()).track("data"); expect((await remote.info()).refresh).toBe(alpn === ALPN_07_WIP ? 1 : null); const baseline = remote.subscribe(); const group = producer.appendGroup(); diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index 8959eaf7baf..d1a732bf00f 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -760,6 +760,122 @@ test("a pending request fails Unroutable once its discovery syncs without a rout origin.close(); }); +test("awaiting a request's broadcast for a missing path rejects Unroutable", async () => { + const origin = new Producer(); + const wire = wireOf(origin); + const detach = wire.attach(true); + const initialSets: (() => void)[] = []; + const stop = wire.interests((prefix, wanted) => { + if (wanted) initialSets.push(wire.snapshot(prefix)); + }); + const request = origin.request(Path.from("room/missing")); + const answer = request.broadcast(); + await settle(); + for (const synced of initialSets) synced(); + await expect(answer).rejects.toMatchObject({ code: StreamCode.Unroutable }); + expect(await request.closed).toBeInstanceOf(StreamError); + + request.close(); + stop(); + detach(); + origin.close(); +}); + +test("awaiting a request's broadcast resolves, now or once routed", async () => { + const origin = new Producer(); + const routed = origin.route(Path.from("room/now")); + const now = origin.request(Path.from("room/now")); + expect((await now.broadcast()).instance).toBe(routed.instance); + expect(await now.broadcast()).toBe(now.active.peek() as NonNullable>); + + const later = origin.request(Path.from("room/later")); + let resolved = false; + const answer = later.broadcast().then((broadcast) => { + resolved = true; + return broadcast; + }); + await settle(); + expect(resolved).toBe(false); + const route = origin.route(Path.from("room/later")); + expect((await answer).instance).toBe(route.instance); + + for (const handle of [now, later, routed, route]) handle.close(); + origin.close(); +}); + +test("closing a pending request rejects its await with a cancellation", async () => { + const origin = new Producer(); + const request = origin.request(Path.from("room/missing")); + const answer = request.broadcast(); + await settle(); + request.close(); + await expect(answer).rejects.toMatchObject({ code: StreamCode.Cancel }); + expect(await request.closed).toBeNull(); + + // Closing the origin ends a pending request, with its abort or cleanly, and a resolved one. + const pending = origin.request(Path.from("room/pending")); + const aborted = new Producer(); + const blocked = aborted.request(Path.from("room/pending")); + const route = aborted.route(Path.from("room/served")); + const served = aborted.request(Path.from("room/served")); + await served.broadcast(); + const pendingAnswer = pending.broadcast(); + const blockedAnswer = blocked.broadcast(); + await settle(); + const abort = new StreamError(StreamCode.Internal, { message: "shutdown" }); + aborted.close(abort); + await expect(blockedAnswer).rejects.toBe(abort); + expect(served.closed.peek()).toBe(abort); + route.close(); + + // A closed origin answers a new request at once, the same way. + origin.close(); + await expect(pendingAnswer).rejects.toMatchObject({ code: StreamCode.Cancel }); + expect(await pending.closed).toBeNull(); + await expect(origin.request(Path.from("room/late")).broadcast()).rejects.toMatchObject({ + code: StreamCode.Cancel, + }); +}); + +// A handle that is not a thenable survives an async return or a promise resolution, which would +// otherwise take the broadcast out from under the request that owns it. +test("a request is not awaitable, so an async return keeps the handle", async () => { + const origin = new Producer(); + const route = origin.route(Path.from("room")); + const request = origin.request(Path.from("room")); + const returned = await (async () => request)(); + expect(returned).toBe(request); + expect("then" in request).toBe(false); + request.close(); + route.close(); + origin.close(); +}); + +test("the first call fixes a request's answer", async () => { + const origin = new Producer(); + const route = origin.route(Path.from("room")); + const request = origin.request(Path.from("room")); + const broadcast = await request.broadcast(); + route.close(); + await settle(); + // The instance ended, so the request closed, yet a later await keeps the first answer. + expect(request.closed.peek()).not.toBeUndefined(); + expect(await request.broadcast()).toBe(broadcast); + + // Awaited only after it ended, the same request would have rejected. + const again = origin.route(Path.from("room")); + const late = origin.request(Path.from("room")); + await settle(); + again.close(); + await settle(); + expect(late.closed.peek()).not.toBeUndefined(); + await expect(late.broadcast()).rejects.toBeDefined(); + + request.close(); + late.close(); + origin.close(); +}); + // Unlike a Rust origin, which answers for its own table at once, a JS origin usually fronts a // reconnecting connection: no session yet means nothing has synced. test("a pending request waits for a session before concluding absence", async () => { diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index cbe5c57a326..88bff53993f 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -1995,11 +1995,14 @@ export class Producer implements Table { cached.front.close(); } this.#state.materialized.clear(); + // Every open request ends with the origin, pending or resolved, so an await never hangs. + const ended: RequestSlot[] = []; this.#state.requests.update((requests) => { for (const slot of requests.values()) { slot.answer?.close(); slot.answer = undefined; slot.route.set(undefined); + ended.push(slot); } return new Map(); }); @@ -2007,8 +2010,12 @@ export class Producer implements Table { for (const slot of slots) { this.#state.detach(path, slot); slot.route.set(undefined); + ended.push(slot); } } + for (const slot of ended) { + for (const closed of slot.handles) if (closed.peek() === undefined) closed.set(abort ?? null); + } } } @@ -2045,6 +2052,15 @@ let requestHandoff: (request: Request) => Handoff | undefined; /** * An owned request for one publisher instance at a broadcast path; see {@link Consumer.request}. * + * Await {@link broadcast} for the broadcast, as Rust awaits `request(path)`; read {@link active} and + * {@link closed} to follow it reactively instead. The handle is not itself awaitable, so an + * `await` or an async return never takes the broadcast out from under the request that owns it. + * + * ```ts + * const request = origin.request(Path.from("room")); + * const broadcast = await request.broadcast(); + * ``` + * * @public */ export class Requesting { @@ -2067,6 +2083,7 @@ export class Requesting { #dispose: Dispose; #disposed = false; + #answer?: Promise; private constructor( path: Path.Valid, @@ -2084,6 +2101,18 @@ export class Requesting { makeRequesting = (path, active, closed, dispose) => new Requesting(path, active, closed, dispose); } + /** + * Resolves with the broadcast once {@link active} holds one. Rejects with the error + * {@link closed} carries if the request ends first, such as `Unroutable`, or with a + * `StreamCode.Cancel` error if it closed cleanly: this handle or its origin was closed. The + * answer is fixed by the first call, and every later call gets the same one. The request + * still owns the broadcast, so close the request, not only the broadcast, when done. + */ + broadcast(): Promise { + this.#answer ??= answer(this.active, this.closed); + return this.#answer; + } + /** Withdraw the request. The path stays routed for any other open request. Idempotent. */ close(): void { if (this.#disposed) return; @@ -2092,6 +2121,29 @@ export class Requesting { } } +// The first of `active` holding a broadcast or `closed` settling, as a promise. +function answer( + active: Getter, + closed: GetPromise, +): Promise { + return new Promise((resolve, reject) => { + let done = false; + const stops: Dispose[] = []; + const check = () => { + if (done) return; + const ended = closed.peek(); + const value = ended === undefined ? active.peek() : undefined; + if (ended === undefined && !value) return; + done = true; + for (const stop of stops) stop(); + if (value) resolve(value); + else reject(ended ?? new StreamError(StreamCode.Cancel, { message: "request closed" })); + }; + check(); + if (!done) stops.push(active.subscribe(check), closed.subscribe(check)); + }); +} + /** * An owned follower of the publisher instances announced at a broadcast path; see {@link Consumer.follow}. * @@ -2236,7 +2288,7 @@ export class Consumer implements Reader { * session's discovery has synced without a route for it, and can use a session without * discovery instead. With no session attached, such as between reconnects, it waits. Once resolved it keeps * that instance, ending when the instance stops serving. Use {@link follow} to move on - * to the next one. + * to the next one. Await the handle for the broadcast, or the error ending it first. */ request(path: Path.Valid, options: RequestOptions = {}): Requesting { return this.#resolve(path, options.instance, false); diff --git a/quest/m2/README.md b/quest/m2/README.md index 01f7bd4ca72..bba3890f694 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -57,8 +57,7 @@ removal, a rename, or a wire, catalog, or format change that is free until [the WHEP pull's announcement](/quest/m2/whep-pull-announce.md), and [upstream str0m](https://github.com/moq-dev/moq/pull/8963), which reverses the 2026-10-30 vendoring. -- **JS and browser.** [`@moq/net`](/quest/m2/js-net-api.md), - and [signals](/quest/m2/signals-semantics.md). +- **JS and browser.** [signals](/quest/m2/signals-semantics.md). - **Bindings.** [The C API as `libmoq`](/quest/m2/libmoq-name.md), reversing 2026-10-25. The bindings break twice by decision: at 0.22, and again at [the exporter switch](/quest/m3/ffi-exporter.md). diff --git a/quest/m2/js-net-api.md b/quest/m2/js-net-api.md deleted file mode 100644 index 384a9e4c50e..00000000000 --- a/quest/m2/js-net-api.md +++ /dev/null @@ -1,85 +0,0 @@ -# [M] @moq/net requests are awaitable, and its last odd names match Rust - -## Goal - -Three `@moq/net` shapes change before the cut freezes them: - -- `await origin.request(path)` returns the `Broadcast.Consumer`, or throws - the refusal, as `origin.request(path).await?` does in Rust. The handle - keeps `active`, `closed`, and `close()` for reactive callers. - `js/net/examples/subscribe.ts` and every hand-rolled wait loop use it. -- `Connection.Props.delay`, the reconnect backoff, is named `backoff`. -- `Connection.Session.closed` and `Auth.Credential.closed` are - `GetPromise`, so a caller can peek them, as on every other - handle. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ `Origin.Requesting` is a thenable that settles once (rejected: - `request()` returning a bare `Promise` while only `follow()` returns a - handle, which breaks the entry `@moq/watch` shares between the two; - keeping the handle and only fixing the example). Reactive callers lose - nothing, and one-shot callers stop writing a loop that never ends. -- ✅ `delay` becomes `backoff` (rejected: keep). Rust, moq-tokio, and - moq-ffi all say `backoff`, and `delay` already means two other things in - this package. -- ✅ Both `closed` fields become `GetPromise` (rejected: keep). It is the - package's own lifecycle rule. - -Facts found by the audit, re-checked at `80ca9787e3`: - -- `Requesting` (`js/net/src/origin.ts:2022`) holds - `active: Getter` and - `closed: GetPromise`. A refused request settles `closed` and - leaves `active` undefined: its doc says it "fails `Unroutable` while - pending once discovery syncs without a route". Rust's `Requesting` - resolves to the broadcast or the error (`poll_ok`, - `rs/moq-net/src/model/origin.rs:7191`). -- The package's hello world waits on `active.changed()` alone - (`js/net/examples/subscribe.ts:12-16`), so it hangs when the broadcast - does not exist. `grep 'active\.changed()'` over `js`, `demo`, and `test` - finds 26 waits; 17 files outside tests hold one, and only - `test/interop/clients/js-native/replace.ts` and `claims.ts` also watch - `closed`. -- `Once` is already a thenable over a signal - (`js/signals/src/index.ts:374`), so the pattern exists. -- `Connection.Props.delay` is `js/net/src/connection/pool.ts:74`, typed - `ReloadDelay` and re-exported as `Connection.Backoff` (`pool.ts:419`). - Rust: `pub backoff: Backoff` (`rs/moq-net/src/reconnect.rs:174`). The - other two meanings of `delay`: `WebSocketProps.delay`, the fallback's head - start, and `Track.Subscription.delay`, the `{min, max}` playout bound. - No caller outside `js/net` sets the reconnect option. -- `Connection.Session.closed` is a mutable `Promise` - (`js/net/src/connection/session.ts:99`) and `Auth.Credential.closed` a - `PromiseLike` (`js/net/src/auth.ts:56`). `js/AGENTS.md`: - "Terminal state is one `closed: GetPromise`". - -For the PR: - -- Awaiting resolves once `active` first holds a broadcast and rejects with - the `Error` that `closed` carries when the request ends first. `closed` - can also settle `null` while pending, when the caller closes the handle; - recommended: that rejects too, with one named cancellation error, so an - `await` never hangs. `Following` stays a plain handle: it never settles. -- Replace every loop the grep above lists with the `await`, starting with - the example and `test/smoke/clients/js-native/subscribe.ts`. Add a test - that awaiting a request for a missing broadcast rejects `Unroutable`. -- Rename the option, the `ReloadDelay` type to match its `Backoff` export, - the "delay cannot be shared" refusal in `pool.ts`, and `DEFAULT_DELAY`. - Leave the two other `delay` options alone. -- `Session.closed` also becomes `readonly`. Recommended, not decided: - `Auth.Issued.closed` and the `@internal` `Auth.Request.closed` - (`auth.ts:78`, `:109`) take the same type in the same PR, since they are - the only other `PromiseLike` terminal fields. -- Update `js/net/api/*.api.md` and `js/net/MIGRATE.md`, and any doc page - that shows the wait loop. - -Public API: breaking for `@moq/net`: `Connection.Props.delay` is renamed. -`Requesting` gains `then` and the two `closed` fields widen, both -compatible with code that awaits them. Wire: none. - -## Related - -- [@moq/net addresses groups by start](/quest/m2/time-addressing/js.md) - the other `@moq/net` rename before the cut diff --git a/test/audio-quality/clients/js/src/recorder.ts b/test/audio-quality/clients/js/src/recorder.ts index 1fc130fcd23..ab447bd3af2 100644 --- a/test/audio-quality/clients/js/src/recorder.ts +++ b/test/audio-quality/clients/js/src/recorder.ts @@ -75,11 +75,7 @@ async function record(): Promise { }); const request = origin.request(Moq.Path.from(required("broadcast"))); - let broadcast = request.active.peek(); - while (!broadcast) { - await request.active.changed(); - broadcast = request.active.peek(); - } + const broadcast = await request.broadcast(); let root: Catalog.Root | undefined; for await (const { value: update } of Catalog.watch(broadcast)) { diff --git a/test/datagram-tracks/client.ts b/test/datagram-tracks/client.ts index 5150942b800..3405f68b99f 100644 --- a/test/datagram-tracks/client.ts +++ b/test/datagram-tracks/client.ts @@ -119,8 +119,7 @@ try { } announcements.close(); const request = origin.consume().request(Moq.Path.from("dg")); - let broadcast = request.active.peek(); - while (!broadcast) broadcast = await request.active.changed(); + const broadcast = await request.broadcast(); const audio = broadcast.datagrams("audio"); audio.setPriority(PRIORITY); @@ -148,7 +147,8 @@ try { for (const [i, want] of EVENTS.entries()) { const got = eventsGot[i]; assert.equal(got.sequence, want.sequence, "events sequence"); - assert.equal(got.timestamp, undefined, "an untimed datagram has no timestamp"); + assert.equal(got.timestamp.scale, undefined, "an untimed datagram's timestamp is unscaled"); + assert.equal(got.timestamp.value, Number(want.sequence), "an unscaled timestamp is its sequence"); assert.deepEqual([...got.payload], want.payload, "events payload"); } const group = await track.recvGroup(); diff --git a/test/interop/clients/js/src/close.ts b/test/interop/clients/js/src/close.ts index 17cae96972e..7385af7292b 100644 --- a/test/interop/clients/js/src/close.ts +++ b/test/interop/clients/js/src/close.ts @@ -56,7 +56,7 @@ export async function refusedWebSocket(relay: string): Promise { const connection = new Connection({ url, share: false, - delay: { initial: Duration.millis(10), max: Duration.millis(10), timeout: null }, + backoff: { initial: Duration.millis(10), max: Duration.millis(10), timeout: null }, }); // The refused session counted as connected first; a second one means the handle redialed. let connected = 0; diff --git a/test/max-age/client.ts b/test/max-age/client.ts index 5bca4546dab..4e9e51b5a9e 100644 --- a/test/max-age/client.ts +++ b/test/max-age/client.ts @@ -43,9 +43,7 @@ try { if (event.kind === "present" && event.prefix === "age") break; } const request = origin.consume().request(Path.from("age")); - let broadcast = request.active.peek(); - while (!broadcast) broadcast = await request.active.changed(); - assert(broadcast); + const broadcast = await request.broadcast(); for (const [i, age] of ages.entries()) { const track = broadcast.track(String(i)).subscribe(); // moq-transport never sends MAX_CACHE_DURATION (it would expire the newest group too), diff --git a/test/stream-credit/src/main.ts b/test/stream-credit/src/main.ts index 6a9f45c9b35..be771a56d20 100644 --- a/test/stream-credit/src/main.ts +++ b/test/stream-credit/src/main.ts @@ -35,9 +35,7 @@ window.subscribe = async (plan) => { websocket: { enabled: false }, }); const request = origin.request(Moq.Path.from(plan.broadcast)); - let broadcast = request.active.peek(); - while (!broadcast) broadcast = await request.active.changed(); - const active = broadcast; + const active = await request.broadcast(); const subscribers = plan.tracks.map((track) => active.track(track.name).subscribe({ diff --git a/test/stream-limits/client.ts b/test/stream-limits/client.ts index f4963fde612..a3bd20459d0 100644 --- a/test/stream-limits/client.ts +++ b/test/stream-limits/client.ts @@ -35,10 +35,7 @@ try { } else { const session = await Moq.Connection.connect({ url, consume: origin }); const request = origin.request(path); - let broadcast = request.active.peek(); - while (!broadcast) broadcast = await request.active.changed(); - assert(broadcast); - const active = broadcast; + const active = await request.broadcast(); // Each subscription is a stream to the publisher; each group, one from the relay. const tracks = Array.from({ length: count }, (_, i) => active.track(String(i)).subscribe()); const groups = await Promise.all(