From aa71b101a0ed459027c03d2375259b73f99cabb3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:15:42 -0800 Subject: [PATCH 1/6] chore(quest): claim quest/m2/js-net-api.md Quest-Claim: 2e6aee30d4faba44 From cb57ca6118b50ee8e41744ddcdb07f99f5f48aa6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:33:00 -0800 Subject: [PATCH 2/6] feat(net)!: a request is awaitable, the reconnect option is backoff, and closed fields are GetPromise Co-Authored-By: Claude Opus 5.5 --- doc/lib/js/net.md | 2 +- js/net/bench/refresh.ts | 4 +- js/net/examples/subscribe.ts | 15 ++-- js/net/src/auth.ts | 8 +- js/net/src/auth_session.ts | 41 ++++----- js/net/src/connection/migrate.test.ts | 26 +++--- js/net/src/connection/pool.test.ts | 14 ++-- js/net/src/connection/pool.ts | 16 ++-- js/net/src/connection/reload.test.ts | 68 +++++++-------- js/net/src/connection/reload.ts | 44 +++++----- js/net/src/connection/session.ts | 4 +- js/net/src/ietf/connection.ts | 13 ++- js/net/src/ietf/publisher.test.ts | 4 +- js/net/src/integration.test.ts | 2 +- js/net/src/lite/compression.test.ts | 4 +- js/net/src/lite/connection.ts | 13 ++- js/net/src/lite/refresh.test.ts | 5 +- js/net/src/origin-request.test.ts | 84 +++++++++++++++++++ js/net/src/origin.ts | 47 ++++++++++- test/audio-quality/clients/js/src/recorder.ts | 6 +- test/datagram-tracks/client.ts | 3 +- test/interop/clients/js/src/close.ts | 2 +- test/max-age/client.ts | 4 +- test/stream-credit/src/main.ts | 4 +- test/stream-limits/client.ts | 5 +- 25 files changed, 280 insertions(+), 158 deletions(-) diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 4f8bad7637c..fa54d09113d 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. 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 origin.request(path)` returns that broadcast or throws why none came, as Rust's `request(path).await` does; the request 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/bench/refresh.ts b/js/net/bench/refresh.ts index 9d40485d114..4a066c31add 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; 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..8a20d90d257 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; // 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 c6bbd6a3108..b273a1233d0 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"; @@ -169,7 +169,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; @@ -177,16 +176,13 @@ class Token implements Pending { ended = 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; @@ -209,7 +205,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 { @@ -436,7 +436,7 @@ class PeerRequest implements Request { this.#issued = issued; } - get closed(): Promise { + get closed(): GetPromise { return this.#issued.closed; } @@ -460,8 +460,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(); @@ -475,15 +474,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/migrate.test.ts b/js/net/src/connection/migrate.test.ts index 2d87e44236c..24dc2a56dd7 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 { @@ -174,7 +174,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 { @@ -201,7 +201,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"); @@ -231,7 +231,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 { @@ -430,7 +430,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"); @@ -521,7 +521,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), @@ -559,7 +559,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 { @@ -586,7 +586,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), @@ -618,7 +618,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 { @@ -641,7 +641,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 { @@ -665,7 +665,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 { @@ -693,7 +693,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), diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index f04a407bbd1..5632f3840b5 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,7 @@ 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(); @@ -864,7 +864,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 c3ae5bea28c..bf6dd841fa0 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 { Drain as DrainType, GoawayProps, Redirect as RedirectType } from "./goaway.ts"; -import { pumpAnnounced, Reload, type ReloadDelay, type ReloadStatus } from "./reload.ts"; +import { pumpAnnounced, Reload, type Backoff as BackoffType, 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. @@ -328,7 +328,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, @@ -416,7 +416,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 reacts to the relay's GOAWAY. @reexport */ export type Goaway = GoawayProps; /** What to do with the URI a relay names in its GOAWAY. @reexport */ @@ -478,8 +478,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"); @@ -497,7 +497,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 b334f0f9749..0663ffd8327 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 { pumpAnnounced, Redirects, Reload, type Backoff, 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")); @@ -314,7 +314,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 { @@ -357,7 +357,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 { @@ -405,7 +405,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) => { @@ -469,7 +469,7 @@ test("a refused credential replaced since its dial redials with the new one", as 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)); @@ -498,7 +498,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 is up: a URL's first attempt failing stops it whatever the cause. @@ -546,7 +546,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 { @@ -609,7 +609,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 { @@ -656,7 +656,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, }); @@ -795,7 +795,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); @@ -955,7 +955,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) }, }); @@ -1146,7 +1146,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 }); @@ -1303,7 +1303,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); @@ -1339,7 +1339,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 { @@ -1366,7 +1366,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", @@ -1384,7 +1384,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(); @@ -1397,7 +1397,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); @@ -1429,7 +1429,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), @@ -1459,7 +1459,7 @@ test("retry window: a backoff that fires past the window gives up", async () => // Each session 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]], @@ -1474,7 +1474,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(); @@ -1492,7 +1492,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[] = []; @@ -1532,7 +1532,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++) { @@ -1553,15 +1553,15 @@ 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( + for (const backoff of invalid) { + expect(() => new Reload({ url: new URL("https://example.com/"), backoff }), String(Object.keys(backoff))).toThrow( RangeError, ); } @@ -1634,7 +1634,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 { @@ -1706,7 +1706,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)); @@ -1778,7 +1778,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 { @@ -1832,7 +1832,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 52406fe6928..91d74f282a8 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -43,16 +43,16 @@ const PROBE_MAX = Duration.secs(300); * lockstep. Nothing retries until a session to the current URL has been established: the * first attempt failing stops that URL with its error. 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; @@ -118,14 +118,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?: GoawayProps; }; /** - * 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 @@ -133,7 +133,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), @@ -142,23 +142,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); @@ -301,7 +301,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: GoawayProps; @@ -353,7 +353,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; @@ -388,9 +388,9 @@ export class Reload { this.url = Signal.from(props?.url); this.enabled = Signal.from(props?.enabled ?? true); this.tokens = Signal.from(props?.tokens ?? []); - 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); @@ -891,10 +891,10 @@ export class Reload { if (draining) this.#end(draining); } - // 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 b7fada73658..913c93ea313 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 b478adf752d..e4a32d8c548 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 b1ae87bc172..2dc39cedc87 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -2419,7 +2419,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..ab40ec64297 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; 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 3e3ed288aed..02390e0fccc 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -163,6 +163,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. @@ -229,6 +232,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)), + ); // Before lite-07 the peer can't ask for hidden routes, so a client publishes none of // them, and a socket endpoint behind it is unreachable. A server leaves it to the // client, whose origin holds that endpoint. @@ -601,9 +608,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..9f841039bce 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).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..fea2e8619cb 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -760,6 +760,90 @@ test("a pending request fails Unroutable once its discovery syncs without a rout origin.close(); }); +test("awaiting a request for a missing broadcast 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 = (async () => await request)(); + 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 resolves with its broadcast, 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).instance).toBe(routed.instance); + expect(await now).toBe(now.active.peek() as NonNullable>); + + const later = origin.request(Path.from("room/later")); + let resolved = false; + const answer = later.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 = (async () => await request)(); + await settle(); + request.close(); + await expect(answer).rejects.toMatchObject({ code: StreamCode.Cancel }); + expect(await request.closed).toBeNull(); + + // A closed origin answers a new request at once, the same way. + origin.close(); + await expect((async () => await origin.request(Path.from("room/late")))()).rejects.toMatchObject({ + code: StreamCode.Cancel, + }); +}); + +test("the first await 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; + 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).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((async () => await late)()).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 15997f45e1b..1d288d911e4 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -2045,9 +2045,16 @@ let requestHandoff: (request: Request) => Handoff | undefined; /** * An owned request for one publisher instance at a broadcast path; see {@link Consumer.request}. * + * Await it for the broadcast, as Rust awaits `request(path)`; read {@link active} and + * {@link closed} to follow it reactively instead. + * + * ```ts + * const broadcast = await origin.request(Path.from("room")); + * ``` + * * @public */ -export class Requesting { +export class Requesting implements PromiseLike { /** The requested path. */ readonly path: Path.Valid; @@ -2067,6 +2074,7 @@ export class Requesting { #dispose: Dispose; #disposed = false; + #answer?: Promise; private constructor( path: Path.Valid, @@ -2084,6 +2092,21 @@ 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 await, and every later await gets the same one. The request + * still owns the broadcast, so close the request, not only the broadcast, when done. + */ + // Read synchronously by `await`, before it schedules the call, so the answer starts from the + // state the caller just saw. + // biome-ignore lint/suspicious/noThenProperty: a request is awaitable, as in Rust. + get then(): Promise["then"] { + this.#answer ??= answer(this.active, this.closed); + return this.#answer.then.bind(this.#answer); + } + /** Withdraw the request. The path stays routed for any other open request. Idempotent. */ close(): void { if (this.#disposed) return; @@ -2092,6 +2115,26 @@ 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 +2279,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/test/audio-quality/clients/js/src/recorder.ts b/test/audio-quality/clients/js/src/recorder.ts index f2116966dfe..aa771c6e762 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; let root: Catalog.Root | undefined; for await (const update of Catalog.watch(broadcast)) { diff --git a/test/datagram-tracks/client.ts b/test/datagram-tracks/client.ts index 5150942b800..2ce917a37b4 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; const audio = broadcast.datagrams("audio"); audio.setPriority(PRIORITY); diff --git a/test/interop/clients/js/src/close.ts b/test/interop/clients/js/src/close.ts index 7140ffad766..4540f0a9329 100644 --- a/test/interop/clients/js/src/close.ts +++ b/test/interop/clients/js/src/close.ts @@ -55,7 +55,7 @@ export async function refusedWebSocket(relay: string): Promise { const connection = new Connection({ url, share: false, - delay: { initial: Duration.millis(200), max: Duration.millis(200), timeout: Duration.secs(2) }, + backoff: { initial: Duration.millis(200), max: Duration.millis(200), timeout: Duration.secs(2) }, }); // Every refused session counted as connected first; a second one proves the handle redialed. let connected = 0; diff --git a/test/max-age/client.ts b/test/max-age/client.ts index 5bca4546dab..4831d003cb8 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; 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..ade94e4f8a2 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; 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..a0dd26ff67a 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; // 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( From 7a7034a1780cf3d2e4b0ae5965b6e102183b6678 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:35:33 -0800 Subject: [PATCH 3/6] chore(net): format and regenerate the API report Co-Authored-By: Claude Opus 5.5 --- js/net/api/index.api.md | 9 +++++---- js/net/src/connection/pool.test.ts | 7 ++++++- js/net/src/connection/pool.ts | 2 +- js/net/src/connection/reload.test.ts | 9 +++++---- js/net/src/origin.ts | 5 ++++- 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 0a60027e0ec..0d9ff286708 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 { @@ -179,8 +179,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.Goaway; publish?: Origin.Consumer; @@ -200,7 +200,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; @@ -509,11 +509,12 @@ export namespace Origin { export interface RequestOptions { instance?: Instance.Valid; } - export class Requesting { + export class Requesting implements PromiseLike { readonly active: Signals.Getter; close(): void; readonly closed: Signals.GetPromise; readonly path: Path.Valid; + get then(): Promise["then"]; } export class Route { [Symbol.dispose](): void; diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index 5632f3840b5..a3956b77a05 100644 --- a/js/net/src/connection/pool.test.ts +++ b/js/net/src/connection/pool.test.ts @@ -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 }, backoff: { timeout: undefined } }); + const handle = new Connection({ + url, + share: false, + websocket: { enabled: false }, + backoff: { timeout: undefined }, + }); try { await relay.outage(handle); const before = relay.attempts(); diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index bf6dd841fa0..a40b62acc82 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 { Drain as DrainType, GoawayProps, Redirect as RedirectType } from "./goaway.ts"; -import { pumpAnnounced, Reload, type Backoff as BackoffType, 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"; diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index 0663ffd8327..dbe06446425 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 Backoff, 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 = {}) { @@ -1561,9 +1561,10 @@ test("a backoff field with no meaning is refused when the loop is built", () => { multiplier: Number.POSITIVE_INFINITY }, ]; for (const backoff of invalid) { - expect(() => new Reload({ url: new URL("https://example.com/"), backoff }), String(Object.keys(backoff))).toThrow( - RangeError, - ); + expect( + () => new Reload({ url: new URL("https://example.com/"), backoff }), + String(Object.keys(backoff)), + ).toThrow(RangeError); } }); diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index 1d288d911e4..f0787fb0f0b 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -2116,7 +2116,10 @@ export class Requesting implements PromiseLike { } // The first of `active` holding a broadcast or `closed` settling, as a promise. -function answer(active: Getter, closed: GetPromise): Promise { +function answer( + active: Getter, + closed: GetPromise, +): Promise { return new Promise((resolve, reject) => { let done = false; const stops: Dispose[] = []; From 5ed981366da88bbe2abfd6e67f475d9880972d9d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:44:29 -0800 Subject: [PATCH 4/6] test(datagram-tracks): an untimed datagram's timestamp is unscaled; finish the quest Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 2 +- quest/m2/js-net-api.md | 87 ---------------------------------- quest/m2/unused-api/js.md | 1 - test/datagram-tracks/client.ts | 3 +- 4 files changed, 3 insertions(+), 90 deletions(-) delete mode 100644 quest/m2/js-net-api.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..a9b0a11b216 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -70,7 +70,7 @@ removal, a rename, or a wire, catalog, or format change that is free until [gateway admission](/quest/m2/gateway-align.md), and [upstream str0m](/quest/m2/str0m-upstream.md), which reverses the 2026-10-30 vendoring. -- **JS and browser.** [`@moq/net`](/quest/m2/js-net-api.md), +- **JS and browser.** [signals](/quest/m2/signals-semantics.md), [`@moq/ui`](/quest/m2/ui-private.md), and [room, publish, and OBS names](/quest/m2/browser-packages.md). - **Bindings.** [Open selectors](/quest/m2/ffi-open-selectors.md), diff --git a/quest/m2/js-net-api.md b/quest/m2/js-net-api.md deleted file mode 100644 index 0b256320f19..00000000000 --- a/quest/m2/js-net-api.md +++ /dev/null @@ -1,87 +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 - -- [Reconnect, absent means off](/quest/m2/reconnect-off.md) - changes the same reconnect options and names GOAWAY once -- [@moq/net addresses groups by start](/quest/m2/time-addressing/js.md) - the other `@moq/net` rename before the cut -- [Unused @moq/net exports](/quest/m2/unused-api/js.md) - the removals that land beside these diff --git a/quest/m2/unused-api/js.md b/quest/m2/unused-api/js.md index ce0c6613ffa..a81163ca604 100644 --- a/quest/m2/unused-api/js.md +++ b/quest/m2/unused-api/js.md @@ -101,5 +101,4 @@ above are removed or hidden, and `rescale` moves from `Datagram` to ## Related -- [@moq/net requests are awaitable](/quest/m2/js-net-api.md) - the other `@moq/net` API changes before the cut - [Broadcast requests](/quest/m4/net-broadcast-requests.md) - republishes `Track.Request` with its accessor diff --git a/test/datagram-tracks/client.ts b/test/datagram-tracks/client.ts index 2ce917a37b4..b1b47594cae 100644 --- a/test/datagram-tracks/client.ts +++ b/test/datagram-tracks/client.ts @@ -147,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(); From fc9794630f6fe45b86d73979b9c36c49f26023f0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 08:18:29 -0800 Subject: [PATCH 5/6] fix(net): closing an origin ends every open request, pending ones included Co-Authored-By: Claude Opus 5.5 --- js/net/src/origin-request.test.ts | 18 ++++++++++++++++++ js/net/src/origin.ts | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index fea2e8619cb..6dff368f4b6 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -812,8 +812,26 @@ test("closing a pending request rejects its await with a cancellation", async () 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; + const pendingAnswer = (async () => await pending)(); + const blockedAnswer = (async () => await blocked)(); + 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((async () => await origin.request(Path.from("room/late")))()).rejects.toMatchObject({ code: StreamCode.Cancel, }); diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index f0787fb0f0b..355bb3df5eb 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); + } } } From 537de6e5fbc130d7e092c427fa3af1e8281e0fb4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 17 Nov 2026 04:01:12 -0800 Subject: [PATCH 6/6] test(net): the request tests await broadcast() --- js/net/src/origin-request.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index ac0a7b82a67..d1a732bf00f 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -818,9 +818,9 @@ test("closing a pending request rejects its await with a cancellation", async () 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; - const pendingAnswer = (async () => await pending)(); - const blockedAnswer = (async () => await blocked)(); + await served.broadcast(); + const pendingAnswer = pending.broadcast(); + const blockedAnswer = blocked.broadcast(); await settle(); const abort = new StreamError(StreamCode.Internal, { message: "shutdown" }); aborted.close(abort);