Skip to content
2 changes: 1 addition & 1 deletion doc/lib/js/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 4 additions & 3 deletions js/net/api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export namespace Auth {
export interface Credential {
readonly answered: PromiseLike<void>;
close(): void;
readonly closed: PromiseLike<Error | null>;
readonly closed: Signals.GetPromise<Error | null>;
readonly grant: Signals.Getter<Auth.Grant | undefined>;
}
export class Duplicate extends Error {
Expand Down Expand Up @@ -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<boolean>;
goaway?: Connection.Handover;
publish?: Origin.Consumer;
Expand All @@ -199,7 +199,7 @@ export namespace Connection {
announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer;
readonly auth: Auth.Handle;
close(): Promise<void>;
closed: Promise<Error | null>;
readonly closed: Signals.GetPromise<Error | null>;
readonly draining: Signals.GetPromise<Connection.Goaway>;
readonly peerImplementation: Promise<string | undefined>;
readonly probe: Signals.Getter<Connection.Probe>;
Expand Down Expand Up @@ -503,6 +503,7 @@ export namespace Origin {
}
export class Requesting {
readonly active: Signals.Getter<Broadcast.Consumer | undefined>;
broadcast(): Promise<Broadcast.Consumer>;
close(): void;
readonly closed: Signals.GetPromise<Error | null>;
readonly path: Path.Valid;
Expand Down
4 changes: 1 addition & 3 deletions js/net/bench/refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down
15 changes: 6 additions & 9 deletions js/net/examples/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (;;) {
Expand All @@ -40,7 +37,7 @@ async function main() {
}

track.close();
broadcast.close();
request.close();
await connection.close();
origin.close();
}
Expand Down
8 changes: 4 additions & 4 deletions js/net/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<Error | null>;
readonly closed: GetPromise<Error | null>;
/**
* 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),
Expand All @@ -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<Error | null>;
readonly closed: GetPromise<Error | null>;
/**
* Grant the token until the returned {@link Issued} is revoked or closed.
*
Expand Down Expand Up @@ -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<Error | null>;
readonly closed: GetPromise<Error | null>;
}

/**
Expand Down
41 changes: 22 additions & 19 deletions js/net/src/auth_session.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<Grant | undefined>(undefined);
readonly closed: Promise<Error | null>;
readonly answered: Promise<void>;
readonly bytes: Uint8Array;

Expand All @@ -180,16 +179,13 @@ class Token implements Pending {
inband = false;

#state: HandleState;
#close!: (err: Error | null) => void;
#closed = new Once<Error | null>();
#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;
Expand All @@ -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<Error | null> {
return this.#closed;
}

get held(): boolean {
Expand Down Expand Up @@ -451,7 +451,7 @@ class PeerRequest implements Request {
this.#issued = issued;
}

get closed(): Promise<Error | null> {
get closed(): GetPromise<Error | null> {
return this.#issued.closed;
}

Expand All @@ -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<Error | null>;
readonly #closed = new Once<Error | null>();
#stream: Stream;
#wire: AuthWire;
#writes = Promise.resolve();
Expand All @@ -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<Error | null> {
return this.#closed;
}

get ended(): boolean {
return this.#closed.peek() !== undefined;
}

#write(write: () => Promise<void>) {
Expand Down
4 changes: 2 additions & 2 deletions js/net/src/connection/answered.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function closing(refused: string, release: Promise<void>) {
}

function loop(versions: string[], tokens: Signal<readonly string[]>) {
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. */
Expand Down Expand Up @@ -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));
Expand Down
28 changes: 14 additions & 14 deletions js/net/src/connection/migrate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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");
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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 {
Expand All @@ -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),
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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 {
Expand Down
Loading